﻿<?php
// error_reporting(-1);
// ini_set('display_errors', 1);
session_start();

include_once 'config.php';
require_once './functions.php';
require_once './vendor/autoload.php';
use Vimeo\Vimeo;
//use Twilio\Rest\Client;
use Aws\S3\S3Client;
use Aws\Exception\AwsException;

$s3 = new S3Client([
    'version' => 'latest',
    'region' => 'ap-south-1',
    'credentials' => [
        'key' => 'AKIARYGLTJQZJH5LDIWU',
        'secret' => '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',
    ],
]);

//to execute subscription code set
$subscriptionCode = "required";
//to don't execute subscription code set
// $subscriptionCode = "notRequired";
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header("Access-Control-Allow-Headers: Content-Type, Authorization");
header('Acscess-Control-Max-Age: 1000');
ini_set('memory_limit', '1024M');
date_default_timezone_set("Asia/Kolkata");

$techIssueTolerance = 60;

if (isset($_GET['getAllUsers'])) {
    $query = mysqli_query($databaseConnection, "select * from users");
    $values = array();
    while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
        $values[] = array(
            'uid' => $row['id'],
            'username' => $row['userName'],
            'fname' => $row['firstName'],
            'lname' => $row['lastName'],
            'mobile' => $row['mobileNumber'],
            'active' => $row['active'],
            'email' => $row['emailId'],
            'verificationStatus' => $row['verificationStatus'],
            'verificationLink' => $row['verificationLink']
        );
    }
} elseif (isset($_GET['getInterviewNamelists'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $panelId = $json['panelId'];
        $interviewName = mysqli_query($databaseConnection, "SELECT id,name FROM `interview` where isActive='Y' and deleted_at is null order by name");
        $interviewNameList = mysqli_fetch_all($interviewName, MYSQLI_ASSOC);
        $to_encode = array(
            'interviewNameList' => $interviewNameList,
            'status' => 1,
        );
    }
    echo json_encode($to_encode);

} elseif (isset($_GET['getPanelInfo'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $panelId = $json['panelId'];
        $interviews = array();
        /* change by Naraayn  19-05-2021 edit panel by admin type of work data comes from panels_transection table */
        $data = "select u.id as candidateId , p.*,pt.isExpertConfirmLater,pt.isExpertAssessmentApproved,pt.isExpertVideoApproved,pt.isExpertPeerApproved from `panel` p inner join panels_transection pt on p.id=pt.panelId inner join users u on u.panelId = p.id  where p.id='" . $panelId . "'";
        $query = mysqli_query($databaseConnection, $data);
        if (mysqli_num_rows($query) >= 1) {
            $values = array();
            while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
                $interviewData = "select * from `interview` where panelId='" . $row['id'] . "' and deleted_at is null  and isActive='Y' and categoryType in (1,2,6,7,8)";
                $interviewQuery = mysqli_query($databaseConnection, $interviewData);
                if (mysqli_num_rows($interviewQuery) >= 1) {
                    $interviewValues = mysqli_fetch_all($interviewQuery, MYSQLI_ASSOC);
                } else {
                    $interviewValues = array(
                        'result' => "info",
                        'status' => 0,
                        'errorCode' => "No courses avaialble."
                    );
                }

                $data15 = "SELECT s.id,s.stream FROM stream s INNER GetOIN favourite_subject fs ON s.id = fs.streamId where s.id NOT IN(21,57,58) GROUP BY s.id;";
                $query15 = mysqli_query($databaseConnection, $data15);
                $row['streamList'] = mysqli_fetch_all($query15, MYSQLI_ASSOC);

                /*  $data16 = "SELECT s.id as streamId,s.stream as streamName,fs.id as subjectId,fs.favourite_subject as subjectName FROM stream s INNER JOIN favourite_subject fs ON s.id = fs.streamId where s.id NOT IN(21) ORDER BY s.stream,fs.favourite_subject ASC;"; */
                $data16 = "SELECT s.id as streamId,s.stream as streamName,fs.id as subjectId,fs.favourite_subject as subjectName FROM stream s INNER JOIN favourite_subject fs ON s.id = fs.streamId where s.id NOT IN(21,57,58) ORDER BY s.stream,fs.favourite_subject ASC;";
                $query16 = mysqli_query($databaseConnection, $data16);
                $row['streamSubjectList'] = mysqli_fetch_all($query16, MYSQLI_ASSOC);

                $data17 = "SELECT s.id as streamId,s.stream as streamName,fs.id as subjectId,fs.favourite_subject as subjectName FROM stream s INNER JOIN favourite_subject fs ON s.id = fs.streamId where s.id IN (21) ORDER BY s.stream,fs.favourite_subject ASC;";
                $query17 = mysqli_query($databaseConnection, $data17);
                $row['codingSubjectList'] = mysqli_fetch_all($query17, MYSQLI_ASSOC);

                $data18 = "SELECT s.id as streamId,s.stream as streamName,fs.id as subjectId,fs.favourite_subject as subjectName FROM stream s INNER JOIN favourite_subject fs ON s.id = fs.streamId where s.id IN (57) ORDER BY s.stream,fs.favourite_subject ASC;";
                $query18 = mysqli_query($databaseConnection, $data18);
                $row['cloudSubjectList'] = mysqli_fetch_all($query18, MYSQLI_ASSOC);

                $data19 = "SELECT s.id as streamId,s.stream as streamName,fs.id as subjectId,fs.favourite_subject as subjectName FROM stream s INNER JOIN favourite_subject fs ON s.id = fs.streamId where s.id IN (58) ORDER BY s.stream,fs.favourite_subject ASC;";
                $query19 = mysqli_query($databaseConnection, $data19);
                $row['dataAnalystSubjectList'] = mysqli_fetch_all($query19, MYSQLI_ASSOC);

                $row['picture'] = 'panel_' . $row['id'] . '.png';
                $row['areaOfExpertise'] = $row['areaOfExpertiseId'];
                $row['interviews'] = $interviewValues;

                array_push($values, $row);
            }
            $to_encode = $values;
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "in Error  while retrieving panel information."
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error whire retrieving panel information."
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getTotalCreditAvailable'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $url = $json['url'];
        $result = connectToSMSServer($url);
        $to_encode = array(
            'result' => json_decode($result, true),
            'status' => 1
        );
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "sms server connection failed",
            'status' => -1
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['addNewCompany'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $company = $json['companyName'];

        $newCompany = mysqli_query($databaseConnection, "insert into aspiration_company(`name`) values ('" . $company . "')");

        if ($newCompany) {
            $to_encode = array(
                'result' => 'success',
                'status' => 1
            );
        } else {
            $to_encode = array(
                'result' => 'error while inserting',
                'status' => -1
            );
        }

    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "error in the given data",
            'status' => -1
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['addNewRole'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $role = $json['roleName'];

        $newCompany = mysqli_query($databaseConnection, "insert into relavant_role(`name`) values ('" . $role . "')");

        if ($newCompany) {
            $to_encode = array(
                'result' => 'success',
                'status' => 1
            );
        } else {
            $to_encode = array(
                'result' => 'error while inserting',
                'status' => -1
            );
        }

    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "error in the given data",
            'status' => -1
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['updateMessageStatus'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $smsUserName = $json['smsUserName'];
        $smsApiKey = $json['smsApiKey'];

        $qry = "select msgId, message from message_log where status is null and sentAt < NOW() - INTERVAL 1 DAY group by msgId";
        $query = mysqli_query($databaseConnection, $qry);
        if (mysqli_num_rows($query) >= 1) {
            while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
                $message = $row['message'];
                $msgId = $row['msgId'];
                $url = 'http://sms.hspsms.com/getDLR?username=' . $smsUserName . '&msgid=' . $msgId . '&apikey=' . $smsApiKey;
                $result = json_decode(connectToSMSServer($url), true);

                $data = $result[0]['dlr_status'];
                for ($i = 0; $i < count($data); $i++) {
                    $updateStatus = "UPDATE `message_log` SET `status` = '" . $data[$i]['dlrstatus'] . "' WHERE `msgId` = '" . $msgId . "' AND `message` = '" . $message . "' AND `mobileNumber` = '" . $data[$i]['mobileno'] . "'";
                    $updateResult = mysqli_query($databaseConnection, $updateStatus);
                }
            }
            $to_encode = array(
                'status' => 1,
                'result' => "Success",
                'message' => 'Message Status Updated Successfully'
            );
        } else {
            $to_encode = array(
                'result' => "success",
                'message' => "No data available",
                'status' => 0
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "sms server connection failed",
            'status' => -1
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['sendMessageToCandidate'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $url = urldecode($json['url']);
        $message = $json['message'];
        $candidateList = $json['candidateList'];
        $insertedCount = 0;

        $result = json_decode(connectToSMSServer($url), true);
        if ($result[0]['responseCode'] === 'Message SuccessFully Submitted') {
            $msgId = $result[1]['msgid'];

            for ($i = 0; $i < count($candidateList); $i++) {
                $SaveMessagelog = "INSERT INTO `message_log`(`candidateId`, `mobileNumber`, `message`, `msgId`) VALUES ('" . $candidateList[$i]['id'] . "', '" . $candidateList[$i]['mobileNumber'] . "', '" . addslashes($message) . "', '" . $msgId . "')";
                mysqli_query($databaseConnection, $SaveMessagelog);
                $insertedId = mysqli_insert_id($databaseConnection);
                if ($insertedId > 0) {
                    $insertedCount = $insertedCount + 1;
                }
            }
            if ($insertedCount == count($candidateList)) {
                $to_encode = array(
                    'result' => 'success',
                    'message' => 'Message SuccessFully Submitted',
                    'status' => 1
                );
            } else {
                $to_encode = array(
                    'result' => 'success',
                    'message' => 'Some message did not save in database',
                    'status' => 1
                );
            }
        } else {
            $to_encode = array(
                'result' => 'error',
                'message' => 'Message Not SuccessFully Submitted',
                'status' => 0
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "out error in data",
            'status' => -1
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['UpdatePaidAmountToExpert'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $amount = $json['amount'];
        $panelId = $json['panelId'];
        $updatePanel = "UPDATE panel set amountPaid='" . $amount . "' where id = '" . $panelId . "'";
        $updateResult = mysqli_query($databaseConnection, $updatePanel);
        if ($updateResult) {
            $to_encode = array(
                'result' => "Success",
                'message' => "Amount Paid Updated.",
                'status' => 1
            );
        } else {
            $to_encode = array(
                'result' => "Success",
                'message' => "Amount paid Updation failed.",
                'status' => -1
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Amount Paid Updation failed.",
            'status' => -1
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getPanalDetails'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $interviewId = $json['interviewId'];

        $data = "select * from `interview` where id='" . $interviewId . "'";
        $query = mysqli_query($databaseConnection, $data);
        if (mysqli_num_rows($query) >= 1) {

            $row = mysqli_fetch_assoc($query);
            $interviewData = "select * from `panel` where id='" . $row['panelId'] . "' ";
            $interviewQuery = mysqli_query($databaseConnection, $interviewData);
            if (mysqli_num_rows($interviewQuery) >= 1) {
                $values = mysqli_fetch_all($interviewQuery, MYSQLI_ASSOC);
                //$values[0]['peerHeading'] = $row['peerHeading'];
                $to_encode = $values;
            } else {
                $to_encode = array(
                    'result' => "info",
                    'status' => 0,
                    'errorCode' => "No panel avaialble."
                );
            }
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "in Error  while retrieving panel information."
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error whire retrieving panel information."
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getCollegeReport'])) {
    /* this API is Lastly Updated By Naraayn Feb 2022 added Student Activity and rating Stream Wise*/
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $filter_query = " ";
        $interview_filter_query = " ";
        $user_filter_query = " ";
        $college = array();
        $totalPractice = array();
        $user_values = array();
        $LeadStatus = array();
        $rawData = " ";
        $totalQuery = " ";
        $total_userQuery = " ";

        if ($json['stream'] != "" and sizeof($json['stream']) > 0)
            $filter_query .= " and pd.specialization in ('" . implode("', '", $json['stream']) . "')";
        if ($json['yop'] != "")
            $filter_query .= " and pd.year in (" . $json['yop'] . ")";
        if ($json['from_date'] != "" && $json['to_date'] == "") {
            $interview_filter_query .= " and m.interviewSessionId >= '" . strtotime($json['from_date']) . "'";
            $user_filter_query .= " and u.createdOn >= '" . strtotime($json['from_date']) . "'";
        }
        if ($json['from_date'] == "" && $json['to_date'] != "") {
            $interview_filter_query .= " and m.interviewSessionId <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";
            $user_filter_query .= " and u.createdOn <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";
        }
        if ($json['from_date'] != "" && $json['to_date'] != "") {
            $interview_filter_query .= " and m.interviewSessionId >= '" . strtotime($json['from_date']) . "' and m.interviewSessionId <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";
            $user_filter_query .= " and u.createdOn >= '" . strtotime($json['from_date']) . "' and u.createdOn <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";
        }


        if ($json['isTieUpStatus'] != "") {
            if ($userType != 'college') {
                $filter_query .= 'and rd.signup_status=1';
                $rawData .= " inner join raw_data rd on rd.email_id = u.emailId ";
                if ($json['isTieUpStatus'] == 'Y') {
                    $filter_query .= " and rd.isPaid = 'Y'";
                } elseif ($json['isTieUpStatus'] == 'F') {
                    $filter_query .= " and rd.isPaid = 'F'";
                } else {
                    $filter_query .= " and rd.isPaid = 'N'";
                }

            }

        }
        if ($userType == 'college') {
            $college_query = mysqli_query($databaseConnection, "select u1.* from users u1 where u1.id =" . $json['userId'] . " ");
            $college_result = mysqli_fetch_array($college_query, MYSQLI_ASSOC);
            $filter_query .= " and pd.college in (" . $college_result['college_id'] . ")";

            $totalQuery .= " if((SELECT mockInterviewAllowed+communicationInterviewAllowed+behaviouralInterviewAllowed+codingInterviewAllowed+problemsolvingInterviewAllowed  as totalAllowed  FROM `college_subscription` WHERE collegeId = pd.college and yop = pd.year and streamId = pd.specialization limit 1),(SELECT mockInterviewAllowed+communicationInterviewAllowed+behaviouralInterviewAllowed+codingInterviewAllowed+problemsolvingInterviewAllowed  as totalAllowed  FROM `college_subscription` WHERE collegeId = pd.college and yop = pd.year and streamId = pd.specialization limit 1),if((SELECT freeTrialAllowed as totalAllowed FROM `college_subscription` WHERE collegeId = pd.college and yop = pd.year and streamId = pd.specialization limit 1),(SELECT freeTrialAllowed as totalAllowed FROM `college_subscription` WHERE collegeId = pd.college and yop = pd.year and streamId = pd.specialization limit 1) , 2)) as totalAllowed, ";
            $total_userQuery .= " 0 as totalAllowed, ";
            $rawData .= " inner join raw_data rd on rd.email_id = u.emailId ";
            $filter_query .= 'and rd.signup_status=1';
            if ($json['isTieUpStatus'] == 'Y') {
                $filter_query .= " and rd.isPaid = 'Y'";
            } elseif ($json['isTieUpStatus'] == 'F') {
                $filter_query .= " and rd.isPaid = 'F'";
            } elseif ($json['isTieUpStatus'] == 'N') {
                $filter_query .= " and rd.isPaid = 'N'";
            } else {
                $filter_query .= " and rd.isPaid in('Y','F')";
            }



        }
        if ($userType == 'mentor') {
            $filter_query .= " and pd.assignMentorId in (" . $json['userId'] . ")";
        }
        if ($json['college'] != "" and sizeof($json['college']) > 0) {
            $filter_query .= " and pd.college in ('" . implode("', '", $json['college']) . "')";
            $college_query = mysqli_query($databaseConnection, "SELECT GROUP_CONCAT(collegeName SEPARATOR ', ') as collegeName FROM `colleges` WHERE id in ('" . implode("', '", array_map("addSlashToString", $json['college'])) . "') ");
            $college = mysqli_fetch_array($college_query, MYSQLI_ASSOC);

            $totalQuery .= " if((SELECT mockInterviewAllowed+communicationInterviewAllowed+behaviouralInterviewAllowed+codingInterviewAllowed+problemsolvingInterviewAllowed  as totalAllowed  FROM `college_subscription` WHERE collegeId = pd.college and yop = pd.year and streamId = pd.specialization limit 1),(SELECT mockInterviewAllowed+communicationInterviewAllowed+behaviouralInterviewAllowed+codingInterviewAllowed+problemsolvingInterviewAllowed  as totalAllowed  FROM `college_subscription` WHERE collegeId = pd.college and yop = pd.year and streamId = pd.specialization limit 1),if((SELECT freeTrialAllowed as totalAllowed FROM `college_subscription` WHERE collegeId = pd.college and yop = pd.year and streamId = pd.specialization limit 1),(SELECT freeTrialAllowed as totalAllowed FROM `college_subscription` WHERE collegeId = pd.college and yop = pd.year and streamId = pd.specialization limit 1) , 2)) as totalAllowed,";
            $total_userQuery .= " 0 as totalAllowed, ";

        }

        $interview_query = "select s.stream, 0 as signedUpUser, 0 as signUpPlusUser," . $totalQuery . " count(distinct (CASE WHEN m.interviewSessionId is not Null THEN m.candidateId ELSE NULL END )) as activeStudent, count(distinct m.interviewSessionId) as interviewGiven,ROUND(AVG(r.userInterface), 1) as interviewRating,count(DISTINCT m.candidateId,m.interviewId) as studentActivity, count(distinct (CASE WHEN fr.review_status = '2' THEN fr.id ELSE NULL END)) AS assessmentProvided, count(distinct (CASE WHEN fr.id is NULL THEN m.interviewSessionId WHEN fr.review_status = '-2' THEN fr.id WHEN fr.review_status = '0' THEN fr.id WHEN fr.review_status = '1' THEN fr.id WHEN fr.review_status = '-3' THEN fr.id ELSE NULL END)) AS assessmentPending, count(distinct (CASE WHEN fr.review_status = '-4' THEN fr.id ELSE NULL END)) AS assessmentRejected,count(DISTINCT (CASE WHEN fr.review_status !='-4' and fr.candidateId = fr.createdBy  THEN fr.id  WHEN fr.review_status = '-4' and fr.candidateId = fr.createdBy and fr.candidateId != fr.rejectedBy THEN fr.id ELSE null END)) as assessmentRequested, (SUM(TIME_TO_SEC(m.totalTime)) + SUM(TIME_TO_SEC(vwd.prwatchDuration)) + SUM(TIME_TO_SEC(vwd.psWatchDuration)) + SUM(TIME_TO_SEC(vwd.gvWatchDuration))) as durationOfPractice from users u inner join professionaldetails pd on pd.candidateId = u.id left outer join stream s on s.id = pd.specialization inner join mergedVideos m on m.candidateId = u.id inner join video_watched_details vwd on vwd.mergeId = m.mergeId left outer join feedback_request fr on fr.interviewSessionId = m.interviewSessionId  left outer join ratings r on r.candidateId = m.candidateId" . $rawData . " where  m.interviewSessionId is not null ";
        $interview_data = $interview_query . $filter_query . $interview_filter_query . ' group by pd.specialization order by s.id ';

        /* echo $interview_data; */

        $user_query = "select s.stream, count(distinct u.id) as signedUpUser, count(distinct (CASE WHEN u.isMentee = 'Y' THEN u.id ELSE NULL END)) as signUpPlusUser, " . $total_userQuery . "  0 as activeStudent, 0 as interviewGiven,0 as interviewRating, 0 as studentActivity, 0 as assessmentProvided, 0 as assessmentPending, 0 as assessmentRejected,0 as assessmentRequested, NULL as durationOfPractice from users u inner join professionaldetails pd on pd.candidateId = u.id left outer join stream s on s.id = pd.specialization " . $rawData . " where 1 ";
        $user_data = $user_query . $filter_query . $user_filter_query . 'group by pd.specialization order by s.id';

        /* echo $user_data; */
        // $collegeReportQuery = $interview_data . " UNION " . $user_data;


        $interview_result = mysqli_query($databaseConnection, $interview_data);
        $user_result = mysqli_query($databaseConnection, $user_data);
        if (mysqli_num_rows($user_result) >= 1) {
            $user_values = mysqli_fetch_all($user_result, MYSQLI_ASSOC);
        }


        // $college_subscriptionQuery = "SELECT mockInterviewAllowed+communicationInterviewAllowed+behaviouralInterviewAllowed+codingInterviewAllowed+problemsolvingInterviewAllowed as totalAllowed  FROM `college_subscription` WHERE 1 and $college_subscription_filter"

        if (mysqli_num_rows($interview_result) >= 1) {
            $interview_values = mysqli_fetch_all($interview_result, MYSQLI_ASSOC);

            /*only 5 reason of rejection will be shown to college 02/03/2022*/
            if ($userType == 'college') {
                $reasonOfRejectionQry = "select count(DISTINCT fr.interviewSessionId) as totalRejectedUser, fr.reasonOfRejection, CASE WHEN fr.reasonOfRejection ='limitedFreeAssessment' THEN 'Limited FREE Assessment'   WHEN fr.reasonOfRejection = 'technicalIssue' THEN 'Internet Issue' WHEN fr.reasonOfRejection = 'unauthorizedUser' THEN 'Unauthorized User' WHEN fr.reasonOfRejection = 'duplicateAttempt' THEN 'Duplicate Attempt' ELSE NULL END as reasonOfRejectionText from users u inner join professionaldetails pd on pd.candidateId = u.id left outer join stream s on s.id = pd.specialization inner join mergedVideos m on m.candidateId = u.id inner join feedback_request fr on fr.interviewSessionId = m.interviewSessionId left outer join reason_of_rejection ror on ror.reasonOfRejection = fr.reasonOfRejection  " . $rawData . " where fr.review_status = '-4' and ror.id in (2,4,9,12)   ";


                $reasonOfRejectionResult = mysqli_query($databaseConnection, $reasonOfRejectionQry . $filter_query . $interview_filter_query . ' group by reasonOfRejectionText  order by ror.sequence');

                $reasonOfRejectionData = array();
                if (mysqli_num_rows($reasonOfRejectionResult) >= 1) {
                    $reasonOfRejectionData = mysqli_fetch_all($reasonOfRejectionResult, MYSQLI_ASSOC);
                }
            } else {
                $reasonOfRejectionQry = "select count(DISTINCT fr.interviewSessionId) as totalRejectedUser, fr.reasonOfRejection, CASE WHEN fr.reasonOfRejection is null THEN 'Other Reason' WHEN fr.reasonOfRejection = 'outOfProductScope' THEN 'Out of Product Scope' WHEN fr.reasonOfRejection = 'yourPracticeDurationIsDue' THEN 'Your Practice Duration is Due' WHEN fr.reasonOfRejection = 'selfRejected' THEN 'Self Rejected' WHEN fr.reasonOfRejection = 'studentIsIndulgedInMalpractice' THEN 'Student is Indulged in Malpractice' WHEN fr.reasonOfRejection = 'assessmentOnHold' THEN 'Assessment on Hold' WHEN fr.reasonOfRejection = 'PracticeInterview' THEN 'Practice Interview' WHEN fr.reasonOfRejection ='fixedNoOfAssessment' THEN 'Completed the Max no of Assessments'  WHEN fr.reasonOfRejection ='limitedFreeAssessment' THEN 'Limited FREE Assessment'    WHEN fr.reasonOfRejection = 'incompleteInterview' THEN 'Incomplete Interview' WHEN fr.reasonOfRejection = 'incompleteAnswer' THEN 'Incomplete Answer' WHEN fr.reasonOfRejection = 'Testing' THEN 'Testing' WHEN fr.reasonOfRejection = 'nonSeriousInterview' THEN 'Non Serious Interview' WHEN fr.reasonOfRejection = 'technicalIssue' THEN 'Technical Issue' WHEN fr.reasonOfRejection = 'unauthorizedUser' THEN 'Unauthorized User' WHEN fr.reasonOfRejection = 'duplicateAttempt' THEN 'Duplicate Attempt' ELSE fr.reasonOfRejection END as reasonOfRejectionText from users u inner join professionaldetails pd on pd.candidateId = u.id left outer join stream s on s.id = pd.specialization inner join mergedVideos m on m.candidateId = u.id inner join feedback_request fr on fr.interviewSessionId = m.interviewSessionId left outer join reason_of_rejection ror on ror.reasonOfRejection = fr.reasonOfRejection  " . $rawData . " where fr.review_status = '-4' ";
                $reasonOfRejectionResult = mysqli_query($databaseConnection, $reasonOfRejectionQry . $filter_query . $interview_filter_query . ' group by fr.reasonOfRejection  order by ror.sequence');
                $reasonOfRejectionData = array();
                if (mysqli_num_rows($reasonOfRejectionResult) >= 1) {
                    $reasonOfRejectionData = mysqli_fetch_all($reasonOfRejectionResult, MYSQLI_ASSOC);
                }

            }

            /*$totalUniqueRejectedUser = "select count(DISTINCT fr.candidateId) as totalUniqueRejectedUser from users u inner join professionaldetails pd on pd.candidateId = u.id left outer join stream s on s.id = pd.specialization inner join mergedVideos m on m.candidateId = u.id inner join feedback_request fr on fr.interviewSessionId = m.interviewSessionId " . $rawData . " where fr.review_status = '-4' ";
            $totalUniqueRejectedResult = mysqli_query($databaseConnection, $totalUniqueRejectedUser . $filter_query . $interview_filter_query);
            $totalUniqueRejectedUserData = array();
            if (mysqli_num_rows($totalUniqueRejectedResult) >= 1) {
                $totalUniqueRejectedUserData = mysqli_fetch_all($totalUniqueRejectedResult, MYSQLI_ASSOC);
            }*/
            /* this added for count for different student issue 11-sep-2021*/
            $studentIssueQry = "select count(DISTINCT mo.id) as totalStudentIssue,mo.studentIssue from users u inner join professionaldetails pd on pd.candidateId = u.id left outer join stream s on s.id = pd.specialization left outer join mergedVideos m on m.candidateId = u.id inner join mentor_observations mo on mo.candidateId = u.id left outer join studentIssueList sil on sil.studentIssueName = mo.studentIssue " . $rawData . " where 1  ";
            $studentIssueResult = mysqli_query($databaseConnection, $studentIssueQry . $filter_query . $interview_filter_query . ' group by mo.studentIssue  order by sil.sequence');
            $studentIssueData = array();
            if (mysqli_num_rows($studentIssueResult) >= 1) {
                $studentIssueData = mysqli_fetch_all($studentIssueResult, MYSQLI_ASSOC);
            }


            if (count($user_values) > 0) {
                for ($i = 0; $i < count($interview_values); $i++) {
                    for ($j = 0; $j < count($user_values); $j++) {
                        if (($user_values[$j]['stream'] == $interview_values[$i]['stream']) && ($user_values[$j]['signedUpUser'] != 0)) {
                            $interview_values[$i]['signedUpUser'] = $user_values[$j]['signedUpUser'];
                            $interview_values[$i]['signUpPlusUser'] = $user_values[$j]['signUpPlusUser'];
                        }
                    }
                }
                foreach ($user_values as $item) {
                    if (array_search($item['stream'], array_column($interview_values, 'stream')) === FALSE) {
                        array_push($interview_values, $item);
                    }
                }
            }

            // for ($i = 0; $i < count($interview_values); $i++) {
            //     if ($interview_values[$i]['durationOfPractice']) {
            //         $totalPractice[] = $interview_values[$i]['durationOfPractice'];
            //     }
            // }
            $to_encode = array(
                'status' => 1,
                'collegeName' => array_key_exists('collegeName', $college) ? $college['collegeName'] : '',
                'result' => $interview_values,
                // 'totalPractice' => sum_the_time($totalPractice),
                'resonOfRejection' => $reasonOfRejectionData,
                'studentIssue' => $studentIssueData,
                //'totalUniqueRejectedData' => $totalUniqueRejectedUserData
            );
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "in Error while retrieving college information."
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error whire retrieving college information."
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getStudentPracticeReportData'])) {
    /* this APi Is Updated By Narayan in Jan 2022 For Automatically Is paid Yes When COllege login */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $flag = $json['flag'];
        $filter_query = " ";
        $college = array();
        $values = array();
        $rawData = " ";
        $signupstatus = " ";
        if ($json['stream'] != "" and sizeof($json['stream']) > 0)
            $filter_query .= " and pd.specialization in ('" . implode("', '", $json['stream']) . "')";
        if ($json['yop'] != "")
            $filter_query .= " and pd.year in (" . $json['yop'] . ")";

        if ($json['from_date'] != "" && $json['to_date'] == "")
            $filter_query .= " and m.interviewSessionId >= '" . strtotime($json['from_date']) . "'";
        if ($json['from_date'] == "" && $json['to_date'] != "")
            $filter_query .= " and m.interviewSessionId <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";
        if ($json['from_date'] != "" && $json['to_date'] != "")
            $filter_query .= " and m.interviewSessionId >= '" . strtotime($json['from_date']) . "' and m.interviewSessionId <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";

        if ($userType == 'college') {
            $college_query = mysqli_query($databaseConnection, "select u1.* from users u1 where u1.id =" . $json['userId'] . " ");
            $college_result = mysqli_fetch_array($college_query, MYSQLI_ASSOC);
            $filter_query .= " and pd.college in (" . $college_result['college_id'] . ")";
            $rawData .= " inner join raw_data rd on rd.email_id = u.emailId ";
            $signupstatus .= 'and rd.signup_status=1';
            if ($json['isTieUpStatus'] == 'Y') {
                $filter_query .= " and rd.isPaid = 'Y'";
            } elseif ($json['isTieUpStatus'] == 'F') {
                $filter_query .= " and rd.isPaid = 'F'";
            } elseif ($json['isTieUpStatus'] == 'N') {
                $filter_query .= " and rd.isPaid = 'N'";
            } else {
                $filter_query .= " and rd.isPaid in('Y','F')";
            }

        }
        if ($json['isTieUpStatus'] != "") {
            if ($userType != 'college') {
                $rawData .= " inner join raw_data rd on rd.email_id = u.emailId ";
                $signupstatus .= 'and rd.signup_status=1';
                if ($json['isTieUpStatus'] == 'Y') {
                    $filter_query .= " and rd.isPaid = 'Y'";
                } elseif ($json['isTieUpStatus'] == 'F') {
                    $filter_query .= " and rd.isPaid = 'F'";
                } else {
                    $filter_query .= " and rd.isPaid = 'N'";
                }

            }

        }
        if ($userType == 'mentor') {
            $filter_query .= " and pd.assignMentorId in (" . $json['userId'] . ")";
        }
        if ($json['college'] != "" and sizeof($json['college']) > 0) {
            $filter_query .= " and pd.college in ('" . implode("', '", $json['college']) . "')";
            $college_query = mysqli_query($databaseConnection, "SELECT GROUP_CONCAT(collegeName SEPARATOR ', ') as collegeName FROM `colleges` WHERE id in ('" . implode("', '", array_map("addSlashToString", $json['college'])) . "') ");
            $college = mysqli_fetch_array($college_query, MYSQLI_ASSOC);
        }


        //added by arun for getting individual users data
        if ($flag) {
            $fetch = "select temp.signUpDate,temp.id,case when (m.candidateId is not null and m.candidateId= temp.id) then 'Active'else case when (temp.id=r.id) then 'SignedUp' else 'Not SignedUp' end end  as 'SignUpStatus',temp.name as Name,temp.mobileNumber as MobileNumber,temp.emailId as EmailId,temp.stream as Stream,temp.year as YOP,temp.collegeName as College, CASE WHEN m.interviewSessionId is not null THEN max(m.interviewSessionId) ELSE 'Not Taken' END as lastInterviewDate, CASE WHEN m.candidateId is null THEN '00:00:00' ELSE SEC_TO_TIME(SUM(TIME_TO_SEC(m.totalTime)) + SUM(TIME_TO_SEC(vwd.prwatchDuration)) + SUM(TIME_TO_SEC(vwd.psWatchDuration)) + SUM(TIME_TO_SEC(vwd.gvWatchDuration))) END as TotalDurationOfPractice,count(distinct m.interviewSessionId) as interviewsTaken from (select u.id,u.createdOn as signUpDate, u.firstName as name, u.emailId, u.mobileNumber, st.stream as stream,pd.year,cl.collegeName,r.userInterface as Rating from users u left outer join professionaldetails pd on u.id = pd.candidateId left outer join stream st on pd.specialization=st.id  left outer join colleges cl on cl.id=pd.college left outer join ratings r on r.candidateId=u.id LEFT OUTER JOIN candidateEmp_status ces ON ces.candidateId = u.id " . $rawData . " left outer join webinar_registration_details wrd on wrd.candidateId=u.id where u.deleted_at is NULL " . $filter_query . $signupstatus . " GROUP BY u.id having 1 order by u.createdOn desc ) as temp left outer join mergedVideos m on m.candidateId = temp.id and m.interviewSessionId is not null left outer join feedback_request fr on fr.interviewSessionId = m.interviewSessionId left outer join interview i on i.id=m.interviewId left outer join product p on i.productId=p.id left outer join favourite_subject fv on i.subject_id = fv.id inner join video_watched_details vwd on vwd.mergeId = m.mergeId left outer join raw_data r on r.id=temp.id  Where 1 GROUP by temp.id having 1 order by interviewsTaken desc";

            $signup_data = "select u.createdOn as signUpDate, case when u.id is not null then 'SignUp' end as 'SignUpStatus', u.firstName as name, u.mobileNumber,u.emailId,st.stream as stream,pd.year,cl.collegeName,0 as LastInterviewTaken, 0 as 'No.OfInterview',null as OverAllRating  from users u left outer join professionaldetails pd on u.id = pd.candidateId left outer join ratings r on r.candidateId=u.id left outer join stream st on pd.specialization=st.id left outer join colleges cl on cl.id=pd.college LEFT OUTER JOIN candidateEmp_status ces ON ces.candidateId = u.id " . $rawData . " left outer join webinar_registration_details wrd on wrd.candidateId=u.id where u.deleted_at is NULL" . $filter_query . $signupstatus . " and u.id not in (select distinct m.candidateId from mergedVideos m) having 1 order by u.createdOn desc ";

            $nosignup_data = "select Null as 'SignUpDate','Not SignedUp' as 'SignUpStatus',rd.candidate_name,rd.contact_number,rd.email_id,rd.college_name,rd.stream,rd.yop,null as 'LastinterviewDate',0 as 'Duration time',null as 'OverAllRating' from raw_data rd inner join professionaldetails pd on pd.candidateId=rd.id inner join users u on u.id=pd.candidateId  where rd.college_name is not null " . $filter_query . " and rd.email_id not in (select distinct emailId from users) ";
            $nosignup_result = mysqli_query($databaseConnection, $nosignup_data);
            /* if (mysqli_num_rows( $nosignup_result) >= 1) { */
            $nosignup_details = mysqli_fetch_all($nosignup_result, MYSQLI_ASSOC);
            /* }
            else
            {
                $nosignup_details="";
            } */
            $fetch_result = mysqli_query($databaseConnection, $fetch);
            while ($detail = mysqli_fetch_array($fetch_result, MYSQLI_ASSOC)) {
                if ($detail['interviewsTaken'] >= 1) {
                    $detail['overallRatings'] = getOverallRatingsForAllInterviews($databaseConnection, $detail['id']);
                } else {
                    $detail['overallRatings'] = NULL;
                }
                array_push($values, $detail);
            }
            $row = "";
            $signup_result = mysqli_query($databaseConnection, $signup_data);
            if (mysqli_num_rows($signup_result) >= 1) {
                $signup_details = mysqli_fetch_all($signup_result, MYSQLI_ASSOC);
                $to_encode = array(
                    'status' => 1,
                    'result' => "sucess",
                    'details' => $values,
                    'signupdetails' => $signup_details,
                    'nosignupdetails' => $nosignup_details,
                    'data' => $row
                );
            } else {
                $to_encode = array(
                    'status' => 0,
                    'result' => "error",
                    'errorCode' => "out Error whire retrieving practice information."
                );
            }

        } else {
            $query = "SELECT s.stream,s.id as streamId, count(temp.TotalDurationOfPractice) as totalCount,COUNT(CASE WHEN temp.noOfInterviewTaken = 1 THEN temp.noOfInterviewTaken ELSE NULL END) as OneInterview,COUNT(CASE WHEN temp.noOfInterviewTaken = 2 THEN temp.noOfInterviewTaken ELSE NULL END) as TwoInterview,COUNT(CASE WHEN temp.noOfInterviewTaken = 3 THEN temp.noOfInterviewTaken ELSE NULL END) as ThreeInterview,COUNT(CASE WHEN temp.noOfInterviewTaken > 3 THEN temp.noOfInterviewTaken ELSE NULL END) as MoreThanThreeInterview,  date_format(SEC_TO_TIME(SUM(CASE WHEN temp.noOfInterviewTaken = 1 THEN TIME_TO_SEC(temp.TotalDurationOfPractice) ELSE '00:00:00' END)),'%H:%i:%s') as OnePrac, date_format(SEC_TO_TIME(SUM(CASE WHEN temp.noOfInterviewTaken = 2 THEN TIME_TO_SEC(temp.TotalDurationOfPractice) ELSE '00:00:00' END)),'%H:%i:%s') as TwoPrac, date_format(SEC_TO_TIME(SUM(CASE WHEN temp.noOfInterviewTaken = 3 THEN TIME_TO_SEC(temp.TotalDurationOfPractice) ELSE '00:00:00' END)),'%H:%i:%s') as ThreePrac, date_format(SEC_TO_TIME(SUM(CASE WHEN temp.noOfInterviewTaken > 3 THEN TIME_TO_SEC(temp.TotalDurationOfPractice) ELSE '00:00:00' END)),'%H:%i:%s') as MoreThanThreePrac,COUNT(CASE WHEN temp.TotalDurationOfPractice > '00:00:00'
        and  temp.TotalDurationOfPractice <= '00:30:00' THEN temp.TotalDurationOfPractice ELSE NULL END) as zeroToThrtyMin ,
        COUNT(CASE WHEN temp.TotalDurationOfPractice > '00:30:00' and  temp.TotalDurationOfPractice <= '01:00:00'   THEN temp.TotalDurationOfPractice ELSE NULL END) as BetweenHalfToOneHrs, COUNT(CASE WHEN temp.TotalDurationOfPractice > '01:00:00' and   temp.TotalDurationOfPractice <= '02:00:00' THEN temp.TotalDurationOfPractice ELSE NULL END) as BetweenOneToTwoHrs,COUNT(CASE WHEN temp.TotalDurationOfPractice > '02:00:00' and   temp.TotalDurationOfPractice <= '05:00:00' THEN temp.TotalDurationOfPractice ELSE NULL END) as BetweenTwoToFiveHrs,COUNT(CASE WHEN temp.TotalDurationOfPractice > '05:00:00' and  temp.TotalDurationOfPractice <= '10:00:00' THEN temp.TotalDurationOfPractice ELSE NULL END) as BetweenTenHrs,COUNT(CASE WHEN temp.TotalDurationOfPractice > '10:00:00' THEN temp.TotalDurationOfPractice ELSE NULL END) as GreaterTenHrs from (select pd.specialization, u.id,count(Distinct m.interviewSessionId) as noOfInterviewTaken, CASE WHEN m.candidateId is null THEN '00:00:00' ELSE SEC_TO_TIME(SUM(TIME_TO_SEC(m.totalTime)) + SUM(TIME_TO_SEC(vwd.prwatchDuration)) + SUM(TIME_TO_SEC(vwd.psWatchDuration)) + SUM(TIME_TO_SEC(vwd.gvWatchDuration))) END as TotalDurationOfPractice from mergedVideos m inner join users u  on m.candidateId = u.id inner join professionaldetails pd on pd.candidateId = u.id inner join video_watched_details vwd on vwd.mergeId = m.mergeId " . $rawData . " where m.interviewSessionId is not null  " . $filter_query . "  group by m.candidateId) as temp inner join stream s on s.id = temp.specialization group by  s.id";

            $values = "";
            $signup_details = "";
            $nosignup_details = "";
            $query_result = mysqli_query($databaseConnection, $query);
            if (mysqli_num_rows($query_result) >= 1) {
                $row = mysqli_fetch_all($query_result, MYSQLI_ASSOC);


                $to_encode = array(
                    'status' => 1,
                    'result' => "sucess",
                    'details' => $values,
                    // 'signupdetails'=>$signup_details,
                    // 'nosignupdetails'=>$nosignup_details,
                    'data' => $row
                );
            } else {
                $to_encode = array(
                    'status' => 0,
                    'result' => "error",
                    'errorCode' => "out Error whire retrieving practice information."
                );
            }
        }


    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error whire retrieving practice information."
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getStudentCompleteSkillReport'])) {
    /* this api is not required and need to be updated Before use */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $filter_query = " ";
        $college = array();
        $values = array();
        $rawData = " ";

        if ($json['stream'] != "" and sizeof($json['stream']) > 0)
            $filter_query .= " and pd.specialization in ('" . implode("', '", $json['stream']) . "')";
        if ($json['yop'] != "")
            $filter_query .= " and pd.year in (" . $json['yop'] . ")";
        if ($json['from_date'] != "" && $json['to_date'] == "")
            $filter_query .= " and er.createdAt >= '" . $json['from_date'] . " 23:59:59'";
        if ($json['from_date'] == "" && $json['to_date'] != "")
            $filter_query .= " and er.createdAt <= '" . $json['to_date'] . " 23:59:59'";
        if ($json['from_date'] != "" && $json['to_date'] != "")
            $filter_query .= " and er.createdAt >= '" . $json['from_date'] . " 23:59:59' and er.createdAt <= '" . $json['to_date'] . " 23:59:59'";

        if ($userType == 'college') {
            $college_query = mysqli_query($databaseConnection, "select u1.* from users u1 where u1.id =" . $json['userId'] . " ");
            $college_result = mysqli_fetch_array($college_query, MYSQLI_ASSOC);
            $filter_query .= " and pd.college in (" . $college_result['college_id'] . ")";
        }
        if ($json['isTieUpStatus'] != "") {
            $rawData .= " inner join raw_data rd on rd.email_id = u.emailId ";
            if ($json['isTieUpStatus'] == 'Y') {
                $filter_query .= " and rd.isPaid = 'Y'";
            } else {
                $filter_query .= " and rd.isPaid = 'N'";
            }
        }
        if ($userType == 'mentor') {
            $filter_query .= " and pd.assignMentorId in (" . $json['userId'] . ")";
        }
        if ($json['college'] != "" and sizeof($json['college']) > 0) {
            $filter_query .= " and pd.college in ('" . implode("', '", $json['college']) . "')";
            $college_query = mysqli_query($databaseConnection, "SELECT GROUP_CONCAT(collegeName SEPARATOR ', ') as collegeName FROM `colleges` WHERE id in ('" . implode("', '", array_map("addSlashToString", $json['college'])) . "') ");
            $college = mysqli_fetch_array($college_query, MYSQLI_ASSOC);
        }


        $query = "SELECT  CASE WHEN fv.favourite_subject is not Null then fv.favourite_subject ELSE 'Not Available' END as SubjectName , ks.key_skill as SkillName, oa.observation_name as ObservationName, COUNT(case when ov.observation_values is null then (select if(observation_values='Good','Good',Null) from observation_values where id = (select erods.observationValueId from expert_review_observation_details erods inner join observation_area oas on oas.id = erods.observationAreaId where erods.expertReviewId = erod.expertReviewId and erods.observationValueId is not null and oas.observation_name = ks.key_skill)) else  if(ov.observation_values = 'Good','Good',Null) end) as Good ,COUNT(case when ov.observation_values is null then (select if(observation_values='Acceptable','Acceptable',Null) from observation_values where id = (select erods.observationValueId from expert_review_observation_details erods inner join observation_area oas on oas.id = erods.observationAreaId where erods.expertReviewId = erod.expertReviewId and erods.observationValueId is not null and oas.observation_name = ks.key_skill)) else  if(ov.observation_values = 'Acceptable','Acceptable',Null) end) as Acceptable,COUNT(case when ov.observation_values is null then (select if(observation_values='Needs Improvement','Needs Improvement',Null) from observation_values where id = (select erods.observationValueId from expert_review_observation_details erods inner join observation_area oas on oas.id = erods.observationAreaId where erods.expertReviewId = erod.expertReviewId and erods.observationValueId is not null and oas.observation_name = ks.key_skill)) else  if(ov.observation_values = 'Needs Improvement','Needs Improvement',Null) end) as NeedsImprovement FROM expert_review_observation_details as erod inner join observation_area as oa on oa.id = erod.observationAreaId inner join expert_review as er on er.id = erod.expertReviewId inner join key_skill as ks on ks.id = oa.key_skill inner join questions q on q.id = er.questionId left outer join favourite_subject fv on fv.id = q.subjectId left outer join observation_values as ov on ov.id = erod.observationValueId and ov.observation_values != 'Not Applicable' left outer join users u on u.id = er.id left outer join professionaldetails pd on pd.candidateId = u.id  " . $rawData . "  WHERE er.review_type = 'question' and er.overallRating != 'videoIssue' " . $filter_query . "  group by q.subjectId,oa.key_skill,oa.observation_name order by SubjectName,SkillName,ObservationName;";
        $query_result = mysqli_query($databaseConnection, $query);
        if (mysqli_num_rows($query_result) >= 1) {
            $row = mysqli_fetch_all($query_result, MYSQLI_ASSOC);
            $to_encode = array(
                'status' => 1,
                'result' => "sucess",
                'data' => $row
            );
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "out Error whire retrieving practice information."
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error whire retrieving practice information."
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getplatFormAvgSkillData'])) {
    /* this New API is Added By Narayan For getting platFormAvgSkillData in Jan 2022 */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $filter_query = " ";
        $college = array();
        $values = array();
        $rawData = " ";

        if ($json['stream'] != "" and sizeof($json['stream']) > 0)
            $filter_query .= " and pd.specialization in ('" . implode("', '", $json['stream']) . "')";
        if ($json['yop'] != "")
            $filter_query .= " and pd.year in (" . $json['yop'] . ")";
        if ($json['from_date'] != "" && $json['to_date'] == "")
            $filter_query .= " and fbr.interviewSessionId >= '" . strtotime($json['from_date']) . "'";
        if ($json['from_date'] == "" && $json['to_date'] != "")
            $filter_query .= " and fbr.interviewSessionId <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";
        if ($json['from_date'] != "" && $json['to_date'] != "")
            $filter_query .= " and fbr.interviewSessionId >= '" . strtotime($json['from_date']) . "' and fbr.interviewSessionId <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";

        if ($userType == 'college') {
            $college_query = mysqli_query($databaseConnection, "select u1.* from users u1 where u1.id =" . $json['userId'] . " ");
            $college_result = mysqli_fetch_array($college_query, MYSQLI_ASSOC);
            $filter_query .= " and pd.college in (" . $college_result['college_id'] . ")";
            $rawData .= " inner join raw_data rd on rd.email_id = u.emailId ";
            if ($json['isTieUpStatus'] == 'Y') {
                $filter_query .= " and rd.isPaid = 'Y'";
            } elseif ($json['isTieUpStatus'] == 'F') {
                $filter_query .= " and rd.isPaid = 'F'";
            } elseif ($json['isTieUpStatus'] == 'N') {
                $filter_query .= " and rd.isPaid = 'N'";
            } else {
                $filter_query .= " and rd.isPaid in('Y','F')";
            }
        }
        if ($userType !== 'college') {
            if ($json['isTieUpStatus'] != "") {
                $rawData .= " inner join raw_data rd on rd.email_id = u.emailId ";
                if ($json['isTieUpStatus'] == 'Y') {
                    $filter_query .= " and rd.isPaid = 'Y'";
                } elseif ($json['isTieUpStatus'] == 'F') {
                    $filter_query .= " and rd.isPaid = 'F'";
                } else {
                    $filter_query .= " and rd.isPaid = 'N'";
                }
            }
        }
        if ($userType == 'mentor') {
            $filter_query .= " and pd.assignMentorId in (" . $json['userId'] . ")";
        }
        if ($json['college'] != "" and sizeof($json['college']) > 0) {
            $filter_query .= " and pd.college in ('" . implode("', '", array_map("addSlashToString", $json['college'])) . "')";
            $college_query = mysqli_query($databaseConnection, "SELECT GROUP_CONCAT(collegeName SEPARATOR ', ') as collegeName FROM `colleges` WHERE id in ('" . implode("', '", array_map("addSlashToString", $json['college'])) . "') ");
            $college = mysqli_fetch_array($college_query, MYSQLI_ASSOC);
        }

        $query = "SELECT  key_skill_id,skillName,ROUND(AVG(skillScore),1) as PlatformAvg,ROUND((AVG(time_to_sec(cumulativeDuration)+time_to_sec(contentConsumed))/3600),1) as AvgPracticeDuration  FROM newFeedbackReport  group by key_skill_id";
        $query_result = mysqli_query($databaseConnection, $query);
        if (mysqli_num_rows($query_result) >= 1) {
            $row = mysqli_fetch_all($query_result, MYSQLI_ASSOC);

            $candidateCountQuery = "Select count(distinct fbr.candidateId) as totalCandidate from newFeedbackReport fr, feedback_request fbr, professionaldetails pd inner join users u on u.id = pd.candidateId " . $rawData . " where fbr.id = fr.feedback_request_id and pd.candidateId = fbr.candidateId ";
            $candidateCountResult = mysqli_query($databaseConnection, $candidateCountQuery . $filter_query);
            $candidateCountData = mysqli_fetch_assoc($candidateCountResult);

            $to_encode = array(
                'status' => 1,
                'result' => "sucess",
                'data' => $row,
                'candidateCount' => $candidateCountData['totalCandidate']
            );
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "out Error whire retrieving practice information."
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error whire retrieving practice information."
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getSkillAnalysisReportData'])) {
    /* this New API is Added By Narayan For getting SkillAnalysisReport in Jan 2022 */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $filter_query = " ";
        $college = array();
        $values = array();
        $rawData = " ";
        $row1 = array();
        $flag = $json['flag'];
        $platformRequired = 0;

        if ($json['stream'] != "" and sizeof($json['stream']) > 0)
            $filter_query .= " and pd.specialization in ('" . implode("', '", $json['stream']) . "')";
        if ($json['yop'] != "")
            $filter_query .= " and pd.year in (" . $json['yop'] . ")";
        /* if($json['from_date']!="" && $json['to_date']=="")
            $filter_query.=" and u.createdOn >= '".strtotime($json['from_date'])."'";
        if($json['from_date']=="" && $json['to_date']!="")
            $filter_query.=" and u.createdOn <= '".strtotime('+1 day', strtotime($json['to_date']))."'";
        if($json['from_date']!="" && $json['to_date']!="")
            $filter_query.=" and u.createdOn >= '".strtotime($json['from_date'])."' and u.createdOn <= '".strtotime('+1 day', strtotime($json['to_date']))."'";*/
        if ($json['from_date'] != "" && $json['to_date'] == "")
            $filter_query .= " and fr.interviewSessionId >= '" . strtotime($json['from_date']) . "'";
        if ($json['from_date'] == "" && $json['to_date'] != "")
            $filter_query .= " and fr.interviewSessionId <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";
        if ($json['from_date'] != "" && $json['to_date'] != "")
            $filter_query .= " and fr.interviewSessionId >= '" . strtotime($json['from_date']) . "' and fr.interviewSessionId <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";

        if ($userType == 'college') {
            $college_query = mysqli_query($databaseConnection, "select u1.* from users u1 where u1.id =" . $json['userId'] . " ");
            $college_result = mysqli_fetch_array($college_query, MYSQLI_ASSOC);
            $filter_query .= " and pd.college in (" . $college_result['college_id'] . ")";
            $rawData .= " inner join raw_data rd on rd.email_id = u.emailId ";
            if ($json['isTieUpStatus'] == 'Y') {
                $filter_query .= " and rd.isPaid = 'Y'";
            } elseif ($json['isTieUpStatus'] == 'F') {
                $filter_query .= " and rd.isPaid = 'F'";
            } elseif ($json['isTieUpStatus'] == 'N') {
                $filter_query .= " and rd.isPaid = 'N'";
            } else {
                $filter_query .= " and rd.isPaid in('Y','F')";
            }
        }
        if ($userType !== 'college') {
            if ($json['isTieUpStatus'] != "") {
                $rawData .= " inner join raw_data rd on rd.email_id = u.emailId ";
                if ($json['isTieUpStatus'] == 'Y') {
                    $filter_query .= " and rd.isPaid = 'Y'";
                } elseif ($json['isTieUpStatus'] == 'F') {
                    $filter_query .= " and rd.isPaid = 'F'";
                } else {
                    $filter_query .= " and rd.isPaid = 'N'";
                }
            }
        }
        if ($userType == 'mentor') {
            $filter_query .= " and pd.assignMentorId in (" . $json['userId'] . ")";
        }
        if ($json['college'] != "" and sizeof($json['college']) > 0) {
            $filter_query .= " and pd.college in ('" . implode("', '", array_map("addSlashToString", $json['college'])) . "')";
            $college_query = mysqli_query($databaseConnection, "SELECT GROUP_CONCAT(collegeName SEPARATOR ', ') as collegeName FROM `colleges` WHERE id in ('" . implode("', '", array_map("addSlashToString", $json['college'])) . "') ");
            $college = mysqli_fetch_array($college_query, MYSQLI_ASSOC);
        }

        //  $query = "SELECT ROUND(AVG(nfr.skillScore),1) as  SkillScore,nfr.key_skill_id,nfr.skillName , nfr.skillSequence as Day_of_practice   from newFeedbackReport nfr inner join feedback_request fr on fr.id = nfr.feedback_request_id inner join users u  on u.id = nfr.candidateId inner join professionaldetails pd on pd.candidateId = u.id  " . $rawData . "  where fr.review_status = 2  " . $filter_query . " group by nfr.key_skill_id,nfr.skillSequence order by  nfr.key_skill_id,nfr.skillSequence";
        /* $query= "SELECT temp1.*, round(time_to_sec(temp1.durationRange)/3600,4) as durationInhr from (SELECT ROUND(AVG(temp.skillScore),1) as  SkillScore,temp.key_skill_id,temp.skillName ,temp.durationRange  from (
             SELECT nfr.skillScore,nfr.key_skill_id,nfr.skillName ,CASE WHEN nfr.cumulativeDuration <= '00:01:00' THEN '00:01:00'  when  nfr.cumulativeDuration > '00:01:00' and nfr.cumulativeDuration <= '00:02:00' THEN '00:02:00'   WHEN     nfr.cumulativeDuration > '00:02:00' and nfr.cumulativeDuration <= '00:03:00' THEN '00:03:00' WHEN  nfr.cumulativeDuration > '00:03:00' and nfr.cumulativeDuration <= '00:04:00' THEN '00:04:00'   WHEN  nfr.cumulativeDuration > '00:04:00' and nfr.cumulativeDuration <= '00:05:00' THEN '00:05:00'     WHEN  nfr.cumulativeDuration > '00:05:00' and nfr.cumulativeDuration <= '00:30:00' THEN '00:30:00'    WHEN  nfr.cumulativeDuration > '00:30:00' and nfr.cumulativeDuration <= '01:00:00' THEN '01:00:00'   WHEN  nfr.cumulativeDuration > '01:00:00' and nfr.cumulativeDuration <= '01:30:00' THEN '01:30:00'     WHEN  nfr.cumulativeDuration > '01:30:00' and nfr.cumulativeDuration <= '02:00:00' THEN '02:00:00'     WHEN  nfr.cumulativeDuration > '02:00:00' and nfr.cumulativeDuration <= '02:30:00' THEN '02:30:00'  WHEN  nfr.cumulativeDuration > '02:30:00' and nfr.cumulativeDuration <= '03:00:00' THEN '03:00:00'    WHEN  nfr.cumulativeDuration  > '03:00:00'  and nfr.cumulativeDuration <= '03:30:00'  THEN '03:30:00'   WHEN  nfr.cumulativeDuration > '03:30:00' and nfr.cumulativeDuration <= '04:00:00' THEN '04:00:00'     WHEN  nfr.cumulativeDuration > '04:00:00' and nfr.cumulativeDuration <= '04:30:00' THEN '04:30:00'     WHEN  nfr.cumulativeDuration > '04:30:00' and nfr.cumulativeDuration <= '05:00:00' THEN '05:00:00'     WHEN  nfr.cumulativeDuration > '05:00:00' and nfr.cumulativeDuration <= '05:30:00' THEN '05:30:00'    WHEN  nfr.cumulativeDuration > '00:30:00' and nfr.cumulativeDuration <= '06:00:00' THEN '06:00:00'     WHEN  nfr.cumulativeDuration > '06:00:00' and nfr.cumulativeDuration <= '06:30:00' THEN '06:30:00'    WHEN  nfr.cumulativeDuration > '06:30:00' and nfr.cumulativeDuration <= '07:00:00' THEN '07:00:00'   WHEN  nfr.cumulativeDuration > '07:00:00' and nfr.cumulativeDuration <= '07:30:00' THEN '07:30:00' WHEN  nfr.cumulativeDuration > '07:30:00' and nfr.cumulativeDuration <= '08:00:00' THEN '08:00:00' WHEN  nfr.cumulativeDuration > '08:00:00' and nfr.cumulativeDuration <= '08:30:00' THEN '08:30:00' WHEN  nfr.cumulativeDuration > '08:30:00' and nfr.cumulativeDuration <= '09:00:00' THEN '09:00:00' WHEN  nfr.cumulativeDuration > '09:00:00' and nfr.cumulativeDuration <= '09:30:00' THEN '09:30:00' WHEN  nfr.cumulativeDuration > '09:30:00' and nfr.cumulativeDuration <= '10:00:00' THEN '10:00:00' WHEN  nfr.cumulativeDuration > '10:00:00' and nfr.cumulativeDuration <= '10:30:00' THEN '10:30:00' WHEN  nfr.cumulativeDuration > '10:30:00' and nfr.cumulativeDuration <= '11:00:00' THEN '11:00:00' WHEN  nfr.cumulativeDuration > '11:00:00' and nfr.cumulativeDuration <= '11:30:00' THEN '11:30:00' WHEN  nfr.cumulativeDuration > '11:30:00' and nfr.cumulativeDuration <= '11:30:00' THEN '11:30:00' WHEN  nfr.cumulativeDuration > '11:30:00' and nfr.cumulativeDuration <= '12:00:00' THEN '12:00:00' WHEN  nfr.cumulativeDuration > '12:00:00'  and nfr.cumulativeDuration <= '12:30:00' THEN '12:30:00' WHEN  nfr.cumulativeDuration > '12:30:00' and nfr.cumulativeDuration <= '13:00:00' THEN '13:00:00' WHEN  nfr.cumulativeDuration > '13:00:00' and nfr.cumulativeDuration <= '13:30:00' THEN '13:30:00' ELSE 'More than 13.30' END as durationRange  from newFeedbackReport nfr inner join feedback_request fr on fr.id = nfr.feedback_request_id inner join users u  on u.id = nfr.candidateId  inner join professionaldetails pd on pd.candidateId = u.id  " . $rawData . "   where fr.review_status = 2  and  nfr.key_skill_id in (1,2,3,6,8)  " . $filter_query . "  order by  nfr.key_skill_id , nfr.cumulativeDuration ) as temp  group by temp.key_skill_id,temp.durationRange order by temp.key_skill_id,temp.durationRange) as temp1";*/


        if ($flag) {
            $fetch = "Select temp.name,temp.mobileNo,temp.email,temp.YOP,temp.college,temp.course,temp.skillName,CASE When temp.SkillScore <=4 THEN 'Need To Improve' else CASE When temp.SkillScore >4 and temp.SkillScore< 7 THEN 'Acceptable' else CASE When temp.SkillScore >=7 THEN 'Good' end end end as 'Status' FROM (SELECT nfr.candidateId , ROUND(AVG(nfr.skillScore),1) as SkillScore,nfr.key_skill_id,nfr.skillName,u.id as id,u.firstName as name,u.mobileNumber as mobileNo,u.emailId as email,pd.year as YOP,c.collegeName as college,s.stream as course from newFeedbackReport nfr inner join feedback_request fr on fr.id = nfr.feedback_request_id inner join users u on u.id = nfr.candidateId inner join professionaldetails pd on pd.candidateId = u.id inner join colleges c on c.id=pd.college inner join stream s on s.id=pd.specialization" . $rawData . " where nfr.key_skill_id in (1,2,3,6,8) and fr.review_status = 2 " . $filter_query . "group by nfr.key_skill_id,nfr.candidateId order by nfr.candidateId, nfr.key_skill_id) as temp ";

            $row = "";
            $candidateCountData1 = "";
            $candidateCountData['totalCandidate'] = "";
            $skillpercentageData = "";
            $result = mysqli_query($databaseConnection, $fetch);

            if (mysqli_num_rows($result) >= 1) {
                $fetch_result = mysqli_fetch_all($result, MYSQLI_ASSOC);
                $to_encode = array(
                    'status' => 1,
                    'result' => "sucess",
                    'data' => $row,
                    'data1' => $candidateCountData1,
                    'details' => $fetch_result,
                    'totalCount' => $candidateCountData['totalCandidate'],
                    'skillReport' => $skillpercentageData
                );
            } else {
                $to_encode = array(
                    'status' => 0,
                    'result' => "error",
                    'errorCode' => "out Error whire retrieving practice information."
                );
            }

        } else {
            $query = "SELECT temp1.*, round(time_to_sec(temp1.durationRange)/3600,1) as durationInhr from (SELECT ROUND(AVG(temp.skillScore),1) as  SkillScore,count(distinct temp.candidateId) as candidateCount,temp.key_skill_id,temp.skillName ,temp.durationRange  from (
                SELECT nfr.candidateId,nfr.skillScore,nfr.key_skill_id,nfr.skillName ,CASE WHEN  nfr.cumulativeDuration <= '00:30:00' THEN '00:30:00'    WHEN  nfr.cumulativeDuration > '00:30:00' and nfr.cumulativeDuration <= '01:00:00' THEN '01:00:00'   WHEN  nfr.cumulativeDuration > '01:00:00' and nfr.cumulativeDuration <= '01:30:00' THEN '01:30:00'     WHEN  nfr.cumulativeDuration > '01:30:00' and nfr.cumulativeDuration <= '02:00:00' THEN '02:00:00'     WHEN  nfr.cumulativeDuration > '02:00:00' and nfr.cumulativeDuration <= '02:30:00' THEN '02:30:00'  WHEN  nfr.cumulativeDuration > '02:30:00' and nfr.cumulativeDuration <= '03:00:00' THEN '03:00:00'    WHEN  nfr.cumulativeDuration  > '03:00:00'  and nfr.cumulativeDuration <= '03:30:00'  THEN '03:30:00'   WHEN  nfr.cumulativeDuration > '03:30:00' and nfr.cumulativeDuration <= '04:00:00' THEN '04:00:00'     WHEN  nfr.cumulativeDuration > '04:00:00' and nfr.cumulativeDuration <= '04:30:00' THEN '04:30:00'     WHEN  nfr.cumulativeDuration > '04:30:00' and nfr.cumulativeDuration <= '05:00:00' THEN '05:00:00'     WHEN  nfr.cumulativeDuration > '05:00:00' and nfr.cumulativeDuration <= '05:30:00' THEN '05:30:00'    WHEN  nfr.cumulativeDuration > '00:30:00' and nfr.cumulativeDuration <= '06:00:00' THEN '06:00:00'     WHEN  nfr.cumulativeDuration > '06:00:00' and nfr.cumulativeDuration <= '06:30:00' THEN '06:30:00'    WHEN  nfr.cumulativeDuration > '06:30:00' and nfr.cumulativeDuration <= '07:00:00' THEN '07:00:00'   WHEN  nfr.cumulativeDuration > '07:00:00' and nfr.cumulativeDuration <= '07:30:00' THEN '07:30:00' WHEN  nfr.cumulativeDuration > '07:30:00' and nfr.cumulativeDuration <= '08:00:00' THEN '08:00:00' WHEN  nfr.cumulativeDuration > '08:00:00' and nfr.cumulativeDuration <= '08:30:00' THEN '08:30:00' WHEN  nfr.cumulativeDuration > '08:30:00' and nfr.cumulativeDuration <= '09:00:00' THEN '09:00:00' WHEN  nfr.cumulativeDuration > '09:00:00' and nfr.cumulativeDuration <= '09:30:00' THEN '09:30:00' WHEN  nfr.cumulativeDuration > '09:30:00' and nfr.cumulativeDuration <= '10:00:00' THEN '10:00:00' WHEN  nfr.cumulativeDuration > '10:00:00' and nfr.cumulativeDuration <= '10:30:00' THEN '10:30:00' WHEN  nfr.cumulativeDuration > '10:30:00' and nfr.cumulativeDuration <= '11:00:00' THEN '11:00:00' WHEN  nfr.cumulativeDuration > '11:00:00' and nfr.cumulativeDuration <= '11:30:00' THEN '11:30:00' WHEN  nfr.cumulativeDuration > '11:30:00' and nfr.cumulativeDuration <= '11:30:00' THEN '11:30:00' WHEN  nfr.cumulativeDuration > '11:30:00' and nfr.cumulativeDuration <= '12:00:00' THEN '12:00:00' WHEN  nfr.cumulativeDuration > '12:00:00'  and nfr.cumulativeDuration <= '12:30:00' THEN '12:30:00' WHEN  nfr.cumulativeDuration > '12:30:00' and nfr.cumulativeDuration <= '13:00:00' THEN '13:00:00' WHEN  nfr.cumulativeDuration > '13:00:00' and nfr.cumulativeDuration <= '13:30:00' THEN '13:30:00' ELSE 'More than 13.30' END as durationRange  from newFeedbackReport nfr inner join feedback_request fr on fr.id = nfr.feedback_request_id inner join users u  on u.id = nfr.candidateId  inner join professionaldetails pd on pd.candidateId = u.id  " . $rawData . "   where fr.review_status = 2  and  nfr.key_skill_id in (1,2,3,6,8)  " . $filter_query . "  order by  nfr.key_skill_id , nfr.cumulativeDuration ) as temp  group by temp.key_skill_id,temp.durationRange order by temp.key_skill_id,temp.durationRange) as temp1";




            $candidateCountQuery = "Select count(distinct nfr.candidateId) as totalCandidate from newFeedbackReport nfr inner join feedback_request fr on fr.id = nfr.feedback_request_id inner join professionaldetails pd inner join users u on u.id = pd.candidateId " . $rawData . " where fr.id = nfr.feedback_request_id and pd.candidateId = fr.candidateId and fr.review_status = 2 and nfr.key_skill_id in (1,2,3,6,8) ";
            $candidateCountResult = mysqli_query($databaseConnection, $candidateCountQuery . $filter_query);
            $candidateCountData = mysqli_fetch_assoc($candidateCountResult);


            $candidateCountQuery1 = "Select nfr.skillName,nfr.key_skill_id,count(distinct nfr.candidateId) as totalCandidate from newFeedbackReport nfr inner join feedback_request fr on fr.id = nfr.feedback_request_id inner join professionaldetails pd inner join users u on u.id = pd.candidateId " . $rawData . " where fr.id = nfr.feedback_request_id and pd.candidateId = fr.candidateId and fr.review_status = 2 and nfr.key_skill_id in (1,2,3,6,8) " . $filter_query . "   group by nfr.key_skill_id order by nfr.key_skill_id ";
            $candidateCountResult1 = mysqli_query($databaseConnection, $candidateCountQuery1);
            $candidateCountData1 = mysqli_fetch_all($candidateCountResult1, MYSQLI_ASSOC);



            $skillpercentageQuery = "Select (Count(DISTINCT CASE When temp.SkillScore <=4 THEN temp.candidateId ELSE NULL END))/(Count(DISTINCT CASE When temp.SkillScore > 0  and  temp.SkillScore <= 10 THEN temp.candidateId ELSE NULL END)) as NeedsImprove, (Count(DISTINCT CASE When temp.SkillScore >4 and  temp.SkillScore< 7 THEN temp.candidateId ELSE NULL END))/(Count(DISTINCT CASE When temp.SkillScore >0 and  temp.SkillScore <= 10 THEN temp.candidateId ELSE NULL END)) as Acceptable, (Count(DISTINCT CASE When temp.SkillScore >=7 THEN temp.candidateId ELSE NULL END))/(Count(DISTINCT CASE When temp.SkillScore > 0 and  temp.SkillScore <= 10 THEN temp.candidateId ELSE NULL END)) as Good,temp.key_skill_id  ,temp.skillName, Count(DISTINCT CASE When temp.SkillScore <=4 THEN temp.candidateId ELSE NULL END) as NCount,Count(DISTINCT CASE When temp.SkillScore >4 and  temp.SkillScore< 7 THEN temp.candidateId ELSE NULL END) as ACount, Count(DISTINCT CASE When temp.SkillScore >=7 THEN temp.candidateId ELSE NULL END) as GCount  FROM (SELECT nfr.candidateId , ROUND(AVG(nfr.skillScore),1) as  SkillScore,nfr.key_skill_id,nfr.skillName    from newFeedbackReport nfr inner join feedback_request fr on fr.id = nfr.feedback_request_id inner join users u  on u.id = nfr.candidateId inner join professionaldetails pd on pd.candidateId = u.id   " . $rawData . " where nfr.key_skill_id in (1,2,3,6,8) and fr.review_status = 2  " . $filter_query . "  group by nfr.key_skill_id,nfr.candidateId order by nfr.candidateId, nfr.key_skill_id) as temp  group by  temp.key_skill_id order by temp.key_skill_id";

            $fetch_result = "";
            $skillpercentageResult = mysqli_query($databaseConnection, $skillpercentageQuery);
            $skillpercentageData = mysqli_fetch_all($skillpercentageResult, MYSQLI_ASSOC);
            $query_result = mysqli_query($databaseConnection, $query);
            if (mysqli_num_rows($query_result) >= 1) {
                $row = mysqli_fetch_all($query_result, MYSQLI_ASSOC);
                $to_encode = array(
                    'status' => 1,
                    'result' => "sucess",
                    'data' => $row,
                    'data1' => $candidateCountData1,
                    'details' => $fetch_result,
                    'totalCount' => $candidateCountData['totalCandidate'],
                    'skillReport' => $skillpercentageData
                );
            } else {
                $to_encode = array(
                    'status' => 0,
                    'result' => "error",
                    'errorCode' => "out Error whire retrieving practice information."
                );
            }
        }

        // //    $queryPlateFormQuery = "SELECT ROUND(AVG(nfr.skillScore),1) as  SkillScore,nfr.key_skill_id,nfr.skillName , nfr.skillSequence  as Day_of_practice from newFeedbackReport nfr inner join feedback_request fr on fr.id = nfr.feedback_request_id inner join users u  on u.id = nfr.candidateId inner join professionaldetails pd on pd.candidateId = u.id where fr.review_status = 2  group by nfr.key_skill_id,nfr.skillSequence order by  nfr.key_skill_id,nfr.skillSequence";
        //    $queryPlate_result = mysqli_query($databaseConnection, $queryPlateFormQuery);
        //    if (mysqli_num_rows($queryPlate_result) >= 1) {
        //         $row1 = mysqli_fetch_all($queryPlate_result, MYSQLI_ASSOC);
        //    }


        // $query = "SELECT nfr.SkillScore,nfr.key_skill_id,nfr.skillName, ROUND((SUM(TIME_TO_SEC(nfr.cumulativeDuration)+TIME_TO_SEC(nfr.contentConsumed))/count(nfr.SkillScore))/3600,2) as DurationAvg from newFeedbackReport nfr inner join feedback_request fr on fr.id = nfr.feedback_request_id inner join users u  on u.id = nfr.candidateId inner join professionaldetails pd on pd.candidateId = u.id " . $rawData . "  where fr.review_status = 2  " . $filter_query . " group by nfr.key_skill_id,nfr.skillScore order by nfr.key_skill_id,nfr.skillScore";

    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error whire retrieving practice information."
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getObservationAreaReportData'])) {
    /* this New API is Added By Narayan For getting Observation Area ReportData in Jan 2022 */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $filter_query = " ";
        $college = array();
        $values = array();
        $rawData = " ";

        if ($json['stream'] != "" and sizeof($json['stream']) > 0)
            $filter_query .= " and pd.specialization in ('" . implode("', '", $json['stream']) . "')";
        if ($json['yop'] != "")
            $filter_query .= " and pd.year in (" . $json['yop'] . ")";
        /* if($json['from_date']!="" && $json['to_date']=="")
            $filter_query.=" and u.createdOn >= '".strtotime($json['from_date'])."'";
        if($json['from_date']=="" && $json['to_date']!="")
            $filter_query.=" and u.createdOn <= '".strtotime('+1 day', strtotime($json['to_date']))."'";
        if($json['from_date']!="" && $json['to_date']!="")
            $filter_query.=" and u.createdOn >= '".strtotime($json['from_date'])."' and u.createdOn <= '".strtotime('+1 day', strtotime($json['to_date']))."'";*/
        if ($json['from_date'] != "" && $json['to_date'] == "")
            $filter_query .= " and fr.interviewSessionId >= '" . strtotime($json['from_date']) . "'";
        if ($json['from_date'] == "" && $json['to_date'] != "")
            $filter_query .= " and fr.interviewSessionId <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";
        if ($json['from_date'] != "" && $json['to_date'] != "")
            $filter_query .= " and fr.interviewSessionId >= '" . strtotime($json['from_date']) . "' and fr.interviewSessionId <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";

        if ($userType == 'college') {
            $college_query = mysqli_query($databaseConnection, "select u1.* from users u1 where u1.id =" . $json['userId'] . " ");
            $college_result = mysqli_fetch_array($college_query, MYSQLI_ASSOC);
            $filter_query .= " and pd.college in (" . $college_result['college_id'] . ")";
            $rawData .= " inner join raw_data rd on rd.email_id = u.emailId ";
            if ($json['isTieUpStatus'] == 'Y') {
                $filter_query .= " and rd.isPaid = 'Y'";
            } elseif ($json['isTieUpStatus'] == 'F') {
                $filter_query .= " and rd.isPaid = 'F'";
            } elseif ($json['isTieUpStatus'] == 'N') {
                $filter_query .= " and rd.isPaid = 'N'";
            } else {
                $filter_query .= " and rd.isPaid in('Y','F')";
            }

        }
        if ($userType !== 'college') {
            if ($json['isTieUpStatus'] != "") {
                $rawData .= " inner join raw_data rd on rd.email_id = u.emailId ";
                if ($json['isTieUpStatus'] == 'Y') {
                    $filter_query .= " and rd.isPaid = 'Y'";
                } elseif ($json['isTieUpStatus'] == 'F') {
                    $filter_query .= " and rd.isPaid = 'F'";
                } else {
                    $filter_query .= " and rd.isPaid = 'N'";
                }
            }
        }
        if ($userType == 'mentor') {
            $filter_query .= " and pd.assignMentorId in (" . $json['userId'] . ")";
        }
        if ($json['college'] != "" and sizeof($json['college']) > 0) {
            $filter_query .= " and pd.college in ('" . implode("', '", array_map("addSlashToString", $json['college'])) . "')";
            $college_query = mysqli_query($databaseConnection, "SELECT GROUP_CONCAT(collegeName SEPARATOR ', ') as collegeName FROM `colleges` WHERE id in ('" . implode("', '", array_map("addSlashToString", $json['college'])) . "') ");
            $college = mysqli_fetch_array($college_query, MYSQLI_ASSOC);
        }

        $query = "SELECT temp1.key_skill as SkillName,temp1.observationAreaId, temp1.observation_name as ObservationArea,count(CASE WHEN temp1.observation_type = 1 THEN temp1.observation_name ELSE NULL END) as Good ,count(CASE WHEN temp1.observation_type = 0 THEN temp1.observation_name ELSE NULL END) as NeedsImprovement, (count(CASE WHEN temp1.observation_type  = 0 THEN temp1.observation_name ELSE NULL END)) / (count(CASE WHEN temp1.observation_type  is not Null THEN temp1.observation_name ELSE NULL END)) as ImprovePercentage, count(CASE WHEN temp1.observation_type  is not Null THEN temp1.observation_name ELSE NULL END) as TotalCount from (select u.id as userId,er.feedback_request_id,er.questionId,ks.key_skill,oa.observation_type,oa.observation_name,erod.observationAreaId from feedback_request fr inner join expert_review er on er.feedback_request_id = fr.id  inner join expert_review_observation_details erod  on erod.expertReviewId  =  er.id inner join observation_area oa on oa.id = erod.observationAreaId inner join key_skill ks on ks.id = oa.key_skill inner join users u on u.id = fr.candidateId  inner join interview  i on i.id = fr.interviewId inner join professionaldetails pd on pd.candidateId = u.id  " . $rawData . " where fr.review_status = 2  and  er.overAllRating !='VideoIssue' and er.overAllRating is not null  and  fr.id in (select max(id) from feedback_request where review_status = 2 group by candidateId) and er.review_type='question'  and  oa.key_skill !=0 and oa.observation_name !='others' and oa.observation_name !='Nothing' and oa.mandatory = 0 and oa.key_skill in (1,2,6,8,3)  " . $filter_query . " group by er.feedback_request_id,er.questionId,oa.key_skill,erod.observationAreaId order by  er.feedback_request_id,oa.key_skill,oa.observation_name) temp1 group by SkillName,ObservationArea order by TotalCount;
        ";
        //limit add for time reducing 
        $query_result = mysqli_query($databaseConnection, $query);
        if (mysqli_num_rows($query_result) >= 1) {
            $row = mysqli_fetch_all($query_result, MYSQLI_ASSOC);
            $to_encode = array(
                'status' => 1,
                'result' => "sucess",
                'data' => $row
            );
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "out Error whire retrieving practice information."
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error whire retrieving practice information."
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getSubscriptionDetailsData'])) {
    /* this New API is Added By Narayan For getting tie up subscription data in Jan 2022 */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $filter_query = " ";
        $college = array();
        $values = array();
        $rawData = " ";

        if ($json['stream'] != "" and sizeof($json['stream']) > 0)
            $filter_query .= " and cs.streamId in ('" . implode("', '", $json['stream']) . "')";
        if ($json['yop'] != "")
            $filter_query .= " and cs.yop in (" . $json['yop'] . ")";

        if ($userType == 'college') {
            $college_query = mysqli_query($databaseConnection, "select u1.college_id from users u1 where u1.id =" . $json['userId'] . " ");
            $college_result = mysqli_fetch_array($college_query, MYSQLI_ASSOC);
            $filter_query .= " and c.id in (" . $college_result['college_id'] . ")";

        }

        if ($json['college'] != "" and sizeof($json['college']) > 0) {
            $filter_query .= " and cs.collegeId in ('" . implode("', '", array_map("addSlashToString", $json['college'])) . "')";
            $college_query = mysqli_query($databaseConnection, "SELECT GROUP_CONCAT(collegeName SEPARATOR ', ') as collegeName FROM `colleges` WHERE id in ('" . implode("', '", array_map("addSlashToString", $json['college'])) . "') ");
            $college = mysqli_fetch_array($college_query, MYSQLI_ASSOC);
        }

        $query = "select  cs.freeTrialAllowed,cs.subscriptionEndDate, CASE WHEN DATEDIFF(cs.subscriptionEndDate,CURDATE()) > 0 THEN 'Active' ELSE 'Expired' END  as subStatus ,cs.mockInterviewAllowed,cs.communicationInterviewAllowed,cs.behaviouralInterviewAllowed,cs.problemsolvingInterviewAllowed,cs.codingInterviewAllowed , (select count(Distinct id) as totalCount from raw_data where isPaid in ('Y','F') and college_name = c.collegeName) as    totalStudentsEnrolled from college_subscription cs inner join colleges c on c.id = cs.collegeId    where cs.amount !='0'   " . $filter_query . "  group by cs.collegeId";
        $query_result = mysqli_query($databaseConnection, $query);

        if (mysqli_num_rows($query_result) >= 1) {
            $data1 = "Select id,name from product order by id";
            $dataresult = mysqli_query($databaseConnection, $data1);
            while ($row = mysqli_fetch_array($dataresult, MYSQLI_ASSOC)) {
                $query1 = "select  DATE_FORMAT(cs.subscriptionEndDate, '%d %b, %Y') as endDate, CASE WHEN DATEDIFF(cs.subscriptionEndDate,CURDATE()) > 0 THEN 'Active' ELSE 'Expired' END  as subStatus , cs.mockInterviewAllowed,cs.communicationInterviewAllowed,cs.behaviouralInterviewAllowed,cs.problemsolvingInterviewAllowed,cs.codingInterviewAllowed ,cs.freeTrialAllowed, (select count(Distinct id) as totalCount from raw_data where isPaid in('Y','F') and college_name = c.collegeName) as totalStudentsEnrolled from college_subscription cs inner join colleges c on c.id = cs.collegeId    where 1  " . $filter_query . "  group by cs.collegeId";
                $queryResult = mysqli_query($databaseConnection, $query1);
                $values1 = mysqli_fetch_all($queryResult, MYSQLI_ASSOC);

                if ($row['id'] == 1) {
                    $row['TotalInterviewAllowed'] = $values1[0]['mockInterviewAllowed'];
                }
                if ($row['id'] == 2) {
                    $row['TotalInterviewAllowed'] = $values1[0]['communicationInterviewAllowed'];
                }
                if ($row['id'] == 3) {
                    $row['TotalInterviewAllowed'] = $values1[0]['behaviouralInterviewAllowed'];
                }
                if ($row['id'] == 4) {
                    $row['TotalInterviewAllowed'] = $values1[0]['problemsolvingInterviewAllowed'];
                }
                if ($row['id'] == 5) {
                    $row['TotalInterviewAllowed'] = $values1[0]['codingInterviewAllowed'];
                }
                if ($row['id'] == 6) {
                    $row['TotalInterviewAllowed'] = $values1[0]['freeTrialAllowed'];
                }
                $row['subscriptionEndDate'] = $values1[0]['endDate'];
                $row['subStatus'] = $values1[0]['subStatus'];
                $row['totalStudentsEnrolled'] = $values1[0]['totalStudentsEnrolled'];
                array_push($values, $row);


            }
            $to_encode = array(
                'status' => 1,
                'result' => "sucess",
                'data' => $values
            );
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "out Error whire retrieving practice information."
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error whire retrieving practice information."
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getFeedbackProvidedByData'])) {
    /* this New API is Added By Narayan For getting FeedbackProvided by expert on COllege Dashboard and college Report For Mock Interview  in Jan 2022 */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $filter_query = " ";
        $college = array();
        $values = array();
        $rawData = " ";

        if ($json['stream'] != "" and sizeof($json['stream']) > 0)
            $filter_query .= " and pd.specialization in ('" . implode("', '", $json['stream']) . "')";
        if ($json['yop'] != "")
            $filter_query .= " and pd.year in (" . $json['yop'] . ")";
        if ($json['from_date'] != "" && $json['to_date'] == "")
            $filter_query .= " and fr.interviewSessionId >= '" . strtotime($json['from_date']) . "'";
        if ($json['from_date'] == "" && $json['to_date'] != "")
            $filter_query .= " and fr.interviewSessionId <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";
        if ($json['from_date'] != "" && $json['to_date'] != "")
            $filter_query .= " and fr.interviewSessionId >= '" . strtotime($json['from_date']) . "' and fr.interviewSessionId <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";

        if ($userType == 'college') {
            $college_query = mysqli_query($databaseConnection, "select u1.* from users u1 where u1.id =" . $json['userId'] . " ");
            $college_result = mysqli_fetch_array($college_query, MYSQLI_ASSOC);
            $filter_query .= " and pd.college in (" . $college_result['college_id'] . ")";
            $rawData .= " inner join raw_data rd on rd.email_id = u.emailId ";
            if ($json['isTieUpStatus'] == 'Y') {
                $filter_query .= " and rd.isPaid = 'Y'";
            } elseif ($json['isTieUpStatus'] == 'F') {
                $filter_query .= " and rd.isPaid = 'F'";
            } elseif ($json['isTieUpStatus'] == 'N') {
                $filter_query .= " and rd.isPaid = 'N'";
            } else {
                $filter_query .= " and rd.isPaid in('Y','F')";
            }

        }
        if ($userType != 'college') {
            if ($json['isTieUpStatus'] != "") {
                $rawData .= " inner join raw_data rd on rd.email_id = u.emailId ";
                if ($json['isTieUpStatus'] == 'Y') {
                    $filter_query .= " and rd.isPaid = 'Y'";
                } elseif ($json['isTieUpStatus'] == 'F') {
                    $filter_query .= " and rd.isPaid = 'F'";
                } else {
                    $filter_query .= " and rd.isPaid = 'N'";
                }
            }
        }
        if ($userType == 'mentor') {
            $filter_query .= " and pd.assignMentorId in (" . $json['userId'] . ")";
        }
        if ($json['college'] != "" and sizeof($json['college']) > 0) {
            $filter_query .= " and pd.college in ('" . implode("', '", array_map("addSlashToString", $json['college'])) . "')";
            $college_query = mysqli_query($databaseConnection, "SELECT GROUP_CONCAT(collegeName SEPARATOR ', ') as collegeName FROM `colleges` WHERE id in ('" . implode("', '", array_map("addSlashToString", $json['college'])) . "') ");
            $college = mysqli_fetch_array($college_query, MYSQLI_ASSOC);
        }

        //    $query = "select er.feedbackGivenBy as ExpertId , p.name as ExpertName, p.linkedinProfile,p.companiesWorked from expert_review er inner join feedback_request fr on fr.id = er.feedback_request_id inner join users u on u.id = er.candidateId inner join professionaldetails pd on pd.candidateId = u.id  inner join panel p on p.id = er.feedbackGivenBy ". $rawData ." where fr.review_status= 2 and  er.review_type='question' and er.overAllRating !='videoIssue' and er.feedbackGivenBy !=62  " . $filter_query . "  group by er.feedbackGivenBy order by p.name";


        // $query = "select s.id,s.name as sectorName , count(Distinct er.feedbackGivenBy) as totalCount,GROUP_CONCAT(Distinct p.companiesWorked) as companiesWorked from expert_review er inner join questions q on q.id = er.questionId inner join scps_transaction st on st.subject = q.subjectId  inner join sector s on s.id = st.sector inner join feedback_request fr on fr.id = er.feedback_request_id inner join users u on u.id = er.candidateId inner join professionaldetails pd on pd.candidateId = u.id  inner join panel p on p.id = er.feedbackGivenBy ". $rawData ." where fr.review_status= 2 and  er.review_type='question' and er.overAllRating !='videoIssue' and er.feedbackGivenBy !=62    and p.companiesWorked !='' and p.companiesWorked is not null    " . $filter_query . "  group by st.sector order by st.sector";

        $query = "select count(distinct er.feedbackGivenBy) as expertCount from expert_review er inner join feedback_request fr on fr.id = er.feedback_request_id inner join users u on u.id = er.candidateId inner join professionaldetails pd on pd.candidateId = u.id  inner join panel p on p.id = er.feedbackGivenBy " . $rawData . " where fr.review_status= 2 and  er.review_type='question' and er.overAllRating !='videoIssue' and er.feedbackGivenBy !=62 " . $filter_query;

        $query_result = mysqli_query($databaseConnection, $query);
        if (mysqli_num_rows($query_result) >= 1) {
            while ($row = mysqli_fetch_array($query_result, MYSQLI_ASSOC)) {
                $query_e = "select er.feedbackGivenBy as ExpertId , p.name as ExpertName, p.linkedinProfile,p.companiesWorked from expert_review er   inner join feedback_request fr on fr.id = er.feedback_request_id inner join users u on u.id = er.candidateId inner join professionaldetails pd on pd.candidateId = u.id  inner join panel p on p.id = er.feedbackGivenBy " . $rawData . " where fr.review_status= 2 and  er.review_type='question' and er.overAllRating !='videoIssue' and er.feedbackGivenBy !=62   " . $filter_query . "  group by er.feedbackGivenBy order by p.name";
                $querye_result = mysqli_query($databaseConnection, $query_e);
                $row['expertDetails'] = mysqli_fetch_all($querye_result, MYSQLI_ASSOC);

                array_push($values, $row);
            }

            $to_encode = array(
                'status' => 1,
                'result' => "sucess",
                'data' => $values
            );
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "out Error whire retrieving practice information."
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error whire retrieving practice information."
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getEmployabilityReportData'])) {
    /* this New API is Added By Narayan For getting Employability Report For Mock Interview  in Jan 2022 */
    $data = @file_get_contents("php://input");
    $details = @file_get_contents("php://input");
    $json = json_decode($data, true);
    $json1 = json_decode($details, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $sectorId = $json['sector_id'];
        $empstatus = $json['empstatus'];
        $flag = $json['flag'];
        $filter_query = " ";
        $college = array();
        $values = array();
        $rawData = " ";
        if ($json['stream'] != "" and sizeof($json['stream']) > 0)
            $filter_query .= " and pd.specialization in ('" . implode("', '", $json['stream']) . "')";
        if ($json['yop'] != "")
            $filter_query .= " and pd.year in (" . $json['yop'] . ")";
        if ($json['from_date'] != "" && $json['to_date'] == "")
            $filter_query .= " and ces.interviewSessionId >= '" . strtotime($json['from_date']) . "'";
        if ($json['from_date'] == "" && $json['to_date'] != "")
            $filter_query .= " and ces.interviewSessionId <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";
        if ($json['from_date'] != "" && $json['to_date'] != "")
            $filter_query .= " and ces.interviewSessionId >= '" . strtotime($json['from_date']) . "' and ces.interviewSessionId <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";

        if ($userType == 'college') {
            $college_query = mysqli_query($databaseConnection, "select u1.* from users u1 where u1.id =" . $json['userId'] . " ");
            $college_result = mysqli_fetch_array($college_query, MYSQLI_ASSOC);
            $filter_query .= " and pd.college in (" . $college_result['college_id'] . ")";
            $rawData .= " inner join raw_data rd on rd.email_id = u.emailId ";
            if ($json['isTieUpStatus'] == 'Y') {
                $filter_query .= " and rd.isPaid = 'Y'";
            } elseif ($json['isTieUpStatus'] == 'F') {
                $filter_query .= " and rd.isPaid = 'F'";
            } elseif ($json['isTieUpStatus'] == 'N') {
                $filter_query .= " and rd.isPaid = 'N'";
            } else {
                $filter_query .= " and rd.isPaid in('Y','F')";
            }

        }
        if ($userType != 'college') {
            if ($json['isTieUpStatus'] != "") {
                $rawData .= " inner join raw_data rd on rd.email_id = u.emailId ";
                if ($json['isTieUpStatus'] == 'Y') {
                    $filter_query .= " and rd.isPaid = 'Y'";
                } elseif ($json['isTieUpStatus'] == 'F') {
                    $filter_query .= " and rd.isPaid = 'F'";
                } else {
                    $filter_query .= " and rd.isPaid = 'N'";
                }
            }
        }
        if ($userType == 'mentor') {
            $filter_query .= " and pd.assignMentorId in (" . $json['userId'] . ")";
        }
        if ($json['college'] != "" and sizeof($json['college']) > 0) {
            $filter_query .= " and pd.college in ('" . implode("', '", array_map("addSlashToString", $json['college'])) . "')";
            $college_query = mysqli_query($databaseConnection, "SELECT GROUP_CONCAT(collegeName SEPARATOR ', ') as collegeName FROM `colleges` WHERE id in ('" . implode("', '", array_map("addSlashToString", $json['college'])) . "') ");
            $college = mysqli_fetch_array($college_query, MYSQLI_ASSOC);
        }

        /*   if ($sectorId != '') {
              $filter_query .= " AND ces.sectorId In (". $sectorid .")";
          }
          if ($empStatus != '') {
              $filter_query .= "AND ces.empstatus in('".$empstatus."')";
          } */
        // $query = "select temp.candidateId, count(temp.candidateId) as countsector  , (Select value as status from ier_for_sector where sector_id =temp.sector_id and score >= temp.aptitudeScore limit 1  ) as Status , temp.sector_id,temp.name from (select er.candidateId,ROUND(AVG(er.overallRating),1) as aptitudeScore, i.sector_id, s.name from expert_review er inner join feedback_request fr on  fr.id = er.feedback_request_id inner join users u on u.id = er.candidateId inner join professionaldetails pd on pd.candidateId = u.id inner " . $rawData . " join interview i on i.id = er.interviewId  inner join sector s on s.id = i.sector_id  where fr.review_status =2 and er.review_type='question' and i.productId = 1 and  er.overAllRating !='videoIssue' " . $filter_query . "  group by er.candidateId , i.sector_id order by er.candidateId,i.sector_id) as temp";


        //    $query = "select COUNT(DISTINCT CASE WHEN Status ='Not Fit' THEN temp1.candidateId ELSE NULL END) as NotReady,COUNT(DISTINCT CASE WHEN Status ='Best Fit' THEN temp1.candidateId ELSE NULL END) as Ready,COUNT(DISTINCT CASE WHEN Status ='Possible Fit' THEN temp1.candidateId ELSE NULL END) as Possible Fit,temp1.sector_id,temp1.name from (select temp.candidateId , CASE WHEN temp.aptitudeScore <=4 THEN (Select value as status from ier_for_sector where sector_id =temp.sector_id and score <=4 limit 1)  WHEN  temp.aptitudeScore > 4 and temp.aptitudeScore < 7   THEN (Select value as status from ier_for_sector where sector_id =temp.sector_id and score > 4 and score < 7  limit 1) WHEN  temp.aptitudeScore >= 7 THEN (Select value as status from ier_for_sector where sector_id =temp.sector_id and score >=7 limit 1) ELSE NULL END as Status , temp.sector_id,temp.name from (select er.candidateId,ROUND(AVG(er.overallRating),1) as aptitudeScore, i.sector_id, s.name from expert_review er inner join feedback_request fr on  fr.id = er.feedback_request_id inner join users u on u.id = er.candidateId inner join professionaldetails pd on pd.candidateId = u.id " . $rawData . " inner join interview i on i.id = er.interviewId  inner join sector s on s.id = i.sector_id  where fr.review_status =2 and er.review_type='question' and i.productId = 1 and  er.overAllRating !='videoIssue'   " . $filter_query . " group by er.candidateId , i.sector_id order by er.candidateId,aptitudeScore desc,i.sector_id) as temp group by temp.candidateId) as temp1 group by temp1.sector_id";

        //    $countquery = "select  COUNT(Distinct CASE  WHEN fr.id is not null and  fr.review_status = 2 and i.productId =1 and i.sector_id  is not null  THEN u.id ELSE NUll END) as Participate from users u  inner join professionaldetails pd on pd.candidateId = u.id " . $rawData . " inner join feedback_request fr on  fr.candidateId = u.id inner join interview i on i.id = fr.interviewId  inner join sector s on s.id = i.sector_id  where  u.deleted_at is null " . $filter_query . " ";



        // added by arun for getting user details


        if ($flag) {
            $details = "select u.firstName as Name, u.emailId, u.mobileNumber, st.stream as Stream,pd.year,cl.collegeName AS college,CASE WHEN ces.sectorId is not null then (SELECT name as sectorName FROM sector where id = ces.sectorId) else null end as sectorName,CASE WHEN ces.empstatus is not null and ces.empstatus='Not Fit' then 'Not Fit' else CASE WHEN ces.empstatus is not null and ces.empstatus='Best Fit'then 'Best Fit' else CASE WHEN ces.empstatus is not null and ces.empstatus='Possible Fit' then 'Possible Fit' 
       end end end as Emp_status from  candidateEmp_status ces inner join users u on u.id = ces.candidateId inner join professionaldetails pd on pd.candidateId = u.id " . $rawData . "inner join sector s on s.id = ces.sectorId  inner join stream st on st.id=pd.specialization inner join colleges cl on cl.id=pd.college where ces.sectorId IN (1,2,3,4,6,10) AND ces.empstatus in ('Not Fit','Best Fit','Possible Fit',' ') " . $filter_query . " order by u.firstName";


            $sec_details = "select u.firstName as Name, u.emailId, u.mobileNumber, st.stream as Stream,pd.year,cl.collegeName AS college,CASE WHEN ces.sectorId is not null then (SELECT name as sectorName FROM sector where id = ces.sectorId) else null end as sectorName,CASE WHEN ces.empstatus is not null and ces.empstatus='Not Fit' then 'Not Fit' else CASE WHEN ces.empstatus is not null and ces.empstatus='Best Fit'then 'Best Fit' else CASE WHEN ces.empstatus is not null and ces.empstatus='Possible Fit' then 'Possible Fit' end end end as Emp_status from  candidateEmp_status ces inner join users u on u.id = ces.candidateId inner join professionaldetails pd on pd.candidateId = u.id " . $rawData . "inner join sector s on s.id = ces.sectorId  inner join stream st on st.id=pd.specialization inner join colleges cl on cl.id=pd.college where ces.sectorId IN (" . $sectorId . ") AND ces.empstatus in ('" . $empstatus . "') " . $filter_query . " order by u.firstName";
            //    echo $sec_details;

            $detail_result = mysqli_query($databaseConnection, $details);

            $sec_detail_result = mysqli_query($databaseConnection, $sec_details);
            $sec_fetching = mysqli_fetch_all($sec_detail_result, MYSQLI_ASSOC);

            $query_result = "";
            $countquery_result = "";
            if (mysqli_num_rows($detail_result) >= 1) {
                $fetching = mysqli_fetch_all($detail_result, MYSQLI_ASSOC);
                $to_encode = array(
                    'status' => 1,
                    'result' => "sucess",
                    'data' => $query_result,
                    'details' => $fetching,
                    'empstatuswise' => $sec_fetching,
                    'countData' => $countquery_result
                );
            } else {
                $to_encode = array(
                    'status' => 0,
                    'result' => "error",
                    'errorCode' => "out Error whire retrieving practice information."
                );
            }
        } else {
            $sec_fetching = "";
            $fetching = "";
            $query = "select COUNT(DISTINCT CASE WHEN empstatus ='Not Fit' THEN ces.candidateId ELSE NULL END) as NotReady,COUNT(DISTINCT CASE WHEN empstatus ='Best Fit' THEN ces.candidateId ELSE NULL END) as Ready,COUNT(DISTINCT CASE WHEN empstatus ='Possible Fit' THEN ces.candidateId ELSE NULL END) as PossibleFit, ces.sectorId as sector_id, s.name from candidateEmp_status ces inner join users u on u.id = ces.candidateId inner join professionaldetails pd on pd.candidateId = u.id " . $rawData . "  inner join sector s on s.id = ces.sectorId  where 1    " . $filter_query . "  group by ces.sectorId order by ces.sectorId";

            $countquery = "select  COUNT(Distinct ces.candidateId ) as Participate from candidateEmp_status ces inner join  users u  on u.id = ces.candidateId  inner join professionaldetails pd on pd.candidateId = u.id " . $rawData . "  inner join sector s on s.id = ces.sectorId  where  u.deleted_at is null " . $filter_query . " ";

            $query_result = mysqli_query($databaseConnection, $query);
            $countquery_result = mysqli_query($databaseConnection, $countquery);
            $result = mysqli_fetch_all($countquery_result, MYSQLI_ASSOC);
            if (mysqli_num_rows($query_result) >= 1) {
                $row = mysqli_fetch_all($query_result, MYSQLI_ASSOC);
                $to_encode = array(
                    'status' => 1,
                    'result' => "sucess",
                    'data' => $row,
                    'details' => $fetching,
                    'empstatuswise' => $sec_fetching,
                    'countData' => $result
                );
            } else {
                $to_encode = array(
                    'status' => 0,
                    'result' => "error",
                    'errorCode' => "out Error whire retrieving practice information."
                );
            }
        }

    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error whire retrieving practice information."
        );
    }
    echo json_encode($to_encode);

} elseif (isset($_GET['getAptitudeReportData'])) {
    /* this New API is Added By Narayan For getting Aptitude Report Subject wise  in Jan 2022 */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $filter_query = " ";
        $flag = $json['flag'];
        $college = array();
        $values = array();
        $rawData = " ";

        if ($json['stream'] != "" and sizeof($json['stream']) > 0)
            $filter_query .= " and pd.specialization in ('" . implode("', '", $json['stream']) . "')";
        if ($json['yop'] != "")
            $filter_query .= " and pd.year in (" . $json['yop'] . ")";
        if ($json['from_date'] != "" && $json['to_date'] == "")
            $filter_query .= " and fr.interviewSessionId >= '" . strtotime($json['from_date']) . "'";
        if ($json['from_date'] == "" && $json['to_date'] != "")
            $filter_query .= " and fr.interviewSessionId <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";
        if ($json['from_date'] != "" && $json['to_date'] != "")
            $filter_query .= " and fr.interviewSessionId >= '" . strtotime($json['from_date']) . "' and fr.interviewSessionId <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";

        if ($userType == 'college') {
            $college_query = mysqli_query($databaseConnection, "select u1.* from users u1 where u1.id =" . $json['userId'] . " ");
            $college_result = mysqli_fetch_array($college_query, MYSQLI_ASSOC);
            $filter_query .= " and pd.college in (" . $college_result['college_id'] . ")";
            $rawData .= " inner join raw_data rd on rd.email_id = u.emailId ";
            if ($json['isTieUpStatus'] == 'Y') {
                $filter_query .= " and rd.isPaid = 'Y'";
            } elseif ($json['isTieUpStatus'] == 'F') {
                $filter_query .= " and rd.isPaid = 'F'";
            } elseif ($json['isTieUpStatus'] == 'N') {
                $filter_query .= " and rd.isPaid = 'N'";
            } else {
                $filter_query .= " and rd.isPaid in('Y','F')";
            }
        }
        if ($userType != 'college') {
            if ($json['isTieUpStatus'] != "") {
                $rawData .= " inner join raw_data rd on rd.email_id = u.emailId ";
                if ($json['isTieUpStatus'] == 'Y') {
                    $filter_query .= " and rd.isPaid = 'Y'";
                } elseif ($json['isTieUpStatus'] == 'F') {
                    $filter_query .= " and rd.isPaid = 'F'";
                } else {
                    $filter_query .= " and rd.isPaid = 'N'";
                }
            }
        }
        if ($userType == 'mentor') {
            $filter_query .= " and pd.assignMentorId in (" . $json['userId'] . ")";
        }
        if ($json['college'] != "" and sizeof($json['college']) > 0) {
            $filter_query .= " and pd.college in ('" . implode("', '", array_map("addSlashToString", $json['college'])) . "')";
            $college_query = mysqli_query($databaseConnection, "SELECT GROUP_CONCAT(collegeName SEPARATOR ', ') as collegeName FROM `colleges` WHERE id in ('" . implode("', '", array_map("addSlashToString", $json['college'])) . "') ");
            $college = mysqli_fetch_array($college_query, MYSQLI_ASSOC);
        }


        if ($flag) {
            $fetching_data = "Select temp.Name,temp.Email_ID,temp.MobileNumber,temp.collegeName,temp.Stream,temp.YOP,temp.SubjectName , case when AptitudeScore <=4 then 'Need To Improve' else case when AptitudeScore>=7 then 'Good' else case when AptitudeScore>4 and AptitudeScore<7 then 'Acceptable' end end end as 'Status' from(select er.candidateId , fv.favourite_subject as SubjectName, ROUND(AVG(er.overallRating),1) as AptitudeScore , fv.id,u.firstName as Name,u.id as userid,c.collegeName as collegeName,pd.year as YOP,u.emailId as Email_ID,u.mobileNumber as MobileNumber,s.stream as Stream  from expert_review er inner join feedback_request fr on fr.id = er.feedback_request_id inner join questions q on q.id = er.questionId inner join users u on u.id = er.candidateId inner join professionaldetails pd on pd.candidateId = u.id inner join favourite_subject fv on fv.id = q.subjectId inner join interview i on i.id = er.interviewId" . $rawData . " LEFT OUTER JOIN topic t ON t.id = q.topic_id inner join colleges c on c.id=pd.college inner join stream s on s.id=pd.specialization where fr.review_status =2 and er.review_type='question' and q.subjectId is not null and er.overAllRating !='videoIssue' and fv.id !=156 " . $filter_query . " group by er.candidateId,fv.favourite_subject  order by er.candidateId  DESC) as temp";

            $result = mysqli_query($databaseConnection, $fetching_data);
            $row = "";
            $row2 = "";
            $count_queryResult['totalCount'] = "";
            $count_queryResult112['totalCount'] = "";
            if (mysqli_num_rows($result) >= 1) {
                $final_val = mysqli_fetch_all($result, MYSQLI_ASSOC);

                $to_encode = array(
                    'status' => 1,
                    'result' => "sucess",
                    'data' => $row,
                    'data1' => $count_queryResult['totalCount'],
                    'data2' => $row2,
                    'data3' => $count_queryResult112['totalCount'],
                    'details' => $final_val,

                );
            } else {
                $to_encode = array(
                    'status' => 0,
                    'result' => "error",
                    'errorCode' => "out Error whire retrieving practice information."
                );
            }

        } else {

            $query = "Select temp.id,temp.SubjectName ,concat(temp.SubjectName,'(',COUNT(Distinct CASE WHEN temp.AptitudeScore <=4 THEN temp.candidateId WHEN temp.AptitudeScore >=7 THEN temp.candidateId WHEN temp.AptitudeScore > 4  and temp.AptitudeScore <7  THEN temp.candidateId ELSE NULL END),')') as totalStudentcount, COUNT(Distinct CASE WHEN temp.AptitudeScore <=4 THEN temp.candidateId ELSE NULL END) as NeedsImprovement , COUNT(Distinct CASE WHEN temp.AptitudeScore >=7 THEN temp.candidateId ELSE NULL END) as Good ,COUNT(Distinct CASE WHEN temp.AptitudeScore > 4  and temp.AptitudeScore < 7  THEN temp.candidateId ELSE NULL END) as Acceptable,(COUNT(Distinct CASE WHEN temp.AptitudeScore <=4 THEN temp.candidateId ELSE NULL END) / COUNT(Distinct CASE WHEN temp.AptitudeScore <=4 THEN temp.candidateId WHEN temp.AptitudeScore >=7 THEN temp.candidateId WHEN temp.AptitudeScore > 4  and temp.AptitudeScore <7  THEN temp.candidateId ELSE NULL END)) as totalPercent  from (select er.candidateId , fv.favourite_subject as SubjectName, ROUND(AVG(er.overallRating),1) as AptitudeScore , fv.id from expert_review er  inner join feedback_request fr on  fr.id = er.feedback_request_id inner join questions q on q.id = er.questionId inner join users u on u.id = er.candidateId inner join professionaldetails pd on pd.candidateId = u.id inner join favourite_subject fv on fv.id = q.subjectId inner join interview i on i.id = er.interviewId " . $rawData . "  LEFT OUTER JOIN topic t ON t.id = q.topic_id   where fv.id NOT IN (56,21,30) and fr.review_status =2 and er.review_type='question' and q.subjectId is not null and er.overAllRating !='videoIssue' and fv.id !=156 " . $filter_query . "   group by er.candidateId,fv.favourite_subject order by er.candidateId DESC) as temp group by temp.SubjectName order by totalPercent DESC";

            $query112 = "Select temp.id,temp.SubjectName ,concat(temp.SubjectName,'(',COUNT(Distinct CASE WHEN temp.AptitudeScore <=4 THEN temp.candidateId WHEN temp.AptitudeScore >=7 THEN temp.candidateId WHEN temp.AptitudeScore > 4  and temp.AptitudeScore <7  THEN temp.candidateId ELSE NULL END),')') as totalStudentcount, COUNT(Distinct CASE WHEN temp.AptitudeScore <=4 THEN temp.candidateId ELSE NULL END) as NeedsImprovement , COUNT(Distinct CASE WHEN temp.AptitudeScore >=7 THEN temp.candidateId ELSE NULL END) as Good ,COUNT(Distinct CASE WHEN temp.AptitudeScore > 4  and temp.AptitudeScore < 7  THEN temp.candidateId ELSE NULL END) as Acceptable,(COUNT(Distinct CASE WHEN temp.AptitudeScore <=4 THEN temp.candidateId ELSE NULL END) / COUNT(Distinct CASE WHEN temp.AptitudeScore <=4 THEN temp.candidateId WHEN temp.AptitudeScore >=7 THEN temp.candidateId WHEN temp.AptitudeScore > 4  and temp.AptitudeScore <7  THEN temp.candidateId ELSE NULL END)) as totalPercent  from (select er.candidateId , fv.favourite_subject as SubjectName, ROUND(AVG(er.overallRating),1) as AptitudeScore , fv.id from expert_review er  inner join feedback_request fr on  fr.id = er.feedback_request_id inner join questions q on q.id = er.questionId inner join users u on u.id = er.candidateId inner join professionaldetails pd on pd.candidateId = u.id inner join favourite_subject fv on fv.id = q.subjectId inner join interview i on i.id = er.interviewId " . $rawData . "  LEFT OUTER JOIN topic t ON t.id = q.topic_id   where fv.id IN (56,21,30) and fr.review_status =2 and er.review_type='question' and q.subjectId is not null and er.overAllRating !='videoIssue' and fv.id !=156 " . $filter_query . "   group by er.candidateId,fv.favourite_subject order by er.candidateId DESC) as temp group by temp.SubjectName order by totalPercent DESC";

            // sibin comment 1-Aug-2022 not used anymore
            // $count_query112 = mysqli_query($databaseConnection, "select count(Distinct er.candidateId) as totalCount from expert_review er  inner join feedback_request fr on  fr.id = er.feedback_request_id inner join questions q on q.id = er.questionId inner join users u on u.id = er.candidateId inner join professionaldetails pd on pd.candidateId = u.id inner join favourite_subject fv on fv.id = q.subjectId inner join interview i on i.id = er.interviewId ". $rawData ."  LEFT OUTER JOIN topic t ON t.id = q.topic_id   where fr.review_status =2 and er.review_type='question' and q.subjectId is not null and er.overAllRating !='videoIssue' and fv.id !=156 and fv.id IN (56,21,30) " . $filter_query . " order by er.candidateId DESC");
// sibin comment 1-Aug-2022 not used anymore
            // $count_query = mysqli_query($databaseConnection, "select count(Distinct er.candidateId) as totalCount from expert_review er  inner join feedback_request fr on  fr.id = er.feedback_request_id inner join questions q on q.id = er.questionId inner join users u on u.id = er.candidateId inner join professionaldetails pd on pd.candidateId = u.id inner join favourite_subject fv on fv.id = q.subjectId inner join interview i on i.id = er.interviewId ". $rawData ."  LEFT OUTER JOIN topic t ON t.id = q.topic_id   where fr.review_status =2 and er.review_type='question' and q.subjectId is not null and er.overAllRating !='videoIssue' and fv.id !=156 " . $filter_query . " order by er.candidateId DESC");

            // $fetching_data="Select temp.Name,temp.Email_ID,temp.MobileNumber,temp.collegeName,temp.Stream,temp.YOP,temp.SubjectName , case when AptitudeScore <=4 then 'Need To Improve' else case when AptitudeScore>=7 then 'Good' else case when AptitudeScore>4 and AptitudeScore<7 then 'Acceptable' end end end as 'Status' from(select er.candidateId , fv.favourite_subject as SubjectName, ROUND(AVG(er.overallRating),1) as AptitudeScore , fv.id,u.firstName as Name,u.id as userid,c.collegeName as collegeName,pd.year as YOP,u.emailId as Email_ID,u.mobileNumber as MobileNumber,s.stream as Stream  from expert_review er inner join feedback_request fr on fr.id = er.feedback_request_id inner join questions q on q.id = er.questionId inner join users u on u.id = er.candidateId inner join professionaldetails pd on pd.candidateId = u.id inner join favourite_subject fv on fv.id = q.subjectId inner join interview i on i.id = er.interviewId".$rawData." LEFT OUTER JOIN topic t ON t.id = q.topic_id inner join colleges c on c.id=pd.college inner join stream s on s.id=pd.specialization where fr.review_status =2 and er.review_type='question' and q.subjectId is not null and er.overAllRating !='videoIssue' and fv.id !=156 ".$filter_query." group by er.candidateId,fv.favourite_subject  order by er.candidateId  DESC) as temp";

            // $result = mysqli_query($databaseConnection, $fetching_data);
            // $final_val = mysqli_fetch_all($result, MYSQLI_ASSOC);
// sibin comment 1-Aug-2022 not used anymore
            // $count_queryResult = mysqli_fetch_assoc($count_query);
            // $count_queryResult112 = mysqli_fetch_assoc($count_query112);

            $querycheck = mysqli_query($databaseConnection, $query112);

            $final_val = "";
            $query_result = mysqli_query($databaseConnection, $query);
            if (mysqli_num_rows($query_result) >= 1) {
                $row = mysqli_fetch_all($query_result, MYSQLI_ASSOC);
                $row2 = mysqli_fetch_all($querycheck, MYSQLI_ASSOC);
                $to_encode = array(
                    'status' => 1,
                    'result' => "sucess",
                    'data' => $row,
                    // 'data1' =>$count_queryResult['totalCount'],
                    'data2' => $row2,
                    // 'data3' =>$count_queryResult112['totalCount'],
                    'details' => $final_val,

                );
            } else {
                $to_encode = array(
                    'status' => 0,
                    'result' => "error",
                    'errorCode' => "out Error whire retrieving practice information."
                );
            }
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error whire retrieving practice information."
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['exportSubjectKnowledgeReport'])) {
    /* this New API is Added By Narayan For getting Aptitude Report Subject wise  in Jan 2022 */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $filter_query = " ";
        $college = array();
        $values = array();
        $rawData = " ";

        if ($json['stream'] != "" and sizeof($json['stream']) > 0)
            $filter_query .= " and pd.specialization in ('" . implode("', '", $json['stream']) . "')";
        if ($json['yop'] != "")
            $filter_query .= " and pd.year in (" . $json['yop'] . ")";
        if ($json['from_date'] != "" && $json['to_date'] == "")
            $filter_query .= " and fr.interviewSessionId >= '" . strtotime($json['from_date']) . "'";
        if ($json['from_date'] == "" && $json['to_date'] != "")
            $filter_query .= " and fr.interviewSessionId <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";
        if ($json['from_date'] != "" && $json['to_date'] != "")
            $filter_query .= " and fr.interviewSessionId >= '" . strtotime($json['from_date']) . "' and fr.interviewSessionId <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";

        if ($userType == 'college') {
            $college_query = mysqli_query($databaseConnection, "select u1.* from users u1 where u1.id =" . $json['userId'] . " ");
            $college_result = mysqli_fetch_array($college_query, MYSQLI_ASSOC);
            $filter_query .= " and pd.college in (" . $college_result['college_id'] . ")";
            $rawData .= " inner join raw_data rd on rd.email_id = u.emailId ";
            if ($json['isTieUpStatus'] == 'Y') {
                $filter_query .= " and rd.isPaid = 'Y'";
            } elseif ($json['isTieUpStatus'] == 'F') {
                $filter_query .= " and rd.isPaid = 'F'";
            } elseif ($json['isTieUpStatus'] == 'N') {
                $filter_query .= " and rd.isPaid = 'N'";
            } else {
                $filter_query .= " and rd.isPaid in('Y','F')";
            }
        }
        if ($userType != 'college') {
            if ($json['isTieUpStatus'] != "") {
                $rawData .= " inner join raw_data rd on rd.email_id = u.emailId ";
                if ($json['isTieUpStatus'] == 'Y') {
                    $filter_query .= " and rd.isPaid = 'Y'";
                } elseif ($json['isTieUpStatus'] == 'F') {
                    $filter_query .= " and rd.isPaid = 'F'";
                } else {
                    $filter_query .= " and rd.isPaid = 'N'";
                }
            }
        }
        if ($userType == 'mentor') {
            $filter_query .= " and pd.assignMentorId in (" . $json['userId'] . ")";
        }
        if ($json['college'] != "" and sizeof($json['college']) > 0) {
            $filter_query .= " and pd.college in ('" . implode("', '", array_map("addSlashToString", $json['college'])) . "')";
            $college_query = mysqli_query($databaseConnection, "SELECT GROUP_CONCAT(collegeName SEPARATOR ', ') as collegeName FROM `colleges` WHERE id in ('" . implode("', '", array_map("addSlashToString", $json['college'])) . "') ");
            $college = mysqli_fetch_array($college_query, MYSQLI_ASSOC);
        }

        $fetching_data = "Select temp.userid,temp.Name,temp.Email_ID,temp.MobileNumber,temp.collegeName,temp.Stream,temp.YOP,case when AptitudeScore <=4 then 'Need To Improve' else case when AptitudeScore>=7 then 'Good' else case when AptitudeScore>4 and AptitudeScore<7 then 'Acceptable' end end end as status,temp.SubjectName as subjects from(select er.candidateId , fv.favourite_subject as SubjectName, ROUND(AVG(er.overallRating),1) as AptitudeScore , fv.id,u.firstName as Name,u.id as userid,c.collegeName as collegeName,pd.year as YOP,u.emailId as Email_ID,u.mobileNumber as MobileNumber,s.stream as Stream  from expert_review er inner join feedback_request fr on fr.id = er.feedback_request_id inner join questions q on q.id = er.questionId inner join users u on u.id = er.candidateId inner join professionaldetails pd on pd.candidateId = u.id inner join favourite_subject fv on fv.id = q.subjectId inner join interview i on i.id = er.interviewId" . $rawData . " LEFT OUTER JOIN topic t ON t.id = q.topic_id inner join colleges c on c.id=pd.college inner join stream s on s.id=pd.specialization where fv.id NOT IN (56,21,30) AND fr.review_status =2 and er.review_type='question' and q.subjectId is not null and er.overAllRating !='videoIssue' and fv.id !=156 " . $filter_query . " group by er.candidateId,fv.favourite_subject  order by er.candidateId  DESC) as temp";

        $result = mysqli_query($databaseConnection, $fetching_data);

        if (mysqli_num_rows($result) >= 1) {
            $final_val = mysqli_fetch_all($result, MYSQLI_ASSOC);
            $to_encode = array(
                'status' => 1,
                'result' => "sucess",
                'details' => $final_val,

            );
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "out Error whire retrieving practice information."
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error whire retrieving practice information."
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['exportProgKnowledgeReport'])) {
    /* this New API is Added By Narayan For getting Aptitude Report Subject wise  in Jan 2022 */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $filter_query = " ";
        $college = array();
        $values = array();
        $rawData = " ";

        if ($json['stream'] != "" and sizeof($json['stream']) > 0)
            $filter_query .= " and pd.specialization in ('" . implode("', '", $json['stream']) . "')";
        if ($json['yop'] != "")
            $filter_query .= " and pd.year in (" . $json['yop'] . ")";
        if ($json['from_date'] != "" && $json['to_date'] == "")
            $filter_query .= " and fr.interviewSessionId >= '" . strtotime($json['from_date']) . "'";
        if ($json['from_date'] == "" && $json['to_date'] != "")
            $filter_query .= " and fr.interviewSessionId <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";
        if ($json['from_date'] != "" && $json['to_date'] != "")
            $filter_query .= " and fr.interviewSessionId >= '" . strtotime($json['from_date']) . "' and fr.interviewSessionId <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";

        if ($userType == 'college') {
            $college_query = mysqli_query($databaseConnection, "select u1.* from users u1 where u1.id =" . $json['userId'] . " ");
            $college_result = mysqli_fetch_array($college_query, MYSQLI_ASSOC);
            $filter_query .= " and pd.college in (" . $college_result['college_id'] . ")";
            $rawData .= " inner join raw_data rd on rd.email_id = u.emailId ";
            if ($json['isTieUpStatus'] == 'Y') {
                $filter_query .= " and rd.isPaid = 'Y'";
            } elseif ($json['isTieUpStatus'] == 'F') {
                $filter_query .= " and rd.isPaid = 'F'";
            } elseif ($json['isTieUpStatus'] == 'N') {
                $filter_query .= " and rd.isPaid = 'N'";
            } else {
                $filter_query .= " and rd.isPaid in('Y','F')";
            }
        }
        if ($userType != 'college') {
            if ($json['isTieUpStatus'] != "") {
                $rawData .= " inner join raw_data rd on rd.email_id = u.emailId ";
                if ($json['isTieUpStatus'] == 'Y') {
                    $filter_query .= " and rd.isPaid = 'Y'";
                } elseif ($json['isTieUpStatus'] == 'F') {
                    $filter_query .= " and rd.isPaid = 'F'";
                } else {
                    $filter_query .= " and rd.isPaid = 'N'";
                }
            }
        }
        if ($userType == 'mentor') {
            $filter_query .= " and pd.assignMentorId in (" . $json['userId'] . ")";
        }
        if ($json['college'] != "" and sizeof($json['college']) > 0) {
            $filter_query .= " and pd.college in ('" . implode("', '", array_map("addSlashToString", $json['college'])) . "')";
            $college_query = mysqli_query($databaseConnection, "SELECT GROUP_CONCAT(collegeName SEPARATOR ', ') as collegeName FROM `colleges` WHERE id in ('" . implode("', '", array_map("addSlashToString", $json['college'])) . "') ");
            $college = mysqli_fetch_array($college_query, MYSQLI_ASSOC);
        }

        $fetching_data = "Select temp.userid,temp.Name,temp.Email_ID,temp.MobileNumber,temp.collegeName,temp.Stream,temp.YOP,GROUP_CONCAT(case when AptitudeScore <=4 then 'Need To Improve' else case when AptitudeScore>=7 then 'Good' else case when AptitudeScore>4 and AptitudeScore<7 then 'Acceptable' end end end) as status, GROUP_CONCAT(temp.SubjectName) as subjects from(select er.candidateId , fv.favourite_subject as SubjectName, ROUND(AVG(er.overallRating),1) as AptitudeScore , fv.id,u.firstName as Name,u.id as userid,c.collegeName as collegeName,pd.year as YOP,u.emailId as Email_ID,u.mobileNumber as MobileNumber,s.stream as Stream  from expert_review er inner join feedback_request fr on fr.id = er.feedback_request_id inner join questions q on q.id = er.questionId inner join users u on u.id = er.candidateId inner join professionaldetails pd on pd.candidateId = u.id inner join favourite_subject fv on fv.id = q.subjectId JOIN fav_prog_skill fps ON fps.fav_prog_skill = fv.favourite_subject inner join interview i on i.id = er.interviewId" . $rawData . " LEFT OUTER JOIN topic t ON t.id = q.topic_id inner join colleges c on c.id=pd.college inner join stream s on s.id=pd.specialization where fr.review_status =2 and er.review_type='question' and q.subjectId is not null and er.overAllRating !='videoIssue' and fv.id !=156 " . $filter_query . " group by er.candidateId,fv.favourite_subject  order by er.candidateId  DESC) as temp GROUP BY temp.userid;";

        $result = mysqli_query($databaseConnection, $fetching_data);

        $getProgSubjectQry = "SELECT fs.id,fs.favourite_subject FROM favourite_subject fs JOIN fav_prog_skill fps ON fps.fav_prog_skill = fs.favourite_subject";

        $ProgSubjectResult = mysqli_query($databaseConnection, $getProgSubjectQry);

        if (mysqli_num_rows($result) >= 1) {
            $to_encode = array(
                'status' => 1,
                'result' => "sucess",
                'details' => mysqli_fetch_all($result, MYSQLI_ASSOC),
                'ProgSubject' => mysqli_fetch_all($ProgSubjectResult, MYSQLI_ASSOC),

            );
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "out Error whire retrieving practice information."
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error whire retrieving practice information."
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getRatingReport'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $filter_query = " ";
        $flag = $json['flag'];
        $college = array();
        $rawData = " ";

        if ($json['stream'] != "" and sizeof($json['stream']) > 0)
            $filter_query .= " and pd.specialization in ('" . implode("', '", $json['stream']) . "')";
        if ($json['yop'] != "")
            $filter_query .= " and pd.year in (" . $json['yop'] . ")";
        if ($json['from_date'] != "" && $json['to_date'] == "")
            $filter_query .= " and r.interviewSessionId >= '" . strtotime($json['from_date']) . "'";
        if ($json['from_date'] == "" && $json['to_date'] != "")
            $filter_query .= " and r.interviewSessionId <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";
        if ($json['from_date'] != "" && $json['to_date'] != "")
            $filter_query .= " and r.interviewSessionId >= '" . strtotime($json['from_date']) . "' and r.interviewSessionId <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";
        if ($json['isTieUpStatus'] != "") {

            if ($userType != 'college') {
                $rawData .= " inner join raw_data rd on rd.email_id = u.emailId ";
                if ($json['isTieUpStatus'] == 'Y') {
                    $filter_query .= " and rd.isPaid = 'Y'";
                } elseif ($json['isTieUpStatus'] == 'F') {
                    $filter_query .= " and rd.isPaid = 'F'";
                } else {
                    $filter_query .= " and rd.isPaid = 'N'";
                }
            }

        }
        if ($userType == 'college') {
            $college_query = mysqli_query($databaseConnection, "select u1.* from users u1 where u1.id =" . $json['userId'] . " ");
            $college_result = mysqli_fetch_array($college_query, MYSQLI_ASSOC);
            $filter_query .= " and pd.college in (" . $college_result['college_id'] . ")";
            $rawData .= " inner join raw_data rd on rd.email_id = u.emailId ";
            if ($json['isTieUpStatus'] == 'Y') {
                $filter_query .= " and rd.isPaid = 'Y'";
            } elseif ($json['isTieUpStatus'] == 'F') {
                $filter_query .= " and rd.isPaid = 'F'";
            } elseif ($json['isTieUpStatus'] == 'N') {
                $filter_query .= " and rd.isPaid = 'N'";
            } else {
                $filter_query .= " and rd.isPaid in('Y','F')";
            }

        }
        if ($userType == 'mentor') {
            $filter_query .= " and pd.assignMentorId in (" . $json['userId'] . ")";
        }
        if ($json['college'] != "" and sizeof($json['college']) > 0) {
            $filter_query .= " and pd.college in ('" . implode("', '", array_map("addSlashToString", $json['college'])) . "')";
            $college_query = mysqli_query($databaseConnection, "SELECT GROUP_CONCAT(collegeName SEPARATOR ', ') as collegeName FROM `colleges` WHERE id in ('" . implode("', '", array_map("addSlashToString", $json['college'])) . "') ");
            $college = mysqli_fetch_array($college_query, MYSQLI_ASSOC);
        }

        if ($flag) {
            $fetch = "select  r.ratingsSubmitTime as RatingsSubmitTime,i.name as interviewName,u.firstName as Name,u.mobileNumber as MobileNumber,u.emailId as EmailId,s.stream as Stream,c.collegeName as CollegeName,pd.year as YOP,r.interviewQuality as 'Complexity of Question',r.userInterface as overallExperience,r.feedbackReason as Comments from users u inner join professionaldetails pd on u.id=pd.candidateId inner join colleges c on c.id=pd.college inner join stream s on s.id= pd.specialization inner join ratings r on r.candidateId=u.id LEFT OUTER JOIN interview i ON i.id = r.interviewId" . $rawData . " where r.isSubmit='Y' and r.interviewSessionId is not null";
            $fetching = $fetch . $filter_query;
            $values = "";
            $data2 = mysqli_query($databaseConnection, $fetching);
            if (mysqli_num_rows($data2) >= 1) {
                $details = mysqli_fetch_all($data2, MYSQLI_ASSOC);
                $to_encode = array(
                    'status' => 1,
                    'collegeName' => array_key_exists('collegeName', $college) ? $college['collegeName'] : '',
                    'details' => $details,
                    'result' => $values
                );
            } else {
                $to_encode = array(
                    'result' => "error",
                    'status' => 0,
                    'errorCode' => "in Error while retrieving college information."
                );
            }


        } else {
            $query = "select count(distinct u.id) as totalUser, pd.specialization, pd.college, ROUND(AVG(r.userInterface), 1) as userInterface,COUNT(Case WHEN r.userInterface = 1 then r.userInterface ELSE NULL END) as OneStar,
            COUNT(Case WHEN r.userInterface = 2 then r.userInterface ELSE NULL END) as TwoStar,
            COUNT(Case WHEN r.userInterface = 3 then r.userInterface ELSE NULL END) as ThreeStar,
            COUNT(Case WHEN r.userInterface = 4 then r.userInterface ELSE NULL END) as FourStar,
            COUNT(Case WHEN r.userInterface = 5 then r.userInterface ELSE NULL END) as FiveStar,
            ROUND(AVG(r.interviewQuality), 1) as interviewQuality, SUM(CASE WHEN r.relevantQues = '1' THEN 1 ELSE 0 END) AS relevantQuesYes, SUM(CASE WHEN r.relevantQues = '2' THEN 1 ELSE 0 END) AS relevantQuesMayBe, SUM(CASE WHEN (r.complexBtn='1' ||r.complexBtn='1,2' || r.complexBtn='1,3' || r.complexBtn='1,4') THEN 1 ELSE 0 END) AS Easy,SUM(CASE WHEN (r.complexBtn='2' ||r.complexBtn='1,2'|| r.complexBtn='2,3' || r.complexBtn='2,4') THEN 1 ELSE 0 END) AS Moderate,SUM(CASE WHEN (r.complexBtn='3' || r.complexBtn='1,3'|| r.complexBtn='2,3'|| r.complexBtn='3,4') THEN 1 ELSE 0 END) AS Tough,SUM(CASE WHEN (r.complexBtn='4' || r.complexBtn='1,4'|| r.complexBtn='2,4'|| r.complexBtn='3,4') THEN 1 ELSE 0 END) AS DidNotUnderstandQuestions,SUM(CASE WHEN r.relevantQues = '3' THEN 1 ELSE 0 END) AS relevantQuesNo, SUM(CASE WHEN r.recommendInt = '1' THEN 1 ELSE 0 END) AS recommendIntYes, SUM(CASE WHEN r.recommendInt = '2' THEN 1 ELSE 0 END) AS recommendIntNo from users u inner join professionaldetails pd on pd.candidateId = u.id inner join ratings r on r.candidateId = u.id " . $rawData . " where r.isSubmit = 'Y' and r.interviewSessionId is not null ";

            $data = $query . $filter_query;
            $details = "";
            $result = mysqli_query($databaseConnection, $data);
            if (mysqli_num_rows($result) >= 1) {
                $values = mysqli_fetch_assoc($result);
                $to_encode = array(
                    'status' => 1,
                    'collegeName' => array_key_exists('collegeName', $college) ? $college['collegeName'] : '',
                    // 'details'=>$details,
                    'result' => $values
                );
            } else {
                $to_encode = array(
                    'result' => "error",
                    'status' => 0,
                    'errorCode' => "in Error while retrieving college information."
                );
            }
        }


    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error whire retrieving college information."
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getStudentProfileAndLeadStatus'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $filter_query = " ";
        $college = array();
        $values = array();
        $rawData = " ";
        $signup_filter = " ";
        $led_filter = " ";
        $led_passive0 = " ";
        $led_active0 = " ";
        $led_active1 = " ";

        if ($json['stream'] != "" and sizeof($json['stream']) > 0)
            $filter_query .= " and pd.specialization in ('" . implode("', '", $json['stream']) . "')";
        if ($json['yop'] != "")
            $filter_query .= " and pd.year in (" . $json['yop'] . ")";

        if ($json['isTieUpStatus'] != "") {

            if ($userType != 'college') {
                $rawData .= " inner join raw_data rd on rd.email_id = u.emailId ";
                if ($json['isTieUpStatus'] == 'Y') {
                    $filter_query .= " and rd.isPaid = 'Y'";
                } elseif ($json['isTieUpStatus'] == 'F') {
                    $filter_query .= " and rd.isPaid = 'F'";
                } else {
                    $filter_query .= " and rd.isPaid = 'N'";
                }
            }
        }

        if ($json['college'] != "" and sizeof($json['college']) > 0) {
            $filter_query .= " and pd.college in ('" . implode("', '", array_map("addSlashToString", $json['college'])) . "')";
        }

        // signupdate and led date filters for Mentor lead status by Anuj Verma 27-11-2021


        if ($userType == 'college') {
            $college_query = mysqli_query($databaseConnection, "select u1.* from users u1 where u1.id =" . $json['userId'] . " ");
            $college_result = mysqli_fetch_array($college_query, MYSQLI_ASSOC);
            $filter_query .= " and pd.college in (" . $college_result['college_id'] . ")";
            $rawData .= " inner join raw_data rd on rd.email_id = u.emailId ";

            if ($json['isTieUpStatus'] == 'Y') {
                $filter_query .= " and rd.isPaid = 'Y'";
            } elseif ($json['isTieUpStatus'] == 'F') {
                $filter_query .= " and rd.isPaid = 'F'";
            } elseif ($json['isTieUpStatus'] == 'N') {
                $filter_query .= " and rd.isPaid = 'N'";
            } else {
                $filter_query .= " and rd.isPaid in('Y','F')";
            }
        }

        if ($json['from_date'] != "" && $json['to_date'] == "")
            $signup_filter .= " and u.createdOn >= '" . strtotime($json['from_date']) . "'";
        if ($json['from_date'] == "" && $json['to_date'] != "")
            $signup_filter .= " and u.createdOn <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";
        if ($json['from_date'] != "" && $json['to_date'] != "")
            $signup_filter .= " and u.createdOn >= '" . strtotime($json['from_date']) . "' and u.createdOn <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";

        if ($userType == 'mentor') {
            $filter_query .= " and pd.assignMentorId in (" . $json['userId'] . ")";

            if ($json['led_from_date'] != "" && $json['led_to_date'] == "")
                $led_filter .= " and pd.contact_Date >= '" . $json['led_from_date'] . "'";
            if ($json['led_from_date'] == "" && $json['led_to_date'] != "")
                $led_filter .= " and pd.contact_Date <= '" . $json['led_to_date'] . "'";
            if ($json['led_from_date'] != "" && $json['led_to_date'] != "")
                $led_filter .= " and pd.contact_Date >= '" . $json['led_from_date'] . "' and pd.contact_Date <= '" . $json['led_to_date'] . "'";

            if ($json['led_from_date'] != "" || $json['led_to_date'] != "") {
                $led_passive0 .= " and DATEDIFF(date_format(from_unixtime(floor(mv.interviewSessionId/1000)),'%Y-%m-%d'),pd.contact_Date) >=0";
                $led_active0 .= " and DATEDIFF(date_format(from_unixtime(floor(mv.interviewSessionId/1000)),'%Y-%m-%d'),pd.contact_Date) >=0";
                $led_active1 .= " and DATEDIFF(date_format(from_unixtime(floor(mv.interviewSessionId/1000)),'%Y-%m-%d'),pd.contact_Date) >=0";
            }
        }


        /* getting data for student profile 13-sep-2021*/
        $query = "select count(CASE WHEN pd.webinarTopic is not null  then pd.webinarTopic ELSE Null END ) as WebinarCount,count(CASE WHEN pd.webinarTopic is not null  then pd.webinarTopic ELSE Null END ) as WebinarCount, (select GROUP_CONCAT(fv_prog.fav_prog_skill SEPARATOR ', ') as Favourite_Prog from (select fps.fav_prog_skill, count(Distinct pd.candidateId) as programmingSkillCount from fav_prog_skill fps, professionaldetails pd inner join users u on u.id = pd.candidateId " . $rawData . " where find_in_set(fps.id,pd.fav_programming_skill) " . $filter_query . $signup_filter . " group by fps.id  order by programmingSkillCount desc limit 2) as fv_prog) as TwoProgramming,
        (select GROUP_CONCAT(fv_subj.favourite_subject SEPARATOR ', ') as Favourite_Subject from (select fv.favourite_subject, count(Distinct pd.candidateId) as subjectCount from favourite_subject fv , professionaldetails pd  inner join users u on u.id = pd.candidateId " . $rawData . "  where find_in_set(fv.id,pd.fav_subjects)  " . $filter_query . $signup_filter . "  group by fv.id  order by subjectCount desc limit 2) as fv_subj) as TwoSubject,
        (select GROUP_CONCAT(ac_comp.name SEPARATOR ', ') as aspirationCompany from (select ac.name, count(Distinct pd.candidateId) as ac_compCount from aspiration_company ac , professionaldetails pd inner join users u on u.id = pd.candidateId " . $rawData . "  where find_in_set(ac.id,pd.asp_companies) " . $filter_query . $signup_filter . " group by ac.id  order by ac_compCount desc limit 5) as ac_comp) as FiveCompany from professionaldetails pd inner join users u on u.id = pd.candidateId " . $rawData . " where 1  ";

        $query_result = mysqli_query($databaseConnection, $query . $filter_query . $signup_filter);
        if (mysqli_num_rows($query_result) >= 1) {
            $row = mysqli_fetch_all($query_result, MYSQLI_ASSOC);

            // get Mentor lead status data according filter apply (LED or Signup) by Anuj Verma 27-11-2021

            $mentor_query_signup = "select count(DISTINCT(CASE WHEN  pd.nextMeetingDate is not NULL AND DATEDIFF(pd.nextMeetingDate,CURDATE()) = 0 THEN pd.candidateId ELSE NULL END)) as totalMeetingToday , count(DISTINCT(CASE WHEN pd.nextMeetingDate is not Null and  DATEDIFF(pd.nextMeetingDate,CURDATE()) < 0  THEN pd.candidateId  ELSE NULL END)) as TotalPendingMeeting, count(Distinct (CASE when pd.assignMentorId='" . $json['userId'] . "' then pd.candidateId else null end)) as candidateAssign from professionaldetails pd inner join users u on u.id =  pd.candidateId left outer join mentor_observations MO on MO.candidateId = pd.candidateId" . $rawData . "  where 1 " . $filter_query . $signup_filter;

            $mentor_query_led = "select COUNT(Distinct (CASE WHEN (Select count(DISTINCT mv.interviewSessionId ) from mergedVideos mv where mv.interviewSessionId is not null " . $led_passive0 . " and mv.candidateId = pd.candidateId ) = 0 THEN pd.candidateId ELSE NULL END)) as passiveStudent, 
            COUNT( DISTINCT(CASE WHEN (Select count(DISTINCT mv.interviewSessionId ) from mergedVideos mv where mv.interviewSessionId is not null and mv.candidateId = pd.candidateId " . $led_active0 . " ) >= 1 AND (Select count(DISTINCT fr.interviewSessionId ) from feedback_request fr where  fr.candidateId = pd.candidateId and fr.review_status in (-3,1,2,0)) = 0 THEN pd.candidateId ELSE NULL END)) as activeStudent,
            COUNT( DISTINCT(CASE WHEN (Select count(DISTINCT mv.interviewSessionId ) from mergedVideos mv where mv.interviewSessionId is NOT null and mv.candidateId = pd.candidateId " . $led_active1 . " ) >= 1 AND (Select count(DISTINCT fr.interviewSessionId ) from feedback_request fr where  fr.candidateId = pd.candidateId and fr.review_status in (-3,1,2,0))>0 THEN pd.candidateId ELSE NULL END)) as  ultraActive, 
            count(Distinct (CASE when pd.mentoringStatus=1 then pd.candidateId else null end)) as totalMentoringCompleted,count((CASE when pd.mentoringStatus=1 then pd.candidateId else null end)) as totalMentoringObservationForCompleted,count(DISTINCT (CASE WHEN pd.contact_Date is not null AND pd.mentoringStatus=0 THEN pd.candidateId ELSE Null END)) as candidateUnderMentor, count(CASE WHEN pd.contact_Date is not null AND pd.mentoringStatus=0 THEN pd.candidateId ELSE Null END) as totalMentorObservations from professionaldetails pd inner join users u on u.id =  pd.candidateId left outer join mentor_observations MO on MO.candidateId = pd.candidateId   " . $rawData . "  where 1 " . $filter_query . $signup_filter . $led_filter;

            $mentor_result_signup = mysqli_query($databaseConnection, $mentor_query_signup);
            $mentorData1 = array();
            if (mysqli_num_rows($mentor_result_signup) >= 1) {
                $mentorData1 = mysqli_fetch_all($mentor_result_signup, MYSQLI_ASSOC);
            }
            $mentor_result_led = mysqli_query($databaseConnection, $mentor_query_led);
            $mentorData2 = array();
            if (mysqli_num_rows($mentor_result_led) >= 1) {
                $mentorData2 = mysqli_fetch_all($mentor_result_led, MYSQLI_ASSOC);
            }
            $mentorData[0] = array_merge($mentorData1[0], $mentorData2[0]);

            $to_encode = array(
                'status' => 1,
                'result' => "sucess",
                'data' => $row,
                'mentorData' => $mentorData
            );
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "out Error whire retrieving practice information."
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error whire retrieving practice information."
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getStudentProfileAndSalesLeadStatus'])) {
    // Sales lead data API by Anuj Verma 10-04-2022
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $filter_query = " WHERE 1 ";
        $college = array();
        $values = array();
        $rawData = " ";
        $signup_filter = " ";
        $led_filter = " ";
        $led_passive0 = " ";
        $led_active0 = " ";
        $led_active1 = " ";

        if ($json['stream'] != "" and sizeof($json['stream']) > 0)
            $filter_query .= " and pd.specialization in ('" . implode("', '", $json['stream']) . "')";
        if ($json['yop'] != "")
            $filter_query .= " and pd.year in (" . $json['yop'] . ")";

        if ($json['isTieUpStatus'] != "") {
            $rawData .= " inner join raw_data rd on rd.email_id = u.emailId ";
            if ($json['isTieUpStatus'] == 'Y') {
                $filter_query .= " and rd.isPaid = 'Y'";
            } else {
                $filter_query .= " and rd.isPaid = 'N'";
            }
        }

        if ($json['college'] != "" and sizeof($json['college']) > 0) {
            $filter_query .= " and pd.college in ('" . implode("', '", array_map("addSlashToString", $json['college'])) . "')";
        }


        if ($userType == 'college') {
            $college_query = mysqli_query($databaseConnection, "select u1.* from users u1 where u1.id =" . $json['userId'] . " ");
            $college_result = mysqli_fetch_array($college_query, MYSQLI_ASSOC);
            $filter_query .= " and pd.college in (" . $college_result['college_id'] . ")";
        }

        if ($json['from_date'] != "" && $json['to_date'] == "")
            $signup_filter .= " and u.createdOn >= '" . strtotime($json['from_date']) . "'";
        if ($json['from_date'] == "" && $json['to_date'] != "")
            $signup_filter .= " and u.createdOn <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";
        if ($json['from_date'] != "" && $json['to_date'] != "")
            $signup_filter .= " and u.createdOn >= '" . strtotime($json['from_date']) . "' and u.createdOn <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";

        if ($userType == 'mentor') {
            $filter_query .= " and pd.assignMentorId in (" . $json['userId'] . ")";

            if ($json['led_from_date'] != "" && $json['led_to_date'] == "")
                $led_filter .= " and pd.s_contact_Date >= '" . $json['led_from_date'] . "'";
            if ($json['led_from_date'] == "" && $json['led_to_date'] != "")
                $led_filter .= " and pd.s_contact_Date <= '" . $json['led_to_date'] . "'";
            if ($json['led_from_date'] != "" && $json['led_to_date'] != "")
                $led_filter .= " and pd.s_contact_Date >= '" . $json['led_from_date'] . "' and pd.s_contact_Date <= '" . $json['led_to_date'] . "'";

            if ($json['led_from_date'] != "" || $json['led_to_date'] != "") {
                $led_passive0 .= " and DATEDIFF(date_format(from_unixtime(floor(mv.interviewSessionId/1000)),'%Y-%m-%d'),pd.contact_Date) >=0";
                $led_active0 .= " and DATEDIFF(date_format(from_unixtime(floor(mv.interviewSessionId/1000)),'%Y-%m-%d'),pd.contact_Date) >=0";
                $led_active1 .= " and DATEDIFF(date_format(from_unixtime(floor(mv.interviewSessionId/1000)),'%Y-%m-%d'),pd.contact_Date) >=0";
            }
        }


        /* getting data for student profile 13-sep-2021*/
        $query = "select count(DISTINCT(CASE WHEN pd.s_nextcontact_date is not NULL AND DATEDIFF(pd.s_nextcontact_date,CURDATE()) = 0 THEN pd.candidateId ELSE NULL END)) as totalMeetingToday , count(DISTINCT(CASE WHEN pd.s_nextcontact_date is not Null and DATEDIFF(pd.s_nextcontact_date,CURDATE()) < 0 THEN pd.candidateId ELSE NULL END)) as TotalPendingMeeting,count(Distinct (CASE when pd.assignMentorId='" . $userId . "' then pd.candidateId else null end)) as candidateAssign from professionaldetails pd inner join users u on u.id = pd.candidateId ";
        $query_result = mysqli_query($databaseConnection, $query . $rawData . $filter_query . $signup_filter . $led_filter);

        if (mysqli_num_rows($query_result) >= 1) {
            $salesQuery = "select COUNT(CASE WHEN slas.id = 1 THEN pd.id ELSE NULL END) as rnr, COUNT(CASE WHEN slas.id = 2 THEN pd.id ELSE NULL END) as declaredNotInterested, COUNT(CASE WHEN slas.id = 3 THEN pd.id ELSE NULL END) as looksInterested, COUNT(CASE WHEN slas.id = 4 THEN pd.id ELSE NULL END) as veryMuchInterested, COUNT(CASE WHEN slas.id = 5 THEN pd.id ELSE NULL END) as deadlead, COUNT(CASE WHEN slas.id = 6 THEN pd.id ELSE NULL END) as paid, COUNT(CASE WHEN slas.id = 7 THEN pd.id ELSE NULL END) as stuEmpNotAvailable, COUNT(CASE WHEN slas.id = 8 THEN pd.id ELSE NULL END) as busyCallbackLater from professionaldetails pd  inner join users u on u.id = pd.candidateId LEFT JOIN salesLeadActionStatus slas ON pd.leadStatus = slas.id  ";
            $salesQuery_result = mysqli_query($databaseConnection, $salesQuery . $rawData . $filter_query . $signup_filter . $led_filter);

            $assessment_qry = "select 
            COUNT( DISTINCT(CASE WHEN (Select count(DISTINCT mv.interviewSessionId ) from mergedVideos mv where mv.interviewSessionId is not null and mv.candidateId = pd.candidateId " . $led_active0 . " ) >= 1 AND (Select count(DISTINCT fr.interviewSessionId ) from feedback_request fr where  fr.candidateId = pd.candidateId and fr.review_status in (-4)) = 0 THEN pd.candidateId ELSE NULL END)) as assesmentRejected,
            COUNT(Distinct (CASE WHEN (Select count(DISTINCT mv.interviewSessionId ) from mergedVideos mv where mv.interviewSessionId is not null " . $led_passive0 . " and mv.candidateId = pd.candidateId ) = 0 THEN pd.candidateId ELSE NULL END)) as passiveZero, 
            COUNT( DISTINCT(CASE WHEN (Select count(DISTINCT mv.interviewSessionId ) from mergedVideos mv where mv.interviewSessionId is not null and mv.candidateId = pd.candidateId " . $led_active0 . " ) >= 1 AND (Select count(DISTINCT fr.interviewSessionId ) from feedback_request fr where  fr.candidateId = pd.candidateId and fr.review_status in (-3,1,2,0)) = 0 THEN pd.candidateId ELSE NULL END)) as activeZero,
            COUNT( DISTINCT(CASE WHEN (Select count(DISTINCT mv.interviewSessionId ) from mergedVideos mv where mv.interviewSessionId is NOT null and mv.candidateId = pd.candidateId " . $led_active1 . " ) >= 1 AND (Select count(DISTINCT fr.interviewSessionId ) from feedback_request fr where  fr.candidateId = pd.candidateId and fr.review_status in (-3,1,2,0))>0 THEN pd.candidateId ELSE NULL END)) as  activeOne from professionaldetails pd  inner join users u on u.id = pd.candidateId ";
            $assessment_qry_result = mysqli_query($databaseConnection, $assessment_qry . $rawData . $filter_query . $signup_filter . $led_filter);

            $sumOfData[0] = array_merge(mysqli_fetch_all($query_result, MYSQLI_ASSOC)[0], mysqli_fetch_all($salesQuery_result, MYSQLI_ASSOC)[0], mysqli_fetch_all($assessment_qry_result, MYSQLI_ASSOC)[0]);
            $to_encode = array(
                'status' => 1,
                'result' => "sucess",
                'mentorData' => $sumOfData,
                'salesResultQry' => $salesQuery . $rawData . $filter_query . $signup_filter . $led_filter
            );
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "out Error whire retrieving practice information."
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error whire retrieving practice information."
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['hashPassword'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $hashsql = "Select id, password from users where length(password) < 60";
        $hashquery = mysqli_query($databaseConnection, $hashsql);
        if (mysqli_num_rows($hashquery) > 0) {
            while ($row = mysqli_fetch_array($hashquery, MYSQLI_ASSOC)) {
                $hash = password_hash($row['password'], PASSWORD_BCRYPT, ["cost" => 12]);
                $hashUpdate = "UPDATE users SET password='" . $hash . "' WHERE id= '" . $row['id'] . "' ";
                mysqli_query($databaseConnection, $hashUpdate);
            }
            $to_encode = array(
                'status' => 1,
                'result' => "Success",
            );
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "in Error while Hashing User Password"
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while Hashing User Password"
        );
    }
    echo json_encode($to_encode);
}
//node-api
elseif (isset($_GET['addNewCollege'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $college = addslashes($json['college']);
        $collegesql = "Select * from colleges where collegeName = '" . $college . "' ";
        $collegequery = mysqli_query($databaseConnection, $collegesql);
        if (mysqli_num_rows($collegequery) > 0) {
            $to_encode = array(
                'status' => 0,
                'result' => "Error",
                'errorCode' => "College Already Exits"
            );
        } else {
            $insertquery = "INSERT INTO `colleges` (`collegeName`) VALUES ('" . $college . "');";
            mysqli_query($databaseConnection, $insertquery);
            $to_encode = array(
                'status' => 1,
                'result' => "Success",
                'successCode' => "College Added SuccessFully"
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => " Error while adding college"
        );
    }
    echo json_encode($to_encode);
}
// node-api
elseif (isset($_GET['addNewCompany1'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $company = addslashes($json['company']);
        $companysql = "Select * from aspiration_company where name = '" . $company . "' ";
        $companyquery = mysqli_query($databaseConnection, $companysql);
        if (mysqli_num_rows($companyquery) > 0) {
            $to_encode = array(
                'status' => 0,
                'result' => "Error",
                'errorCode' => "Company Already Exits"
            );
        } else {
            $insertquery = "INSERT INTO `aspiration_company` (`name`) VALUES ('" . $company . "');";
            mysqli_query($databaseConnection, $insertquery);
            $to_encode = array(
                'status' => 1,
                'result' => "Success",
                'successCode' => "Company Added SuccessFully"
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => " Error while adding Company"
        );
    }
    echo json_encode($to_encode);
}
// node-api
elseif (isset($_GET['addNewLocation1'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $Location = addslashes($json['Location']);
        $companysql = "Select * from locations where cityName = '" . $Location . "' ";
        $companyquery = mysqli_query($databaseConnection, $companysql);
        if (mysqli_num_rows($companyquery) > 0) {
            $to_encode = array(
                'status' => 0,
                'result' => "Error",
                'errorCode' => "Location Already Exits"
            );
        } else {
            $insertquery = "INSERT INTO `locations` (`cityName`) VALUES ('" . $Location . "');";
            mysqli_query($databaseConnection, $insertquery);
            $to_encode = array(
                'status' => 1,
                'result' => "Success",
                'successCode' => "Location Added SuccessFully"
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => " Error while adding Location"
        );
    }
    echo json_encode($to_encode);
}
//node-api
elseif (isset($_GET['addNewSubject1'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $Subject = addslashes($json['Subject']);
        // Get isCompetencySubject as 1 (true) or 0 (false)
        $subjectType = (isset($json['isCompetencySubject']) && $json['isCompetencySubject']) ? "'competency'" : "NULL";
        
        $companysql = "Select * from favourite_subject where favourite_subject = '" . $Subject . "' ";
        $companyquery = mysqli_query($databaseConnection, $companysql);
        if (mysqli_num_rows($companyquery) > 0) {
            $to_encode = array(
                'status' => 0,
                'result' => "Error",
                'errorCode' => "Subject Already Exits"
            );
        } else {
            $insertquery = "INSERT INTO `favourite_subject` (`favourite_subject`, `subjectType`) VALUES ('" . $Subject . "', $subjectType);";
            mysqli_query($databaseConnection, $insertquery);
            $to_encode = array(
                'status' => 1,
                'result' => "Success",
                'successCode' => "Subject Added SuccessFully"
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => " Error while adding Subject"
        );
    }
    echo json_encode($to_encode);
}
elseif (isset($_GET['UpdateSubjectRoleStatus'])) {
    // node-api
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    if (isset($json)) {
        $subjectId = addslashes($json['subjectId']);

        $subjectType = (isset($json['isCompetencySubject']) && $json['isCompetencySubject']) ? "'competency'" : "NULL";

        if ($json['selectedRoles'] != null) {
            $roleId = array_map('addslashes', $json['selectedRoles']);
        }

        $active = addslashes($json['selectedActiveStatus']);


        if ($json['subjectId'] != '' && $json['subjectId'] != null) {


            $dsubjectq = "delete from role_subject where subjectId = '" . $subjectId . "' ";
            $dsubjectquery = mysqli_query($databaseConnection, $dsubjectq);
        }


        if ($json['selectedRoles'] != '' && $json['selectedRoles'] != null) {

            foreach ($roleId as $role) {
                $insertsubjectq = "INSERT INTO role_subject (roleId, subjectId) VALUES ('" . $role . "', '" . $subjectId . "')";
                //  echo  $insertsubjectq ;
                mysqli_query($databaseConnection, $insertsubjectq);
            }
        }

        if (($json['selectedActiveStatus'] != '' && $json['selectedActiveStatus'] != null) ||
            ($subjectType !== null)
        ) {
            // echo $subjectType;
            // Update active and subjectType fields
            $set = [];
            if ($json['selectedActiveStatus'] != '' && $json['selectedActiveStatus'] != null) {
                $set[] = "active='$active'";
            }
            if ($subjectType !== null) {
                $set[] = "subjectType=$subjectType";
            }
            $setClause = implode(', ', $set);
            $updateFields = "UPDATE favourite_subject SET $setClause WHERE id = '" . $subjectId . "' ";
            // echo $updateFields;
            mysqli_query($databaseConnection, $updateFields);
        }

        $to_encode = array(
            'status' => 1,
            'result' => "Success",
            'successCode' => "Updated  Successfully"
        );
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => " Error while Updating"
        );
    }
    echo json_encode($to_encode);
}
elseif (isset($_GET['expertContentWorkLog'])) {
    /* this method is added for expert content work log by anuj 9-nov-2021*/
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    $values = array();
    if (isset($json)) {
        $questionId = $json['questionId'];
        $expertId = $json['expertId'];
        $status = $json['status'];
        $delegationType = $json['delegationType'];
        $Query = "SELECT expertId,questionId,delegationType,attempt FROM `expert_content_log` WHERE expertId='" . $expertId . "' AND questionId='" . $questionId . "' AND delegationType='" . $delegationType . "'";
        $Result = mysqli_query($databaseConnection, $Query);
        if (mysqli_num_rows($Result) > 0) {
            if ($status == 'recording') {
                $attempt = mysqli_fetch_assoc($Result);

                $updateQuery = "UPDATE `expert_content_log` SET `attempt` = " . $attempt['attempt'] . "+1,`status`='" . $status . "' WHERE questionId='" . $questionId . "' AND expertId='" . $expertId . "' AND delegationType='" . $delegationType . "'";
                if (mysqli_query($databaseConnection, $updateQuery)) {
                    $to_encode = array(
                        'status' => 1,
                        'result' => "success",
                        'msg' => "success update"
                    );
                } else {
                    $to_encode = array(
                        'status' => 0,
                        'result' => "error",
                        'errorCode' => "Error while entry"
                    );
                }
            } else {
                $updateQuery = "UPDATE `expert_content_log` SET `status`='" . $status . "' WHERE questionId='" . $questionId . "' AND expertId='" . $expertId . "' AND delegationType='" . $delegationType . "'";
                if (mysqli_query($databaseConnection, $updateQuery)) {
                    $to_encode = array(
                        'status' => 1,
                        'result' => "success",
                        'msg' => "success"
                    );
                } else {
                    $to_encode = array(
                        'status' => 0,
                        'result' => "error",
                        'errorCode' => "Error while entry"
                    );
                }
            }

        } else {
            $insertQuery = "INSERT INTO `expert_content_log`(`expertId`, `questionId`,`delegationType`,`attempt`,`status`) VALUES ('" . $expertId . "','" . $questionId . "','" . $delegationType . "',1,'" . $status . "')";
            if (mysqli_query($databaseConnection, $insertQuery)) {
                $to_encode = array(
                    'status' => 1,
                    'result' => "success",
                    'msg' => "success insert"
                );
            } else {
                $to_encode = array(
                    'status' => 0,
                    'result' => "error",
                    'errorCode' => "Error while entry"
                );
            }
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "Error while entry"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getDelegatedQuestionList'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $start = 0;
        $panelId = $json['panelId'];
        $limit = $json['limit'];
        $start = ($json['page'] - 1) * $limit;
        $order_query = " ";
        $join_query = " ";
        $filter_query = "";
        $filter1 = "0";
        $limit_query = $limit == 0 ? "" : " limit " . $start . "," . $limit;
        $questionList = array();
        if ($json['quesStatus'] != "") {
            if ($json['quesStatus'] == "rawQus") {
                $filter_query .= " and (q.deleted_at is null and (q.expertApproval ='N'  OR (q.eligibleStreamId = '' OR q.eligibleStreamId IS  NULL OR q.subjectId = '' OR q.subjectId IS  NULL OR q.conceptId = '' OR q.conceptId IS  NULL OR q.key_skill_id = '' OR q.key_skill_id IS  NULL OR  q.topic_id = '' OR q.topic_id IS  NULL OR q.isWbRequired = '' OR q.isWbRequired IS  NULL OR q.questionLevel = '' OR q.questionLevel IS  NULL))) ";
            } elseif ($json['quesStatus'] == "inactive") {
                $filter_query .= " and q.deleted_at is not null ";
            } elseif ($json['quesStatus'] == "readyToUse") {
                $filter_query .= " and q.deleted_at is null and  q.expertApproval = 'Y' and (q.eligibleStreamId != '' AND q.eligibleStreamId IS NOT NULL AND q.subjectId != '' AND q.subjectId IS NOT NULL AND q.conceptId != '' AND q.conceptId IS NOT NULL AND q.key_skill_id != '' AND q.key_skill_id IS NOT NULL AND q.topic_id != '' AND q.topic_id IS NOT NULL AND q.isWbRequired != '' AND q.isWbRequired IS NOT NULL AND q.questionLevel != '' AND q.questionLevel IS NOT NULL)";
            } elseif ($json['quesStatus'] == "readyUpdatedUse") {
                $filter_query .= " and q.deleted_at is null and q.expertAdvice is not null  and (q.peerResponseVideo is not null or q.mbr_id != '0')  and  youtubeId !=314664775 ";
            }
        }
        if ($json['quesPriority'] != "") {
            if ($json['quesPriority'] == "1") {
                $filter_query .= " and q.priorityStatus = '1' ";
            } else if ($json['quesPriority'] == "2") {
                $filter_query .= " and q.priorityStatus = '2' ";
            } else {
                $filter_query .= "  and  q.priorityStatus = '0' ";
            }
        }
        if ($json['typeOfWork'] != "") {
            if ($json['typeOfWork'] == "0") {
                $filter_query .= " and qs.delegationType = 'guidanceVideo' ";
            } elseif ($json['typeOfWork'] == "1") {
                $filter_query .= "  and  qs.delegationType = 'questionVideo' ";
            } elseif ($json['typeOfWork'] == "2") {
                $filter_query .= "  and  qs.delegationType = 'peerResponseVideo' ";
            } else {
                $filter_query .= "  and  qs.delegationType = 'tagging' ";
            }

        }
        if ($json['questionId'] != "") {
            $filter_query .= " and q.id in (" . $json['questionId'] . ") ";
        }
        if ($json['expertName'] != "") {
            $filter_query .= " and p.name like '%" . $json['expertName'] . "%' ";
        }
        if ($json['workStatus'] != "") {
            if ($json['workStatus'] == "2") {
                $filter_query .= " and qs.uploadStatus = '2' ";
            } elseif ($json['workStatus'] == "1") {
                $filter_query .= "  and  qs.uploadStatus = '1' ";
            } else {
                $filter_query .= "  and  qs.uploadStatus = '0' ";
            }
        }
        if ($json['from_date'] != "" && $json['to_date'] == "") {
            $filter_query .= " and qs.updatedAt >= '" . $json['from_date'] . " 23:59:59'";
        }

        if ($json['from_date'] == "" && $json['to_date'] != "") {
            $filter_query .= " and qs.updatedAt <= '" . $json['to_date'] . " 23:59:59'";
        }

        if ($json['from_date'] != "" && $json['to_date'] != "") {
            $filter_query .= " and qs.updatedAt >= '" . $json['from_date'] . " 00:00:00' and qs.updatedAt <= '" . $json['to_date'] . " 23:59:59'";
        }



        if ($panelId != 0) {
            $query = "select u.id as candidateId,p.* from panel p LEFT OUTER JOIN users u ON u.panelId = p.id where p.id = '" . $panelId . "'";
            $result = mysqli_query($databaseConnection, $query);
            $values = mysqli_fetch_assoc($result);
            if ($values['expertStatus'] == 1) {
                /* change by Naraayn 18-05-2021 coding in areaOfExpertise */
                $expertExpertise = explode(",", $values['areaOfExpertiseId']);
                //$coding = explode(",", $values['coding']);
                foreach ($expertExpertise as $afe) {
                    if ($values['isVideoApproved'] == 'Y') {
                        $filter1 .= " OR (FIND_IN_SET('" . $afe . "', q.subjectId) AND qs.delegationType !='peerResponseVideo' AND qs.delegationType != 'tagging')";
                    }
                    if ($values['isTaggingApproved'] == 'Y') {
                        $filter1 .= " OR (FIND_IN_SET('" . $afe . "', q.subjectId) AND qs.delegationType = 'tagging')";
                    }
                    if ($values['isPeerApproved'] == 'Y') {
                        $filter1 .= " OR (FIND_IN_SET('" . $afe . "', q.subjectId) AND qs.delegationType = 'peerResponseVideo')";
                    }
                }
            }
            /* change by Naraayn  6/5/2021 */
            /* previous high priority case was like this  CASE when iqt.questionId is not null then (CASE WHEN ((DATEDIFF(sub.endDate,CURDATE()) > 0 and (fr.review_status=1 OR fr.review_status =0)) OR (DATEDIFF(sub.endDate,CURDATE()) > 0 and (qs.uploadStatus=1 OR qs.uploadStatus =0)) OR q.highPriority='Y')  then 'Y' ELSE 'N' END) WHEN iqt.questionId is null THEN (CASE when q.highPriority = 'Y' THEN 'Y' ELSE 'N' END) ELSE 'N' END AS questionPriority*/
            /* Thats why there is no need left outer join  with these interview_questions_transection iqt  on q.id = iqt.questionId left outer join feedback_request fr on (fr.interviewId = iqt.interviewId and (fr.review_status = 1 || fr.review_status = 0)) left outer join subscription sub on sub.candidateId =  fr.candidateId*/
            /*In content inbox we don't need for checking subscribe user or free trial*/
            $join_query = " inner join questions q on q.id = qs.questionId left outer join panel p on p.id = qs.expertId inner join favourite_subject fv on fv.id = q.subjectId where ((qs.ExpertId = '" . $panelId . "') OR (qs.ExpertId = '" . $panelId . "') OR (qs.ExpertId = '" . $panelId . "') OR (qs.uploadStatus='0' AND qs.expertId is null AND (" . $filter1 . " ))) " . $filter_query . "  group by qs.questionId,q.subjectId order by q.priorityStatus DESC,qs.questionId DESC";
            $query2 =
                "select q.*,(select count(qt.questionId) from questions_transection qt inner join questions qu on qu.id = qt.questionId where delegationType in ('guidanceVideo','tagging','questionVideo','PeerResponseVideo') and expertId = qs.expertId and uploadStatus = 2 and qu.subjectId = q.subjectId) as TotalWorkDone,CASE WHEN qs.delegationType='guidanceVideo' THEN qs.noOfImages ELSE 0 END as imageNumber ,CASE WHEN qs.delegationType='guidanceVideo' THEN qs.noOfVideos ELSE 0 END as videoNumber,p.name as expertName,fv.favourite_subject as subjectName, qs.expertId, qs.questionId,

                max(case when qs.delegationType = 'questionVideo' then DATE_FORMAT(qs.createdAt ,'%D %b %Y')  end) as qRequestDate,
                max(case when qs.delegationType = 'guidanceVideo' then DATE_FORMAT(qs.createdAt ,'%D %b %Y') end) as gRequestDate,
                max(case when qs.delegationType = 'peerResponseVideo' then DATE_FORMAT(qs.createdAt ,'%D %b %Y')  end) as pRequestDate,
                max(case when qs.delegationType = 'tagging' then DATE_FORMAT(qs.createdAt ,'%D %b %Y') END) as tRequestDate,

                max(case when qs.delegationType = 'questionVideo' then qs.delegationType end) as qDelegationType,
                max(case when qs.delegationType = 'guidanceVideo' then qs.delegationType end) as gDelegationType,
                max(case when qs.delegationType = 'peerResponseVideo' then qs.delegationType end) as pDelegationType,
                max(case when qs.delegationType = 'tagging' then qs.delegationType end) as tDelegationType,
                max(case when qs.delegationType = 'questionVideo' then qs.uploadStatus end) as qUploadStatus,
                max(case when qs.delegationType = 'guidanceVideo' then qs.uploadStatus end) as gUploadStatus,
                max(case when qs.delegationType = 'peerResponseVideo' then qs.uploadStatus end) as pUploadStatus,
                max(case when qs.delegationType = 'peerResponseVideo' then qs.whiteboardText end) as pWhiteboardText,
                max(case when qs.delegationType = 'tagging' then qs.uploadStatus end) as tUploadStatus,
                max(case when qs.delegationType = 'questionVideo' then qs.vimeoId end) as qVimeoId,
                max(case when qs.delegationType = 'guidanceVideo' then qs.vimeoId end) as gVimeoId,
                max(case when qs.delegationType = 'peerResponseVideo' then qs.vimeoId end) as pVimeoId,
                max(case when qs.delegationType = 'tagging' then qs.vimeoId end) as tVimeoId,(select count(m.youtubeId) as personalizedvideoFeedback from expert_review  er  inner join mergedVideos m on er.feedbackVideoURL= m.outputVideoURL inner join panel p on p.id = er.feedbackGivenBy where er.feedbackGivenBy = '" . $panelId . "' and er.feedbackVideoURL is not NULL and er.isGvAvailable ='N' and er.questionId = q.id) as personalizedvideoFeedback 
                from  questions_transection qs";
            $data = $query2 . $join_query . $order_query;
            $count_query2 = "select q.id from questions_transection qs";
            $count_query = $count_query2 . $join_query . $order_query;
            $count = mysqli_query($databaseConnection, $count_query);
            //$count = mysqli_query($databaseConnection, $data);
            $count_result = mysqli_num_rows($count);
            $result2 = mysqli_query($databaseConnection, $data . $limit_query);
            if (mysqli_num_rows($result2) > 0) {
                // $count_result = mysqli_fetch_assoc($count_query);
                while ($row = mysqli_fetch_array($result2, MYSQLI_ASSOC)) {
                    if ($row['pDelegationType'] == 'peerResponseVideo' && ($row['followUp'] == 'Parent' || $row['followUp'] == 'Single')) {
                        $query3 = "SELECT GROUP_CONCAT(t.id) as questionsId FROM (SELECT id, youtubeId,subjectId, questionText, isFollowUp, answerDuration,key_skill_id,questionLevel FROM questions  WHERE id = '" . $row['id'] . "' UNION SELECT id, youtubeId,subjectId,questionText, isFollowUp, answerDuration,key_skill_id,questionLevel FROM questions WHERE id in (SELECT lv FROM (SELECT @pv:=(SELECT GROUP_CONCAT(id SEPARATOR ',') FROM questions WHERE isFollowUp IN (@pv)) AS lv FROM questions JOIN (SELECT @pv:='" . $row['id'] . "')tmp WHERE isFollowUp IN (@pv)) a) ORDER BY isFollowUp <> 'Y', isFollowUp) as t";
                        $queryResult3 = mysqli_query($databaseConnection, $query3);
                        $queryValue3 = mysqli_fetch_all($queryResult3, MYSQLI_ASSOC)[0]['questionsId'];
                        $row['questionsList'] = $queryValue3;
                        $query4 = "SELECT qt.questionId,qt.uploadStatus FROM questions_transection qt WHERE qt.questionId IN (" . $queryValue3 . ") AND qt.delegationType = 'peerResponseVideo'";
                        $queryResult4 = mysqli_query($databaseConnection, $query4);
                        $queryValue4 = mysqli_fetch_all($queryResult4, MYSQLI_ASSOC);
                        $row['readyToSubmit'] = 'Y';
                        for ($i = 0; $i < count($queryValue4); $i++) {
                            if ($queryValue4[$i]['uploadStatus'] == '0') {
                                $row['readyToSubmit'] = 'N';
                            }
                        }
                        if ($row['readyToSubmit'] == 'Y') {
                            $query4 = "SELECT * FROM mergedVideos mv JOIN `interview` i ON i.id = mv.interviewId JOIN questions_transection qt ON qt.questionId = mv.questionId AND qt.delegationType = 'peerResponseVideo' AND qt.vimeoId = mv.youtubeId WHERE i.name = 'peerResponse#" . $row['id'] . "' AND mv.candidateId = " . $values['candidateId'] . ";";
                            $queryResult4 = mysqli_query($databaseConnection, $query4);
                            if (mysqli_num_rows($queryResult4) > 0) {
                                $row['mvDetails'] = mysqli_fetch_all($queryResult4, MYSQLI_ASSOC);
                                $row['readyToSubmit'] = 'H';
                            }
                        }
                    }
                    $row['questionHtml'] = nl2br($row['questionText']);
                    $row['shortExpectedAnsHtml'] = nl2br($row['shortExpectedAns']);
                    $row['expertId'] = $values['id'];
                    array_push($questionList, $row);
                }

                $to_encode = array(
                    'questionList' => $questionList,
                    'expertName' => $values['name'],
                    'isPeerApproved' => $values['isPeerApproved'],
                    'isVideoApproved' => $values['isVideoApproved'],
                    'isTaggingApproved' => $values['isTaggingApproved'],
                    'status' => 1,
                    'count' => $count_result
                );
            } else {
                $to_encode = array(
                    'questionList' => $questionList,
                    'expertName' => $values['name'],
                    'status' => 0,
                    'count' => 0,
                    'query' => $data
                );
            }
        } else {
            $join_query = " inner join questions q on q.id = qs.questionId left outer join panel p on p.id = qs.expertId inner join favourite_subject fv on fv.id = q.subjectId Where 1 " . $filter_query . " group by qs.questionId,q.subjectId,qs.expertId order by q.priorityStatus DESC, q.id DESC";
            $query2 =
                "select q.*,DATE_FORMAT(qs.createdAt ,'%D %b %Y %T')  as RequestDate ,CASE WHEN qs.expertId is not NULL THEN (select count(qt.questionId) from questions_transection qt inner join questions qu on qu.id = qt.questionId where delegationType in ('guidanceVideo','tagging','questionVideo','peerResponseVideo') and expertId = qs.expertId and uploadStatus = 2 and qu.subjectId = q.subjectId) ELSE 0 END  as TotalWorkDone, CASE WHEN qs.delegationType='guidanceVideo' THEN qs.noOfImages ELSE 0 END as imageNumber ,CASE WHEN qs.delegationType='guidanceVideo' THEN qs.noOfVideos ELSE 0 END as videoNumber ,p.name as expertName,fv.favourite_subject as subjectName,qs.expertId, qs.questionId,
                max(case when qs.delegationType = 'questionVideo' then DATE_FORMAT(qs.createdAt ,'%D %b %Y')  end) as qRequestDate,
                max(case when qs.delegationType = 'guidanceVideo' then DATE_FORMAT(qs.createdAt ,'%D %b %Y') end) as gRequestDate,
                max(case when qs.delegationType = 'peerResponseVideo' then DATE_FORMAT(qs.createdAt ,'%D %b %Y')  end) as pRequestDate,
                max(case when qs.delegationType = 'tagging' then DATE_FORMAT(qs.createdAt ,'%D %b %Y') END) as tRequestDate,

            max(case when qs.delegationType = 'questionVideo' then qs.delegationType end) as qDelegationType,
            max(case when qs.delegationType = 'guidanceVideo' then qs.delegationType end) as gDelegationType,
            max(case when qs.delegationType = 'peerResponseVideo' then qs.delegationType end) as pDelegationType,
            max(case when qs.delegationType = 'tagging' then qs.delegationType end) as tDelegationType,
            max(case when qs.delegationType = 'questionVideo' then qs.uploadStatus end) as qUploadStatus,
            max(case when qs.delegationType = 'guidanceVideo' then qs.uploadStatus end) as gUploadStatus,
            max(case when qs.delegationType = 'peerResponseVideo' then qs.uploadStatus end) as pUploadStatus,
            max(case when qs.delegationType = 'peerResponseVideo' then qs.whiteboardText end) as pWhiteboardText,
            max(case when qs.delegationType = 'tagging' then qs.uploadStatus end) as tUploadStatus,
            max(case when qs.delegationType = 'questionVideo' then qs.vimeoId end) as qVimeoId,
            max(case when qs.delegationType = 'guidanceVideo' then qs.vimeoId end) as gVimeoId,
            max(case when qs.delegationType = 'peerResponseVideo' then qs.vimeoId end) as pVimeoId,
            max(case when qs.delegationType = 'tagging' then qs.vimeoId end) as tVimeoId, (select count(m.youtubeId) as personalizedvideoFeedback from expert_review  er  inner join mergedVideos m on er.feedbackVideoURL= m.outputVideoURL inner join panel p on p.id = er.feedbackGivenBy where er.feedbackVideoURL is not NULL and er.isGvAvailable ='N' and er.questionId = q.id) as personalizedvideoFeedback
            from questions_transection qs";
            $data = $query2 . $join_query . $order_query;
            $count_query2 = "select q.id from questions_transection qs";
            $count_query = $count_query2 . $join_query . $order_query;
            $count = mysqli_query($databaseConnection, $count_query);
            $count_result = mysqli_num_rows($count);
            $result2 = mysqli_query($databaseConnection, $data . $limit_query);
            if (mysqli_num_rows($result2) > 0) {
                while ($row = mysqli_fetch_array($result2, MYSQLI_ASSOC)) {
                    if ($row['pDelegationType'] == 'peerResponseVideo' && ($row['followUp'] == 'Parent' || $row['followUp'] == 'Single')) {
                        $query3 = "SELECT GROUP_CONCAT(t.id) as questionsId FROM (SELECT id, youtubeId,subjectId, questionText, isFollowUp, answerDuration,key_skill_id,questionLevel FROM questions  WHERE id = '" . $row['id'] . "' UNION SELECT id, youtubeId,subjectId,questionText, isFollowUp, answerDuration,key_skill_id,questionLevel FROM questions WHERE id in (SELECT lv FROM (SELECT @pv:=(SELECT GROUP_CONCAT(id SEPARATOR ',') FROM questions WHERE isFollowUp IN (@pv)) AS lv FROM questions JOIN (SELECT @pv:='" . $row['id'] . "')tmp WHERE isFollowUp IN (@pv)) a) ORDER BY isFollowUp <> 'Y', isFollowUp) as t";
                        $queryResult3 = mysqli_query($databaseConnection, $query3);
                        $queryValue3 = mysqli_fetch_all($queryResult3, MYSQLI_ASSOC)[0]['questionsId'];
                        $row['questionsList'] = $queryValue3;
                        $query4 = "SELECT qt.questionId,qt.uploadStatus FROM questions_transection qt WHERE qt.questionId IN (" . $queryValue3 . ") AND qt.delegationType = 'peerResponseVideo'";
                        $queryResult4 = mysqli_query($databaseConnection, $query4);
                        $queryValue4 = mysqli_fetch_all($queryResult4, MYSQLI_ASSOC);
                        $row['readyToSubmit'] = 'Y';
                        for ($i = 0; $i < count($queryValue4); $i++) {
                            if ($queryValue4[$i]['uploadStatus'] == '0') {
                                $row['readyToSubmit'] = 'N';
                            }
                        }
                        if ($row['readyToSubmit'] == 'Y') {
                            $query4 = "SELECT * FROM mergedVideos mv JOIN `interview` i ON i.id = mv.interviewId JOIN questions_transection qt ON qt.questionId = mv.questionId AND qt.delegationType = 'peerResponseVideo' AND qt.vimeoId = mv.youtubeId WHERE i.name = 'peerResponse#" . $row['id'] . "';";
                            $queryResult4 = mysqli_query($databaseConnection, $query4);
                            if (mysqli_num_rows($queryResult4) > 0) {
                                $row['mvDetails'] = mysqli_fetch_all($queryResult4, MYSQLI_ASSOC);
                                $row['readyToSubmit'] = 'H';
                            }
                        }
                    }
                    $row['questionHtml'] = nl2br($row['questionText']);
                    $row['shortExpectedAnsHtml'] = nl2br($row['shortExpectedAns']);
                    array_push($questionList, $row);
                }
                $to_encode = array(
                    'questionList' => $questionList,
                    'status' => 1,
                    'count' => $count_result
                );
            } else {
                $to_encode = array(
                    'questionList' => $questionList,
                    'status' => 0,
                    'count' => 0,
                    'query' => $data
                );
            }
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Request for getting question list Failed.",
            'status' => -1

        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getProductReportData'])) {
    /*it is known as question report */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $limit = $json['limit'];
        $start = ($json['page'] - 1) * $limit;
        $limit_query = $limit == 0 ? "" : " limit " . $start . "," . $limit;
        $filter_query = " where q.deleted_at is null  ";

        /* if($json['company']!=""){
            $filter_query.=" and q.source='".$json['company']."'";
        }  */
        if ($json['subject'] != "") {
            $filter_query .= " and q.subjectId ='" . $json['subject'] . "'";
        }
        if ($json['concept'] != "") {
            $filter_query .= " and q.conceptId ='" . $json['concept'] . "'";
        }
        if ($json['topic'] != "") {
            $filter_query .= " and q.topic_id ='" . $json['topic'] . "'";
        }
        if ($json['questionType'] != "") {
            if ($json['questionType'] == "raw") {
                $filter_query .= " and (q.deleted_at is null and q.expertApproval = 'N' or (q.eligibleStreamId = '' OR q.eligibleStreamId IS  NULL OR q.subjectId = '' OR q.subjectId IS  NULL OR q.conceptId = '' OR q.conceptId IS  NULL OR q.key_skill_id = '' OR q.key_skill_id IS  NULL  OR q.topic_id = '' OR q.topic_id IS  NULL OR q.isWbRequired = '' OR q.isWbRequired IS  NULL OR q.questionLevel = '' OR q.questionLevel IS  NULL))";
            } elseif ($json['questionType'] == "rtu") {
                $filter_query .= " and q.deleted_at is null and q.expertApproval = 'Y' and (q.eligibleStreamId != '' AND q.eligibleStreamId IS NOT NULL AND q.subjectId != '' AND q.subjectId IS NOT NULL AND q.conceptId != '' AND q.conceptId IS NOT NULL AND q.key_skill_id != '' AND q.key_skill_id IS NOT NULL AND q.topic_id != '' AND q.topic_id IS NOT NULL AND q.isWbRequired != '' AND q.isWbRequired IS NOT NULL AND q.questionLevel != '' AND q.questionLevel IS NOT NULL)";
            } elseif ($json['questionType'] == "plus") {
                $filter_query .= " and q.deleted_at is null and q.expertAdvice is not null  and (q.peerResponseVideo is not null or q.mbr_id != '0')  and  youtubeId !=314664775 ";
            }
        }

        $data = '';
        if ($userType == 'admin') {
            $data = "SELECT q.subjectId, fv.favourite_subject as subject, c.name as conceptName, tp.name as topicName, count(distinct (CASE WHEN (isFollowUp = 'Y' or isFollowUp = 'N') and (q.expertApproval = 'N' or (q.eligibleStreamId = '' OR q.eligibleStreamId IS NULL OR q.subjectId = '' OR q.subjectId IS NULL OR q.conceptId = '' OR q.conceptId IS NULL OR q.key_skill_id = '' OR q.key_skill_id IS NULL OR q.topic_id = '' OR q.topic_id IS NULL OR q.isWbRequired = '' OR q.isWbRequired IS NULL OR q.questionLevel = '' OR q.questionLevel IS NULL)) THEN q.id ELSE NULL END)) AS rawQns, count(distinct (CASE WHEN q.expertApproval = 'Y' and (isFollowUp = 'Y' or isFollowUp = 'N') and (q.eligibleStreamId != '' AND q.eligibleStreamId IS NOT NULL AND q.subjectId != '' AND q.subjectId IS NOT NULL AND q.conceptId != '' AND q.conceptId IS NOT NULL AND q.key_skill_id != '' AND q.key_skill_id IS NOT NULL AND q.topic_id != '' AND q.topic_id IS NOT NULL AND q.isWbRequired != '' AND q.isWbRequired IS NOT NULL AND q.questionLevel != '' AND q.questionLevel IS NOT NULL) THEN q.id ELSE NULL END)) AS readyToUseQns, count(distinct (CASE WHEN (isFollowUp = 'Y' or isFollowUp = 'N') and q.expertAdvice is not null and youtubeId != 314664775 THEN q.id ELSE NULL END)) AS readyToUseGV, count(distinct (CASE WHEN (isFollowUp = 'Y' or isFollowUp = 'N') and q.expertAdvice is not null and (q.peerResponseVideo is not null or q.mbr_id != '0') and youtubeId != 314664775 THEN q.id ELSE NULL END)) AS readyToUsePlus FROM `questions` q left outer join favourite_subject fv on q.subjectId = fv.id left outer join concepts c on q.`conceptId` = c.id left outer join topic tp on q.`topic_id` = tp.id" . $filter_query . " group by q.topic_id, q.conceptId, q.subjectId order by q.conceptId";
        }
        if ($data != '') {
            $query = mysqli_query($databaseConnection, $data . $limit_query);
            $count_query = mysqli_query($databaseConnection, "select count(*) as count_result from ($data) as temp;");
            if (mysqli_num_rows($query) >= 1) {
                $count_result = mysqli_fetch_assoc($count_query);
                $values = array();
                while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
                    $verifiedExpertQry = mysqli_query($databaseConnection, "select id, name, emailId, phonenumber, linkedinProfile from panel where FIND_IN_SET('" . $row['subjectId'] . "', areaOfExpertiseId) and expertStatus='1'");
                    if (mysqli_num_rows($verifiedExpertQry) >= 1) {
                        $verifiedExpertRes = mysqli_fetch_all($verifiedExpertQry, MYSQLI_ASSOC);
                        $row['verifiedExpert'] = $verifiedExpertRes;
                    } else {
                        $row['verifiedExpert'] = [];
                    }

                    $contentVerifiedExpertQry = mysqli_query($databaseConnection, "select id, name, emailId, phonenumber, linkedinProfile from panel where FIND_IN_SET('" . $row['subjectId'] . "', areaOfExpertiseId) and expertStatus='1' and isVideoApproved = 'Y'");
                    if (mysqli_num_rows($contentVerifiedExpertQry) >= 1) {
                        $contentVerifiedExpertRes = mysqli_fetch_all($contentVerifiedExpertQry, MYSQLI_ASSOC);
                        $row['contentVerifiedExpert'] = $contentVerifiedExpertRes;
                    } else {
                        $row['contentVerifiedExpert'] = [];
                    }

                    array_push($values, $row);
                }
                $to_encode = array(
                    'result' => "success",
                    'status' => 1,
                    'data' => $values,
                    'count' => $count_result['count_result'],
                    'query' => $data . $limit_query
                );
            } else {
                $to_encode = array(
                    'result' => "error",
                    'status' => 0,
                    'query' => $data . $limit_query,
                    'errorCode' => "in Error while retrieving Product information."
                );
            }
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "in Error You are not having access this page."
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving Product information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getFollowupEngineData'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $limit = $json['limit'];
        $start = ($json['page'] - 1) * $limit;
        $limit_query = $limit == 0 ? "" : " limit " . $start . "," . $limit;
        $data = '';
        $filter_query = "";
        $having_query = " having (totalAssementPending > 0 or gPending > 0 or qPending > 0 or peerPending > 0 or tPending > 0)";
        $order_query = " order by fs.favourite_subject, p.name";
        if ($json['area'] != "") {
            $filter_query .= " and q.subjectId ='" . $json['area'] . "'";
        }
        if ($json['panelName'] != "") {
            $filter_query .= " and p.name like '%" . $json['panelName'] . "%' ";
        }
        if ($json['lcd'] != "") {
            $filter_query .= " and p.lastContactDate >='" . $json['lcd'] . " 23:59:59'";
        }
        if ($json['lad'] != "") {
            $filter_query .= " and (fr.updatedAt ='" . $json['lad'] . " 23:59:59' OR qt.updatedAt ='" . $json['lad'] . " 23:59:59')";
        }
        if ($json['highpriority'] != "") {
            if ($json['highpriority'] == '0') {
                $having_query .= " and (highAssPend = 0 OR highQPend = 0 OR highPPend = 0 OR highTPend = 0 OR highGPend = 0)";
            }
            if ($json['highpriority'] == '1+') {
                $having_query .= " and (highAssPend > 0 OR  highQPend > 0 OR  highPPend > 0 OR  highTPend > 0 OR  highGPend > 0)";
            }
        }
        if ($json['typeofwork'] != "") {
            if ($json['typeofwork'] == 'assement') {
                $having_query .= " and totalAssementPending > 0";
            }
            if ($json['typeofwork'] == 'peerVideo') {
                $having_query .= " and peerPending > 0";
            }
            if ($json['typeofwork'] == 'qnsVideo') {
                $having_query .= " and qPending > 0";
            }
            if ($json['typeofwork'] == 'guidanceVideo') {
                $having_query .= " and gPending > 0";
            }
            if ($json['typeofwork'] == 'tagging') {
                $having_query .= " and tPending > 0";
            }
        }
        if ($userType == 'admin') {
            $data = "select q.subjectId, p.id as panelId, fs.favourite_subject as areaofexpertise, p.name as panelName, p.emailId, p.phonenumber, DATEDIFF(CURDATE(), DATE(p.lastContactDate)) as lcd, CASE WHEN fsq.questionId is not null THEN DATE(fr.updatedAt) ELSE 'Not Active' END AS LastActiveAssement, CASE WHEN (fsq.questionId is not null or qt.questionId is null) THEN ROUND(AVG(DATEDIFF(fr.updatedAt, fr.requestDate))) ELSE 0 END AS avgDelay, CASE WHEN qt.questionId is not null THEN DATE(qt.updatedAt) ELSE 'Not Active' END AS LastActiveContent,

            count(distinct case when fsq.questionId is not null and ((find_in_set(q.subjectId, p.areaOfExpertiseId) and fsq.expertId is null) or fsq.expertId = p.id) and fsq.review_status IN (1,0) and p.isAssessmentApproved = 'Y' then fsq.id ELSE NULL END) AS totalAssementPending,

            count(distinct case when fsq.questionId is not null and ((find_in_set(q.subjectId, p.areaOfExpertiseId) and fsq.expertId is null) or fsq.expertId = p.id) and fsq.review_status IN (1,0) and p.isAssessmentApproved = 'Y' and fr.priority IN (1,2) then fsq.id ELSE NULL END) AS highAssPend,
            count(distinct case when fsq.questionId is not null and ((find_in_set(q.subjectId, p.areaOfExpertiseId) and fsq.expertId is null) or fsq.expertId = p.id) and fsq.review_status IN (1,0) and p.isAssessmentApproved = 'Y' and fr.priority='2' then fsq.id ELSE NULL END) AS veryHighAssPend,

            count(distinct case when qt.questionId is not null and ((find_in_set(q.subjectId, p.areaOfExpertiseId) and qt.expertId is null) or qt.expertId = p.id) and qt.delegationType ='guidanceVideo' and qt.uploadStatus !='2' and p.isVideoApproved = 'Y' then qt.id ELSE NULL END) AS gPending,

            count(distinct case when qt.questionId is not null and ((find_in_set(q.subjectId, p.areaOfExpertiseId) and qt.expertId is null) or qt.expertId = p.id) and qt.delegationType ='guidanceVideo' and qt.uploadStatus !='2' and p.isVideoApproved = 'Y' and q.priorityStatus IN (1,2) then qt.id ELSE NULL END) AS highGPend,

            count(distinct case when qt.questionId is not null and ((find_in_set(q.subjectId, p.areaOfExpertiseId) and qt.expertId is null) or qt.expertId = p.id) and qt.delegationType ='questionVideo' and qt.uploadStatus !='2' and p.isVideoApproved = 'Y' then qt.id ELSE NULL END) AS qPending,

            count(distinct case when qt.questionId is not null and ((find_in_set(q.subjectId, p.areaOfExpertiseId) and qt.expertId is null) or qt.expertId = p.id) and qt.delegationType ='questionVideo' and qt.uploadStatus !='2' and p.isVideoApproved = 'Y' and q.priorityStatus IN (1,2) then qt.id ELSE NULL END) AS highQPend,

            count(distinct case when qt.questionId is not null and ((find_in_set(q.subjectId, p.areaOfExpertiseId) and qt.expertId is null) or qt.expertId = p.id) and qt.delegationType ='peerResponseVideo' and qt.uploadStatus !='2' and p.isPeerApproved = 'Y' then qt.id ELSE NULL END) AS peerPending,

            count(distinct case when qt.questionId is not null and ((find_in_set(q.subjectId, p.areaOfExpertiseId) and qt.expertId is null) or qt.expertId = p.id) and qt.delegationType ='peerResponseVideo' and qt.uploadStatus !='2' and p.isPeerApproved = 'Y' and q.priorityStatus IN (1,2) then qt.id ELSE NULL END) AS highPPend,

            count(distinct case when qt.questionId is not null and ((find_in_set(q.subjectId, p.areaOfExpertiseId) and qt.expertId is null) or qt.expertId = p.id) and qt.delegationType ='tagging' and qt.uploadStatus !='2' and p.isVideoApproved = 'Y' then qt.id ELSE NULL END) AS tPending,

            count(distinct case when qt.questionId is not null and ((find_in_set(q.subjectId, p.areaOfExpertiseId) and qt.expertId is null) or qt.expertId = p.id) and qt.delegationType ='tagging' and qt.uploadStatus !='2' and p.isVideoApproved = 'Y' and q.priorityStatus IN (1,2) then qt.id ELSE NULL END) AS highTPend

            from panel p, questions q inner join favourite_subject fs on fs.id = q.subjectid left outer join feedback_status_question fsq on fsq.questionId = q.id left outer join feedback_request fr on fr.id = fsq.feedbackRequestId left outer join questions_transection qt on qt.questionId = q.id where q.deleted_at is null and p.deleted_at is null and p.areaOfExpertiseId != '' and ((find_in_set(q.subjectId, p.areaOfExpertiseId) and (qt.expertId is null or fsq.expertId is null)) or (qt.expertId = p.id or fsq.expertId = p.id)) and (fsq.review_status !='2' OR qt.uploadStatus !='2')" . $filter_query . " group by q.subjectId, p.id" . $having_query . $order_query;
        }
        if ($data != '') {
            $query = mysqli_query($databaseConnection, $data . $limit_query);
            $count_query = mysqli_query($databaseConnection, $data);
            if (mysqli_num_rows($query) >= 1) {
                $count_result = mysqli_num_rows($count_query);
                $values = mysqli_fetch_all($query, MYSQLI_ASSOC);
                $to_encode = array(
                    'result' => "success",
                    'status' => 1,
                    'data' => $values,
                    'count' => $count_result,
                    'query' => $data . $limit_query
                );
            } else {
                $to_encode = array(
                    'result' => "error",
                    'status' => 0,
                    'query' => $data . $limit_query,
                    'errorCode' => "in Error while retrieving Panel information."
                );
            }
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "in Error You are not having access this page."
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving Panel information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getContentFollowupEngineData'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $limit = $json['limit'];
        $start = ($json['page'] - 1) * $limit;
        $limit_query = $limit == 0 ? "" : " limit " . $start . "," . $limit;
        $data = '';
        $filter_query = "";
        $collegeJoin = " ";
        $having_query = " having (gPending > 0 or qPending > 0 or peerPending > 0 or tPending > 0)";
        $order_query = " order by fs.favourite_subject, p.name";
        if ($json['area'] != "") {
            $filter_query .= " and q.subjectId ='" . $json['area'] . "'";
        }
        if ($json['panelName'] != "") {
            $filter_query .= " and p.name like '%" . $json['panelName'] . "%' ";
        }
        if ($json['lcd'] != "") {
            $filter_query .= " and p.lastContactDate >='" . $json['lcd'] . " 23:59:59'";
        }
        if ($json['lad'] != "") {
            $filter_query .= " and (qt.updatedAt ='" . $json['lad'] . " 23:59:59')";
        }
        if ($json['highpriority'] != "") {
            if ($json['highpriority'] == '0') {
                $having_query .= " and (highQPend = 0 AND highPPend = 0 AND highTPend = 0 AND highGPend = 0)";
            }
            if ($json['highpriority'] == '1+') {
                $having_query .= " and (highQPend > 0 OR  highPPend > 0 OR  highTPend > 0 OR  highGPend > 0)";
            }
        }
        if ($json['typeofwork'] != "") {
            if ($json['typeofwork'] == 'peerVideo') {
                $having_query .= " and peerPending > 0";
            }
            if ($json['typeofwork'] == 'qnsVideo') {
                $having_query .= " and qPending > 0";
            }
            if ($json['typeofwork'] == 'guidanceVideo') {
                $having_query .= " and gPending > 0";
            }
            if ($json['typeofwork'] == 'tagging') {
                $having_query .= " and tPending > 0";
            }
        }
        // if (($json['college'] != "" and sizeof($json['college']) > 0) || ($json['stream'] != "" and sizeof($json['stream']) > 0) || ($json['interview'] != "" and sizeof($json['interview']) > 0) || $json['year'] != "")
        if (($json['college'] != "" and sizeof($json['college']) > 0) || ($json['stream'] != "" and sizeof($json['stream']) > 0) || $json['year'] != "") {
            $collegeJoin .= " inner join feedback_status_question fsq on fsq.questionId = qt.questionId inner join feedback_request fr on fr.id = fsq.feedbackRequestId inner join professionaldetails pd on pd.candidateId = fr.candidateId ";
        }
        if ($json['college'] != "" and sizeof($json['college']) > 0)
            $filter_query .= " and pd.college in ('" . implode("', '", array_map("addSlashToString", $json['college'])) . "')";
        if ($json['stream'] != "" and sizeof($json['stream']) > 0)
            $filter_query .= " and pd.specialization in ('" . implode("', '", $json['stream']) . "')";
        if ($json['year'] != "")
            $filter_query .= " and pd.year in (" . $json['year'] . ")";
        if ($userType == 'admin') {
            $data = "select q.subjectId, p.id as panelId, fs.favourite_subject as areaofexpertise, p.name as panelName, p.emailId, p.phonenumber, DATEDIFF(CURDATE(), DATE(p.lastContactDate)) as lcd, 
            
            CASE WHEN qt.questionId is not null THEN CONCAT(DATEDIFF(CURDATE(), DATE(qt.updatedAt)),' Days') ELSE 'Not Active' END AS LastActiveContent,
            count(distinct case when qt.questionId is not null and ((find_in_set(q.subjectId, p.areaOfExpertiseId) and qt.expertId is null) or qt.expertId = p.id) and qt.delegationType ='guidanceVideo' and qt.uploadStatus !='2' and p.isVideoApproved = 'Y' then qt.id ELSE NULL END) AS gPending,

            count(distinct case when qt.questionId is not null and ((find_in_set(q.subjectId, p.areaOfExpertiseId) and qt.expertId is null) or qt.expertId = p.id) and qt.delegationType ='guidanceVideo' and qt.uploadStatus !='2' and p.isVideoApproved = 'Y' and q.priorityStatus IN (1,2) then qt.id ELSE NULL END) AS highGPend,

            count(distinct case when qt.questionId is not null and ((find_in_set(q.subjectId, p.areaOfExpertiseId) and qt.expertId is null) or qt.expertId = p.id) and qt.delegationType ='guidanceVideo' and qt.uploadStatus !='2' and p.isVideoApproved = 'Y' and q.priorityStatus IN (2) then qt.id ELSE NULL END) AS veryhighGPend,

            count(distinct case when qt.questionId is not null and ((find_in_set(q.subjectId, p.areaOfExpertiseId) and qt.expertId is null) or qt.expertId = p.id) and qt.delegationType ='questionVideo' and qt.uploadStatus !='2' and p.isVideoApproved = 'Y' then qt.id ELSE NULL END) AS qPending,

            count(distinct case when qt.questionId is not null and ((find_in_set(q.subjectId, p.areaOfExpertiseId) and qt.expertId is null) or qt.expertId = p.id) and qt.delegationType ='questionVideo' and qt.uploadStatus !='2' and p.isVideoApproved = 'Y' and q.priorityStatus IN (1,2) then qt.id ELSE NULL END) AS highQPend,

            count(distinct case when qt.questionId is not null and ((find_in_set(q.subjectId, p.areaOfExpertiseId) and qt.expertId is null) or qt.expertId = p.id) and qt.delegationType ='questionVideo' and qt.uploadStatus !='2' and p.isVideoApproved = 'Y' and q.priorityStatus IN (2) then qt.id ELSE NULL END) AS veryhighQPend,

            count(distinct case when qt.questionId is not null and ((find_in_set(q.subjectId, p.areaOfExpertiseId) and qt.expertId is null) or qt.expertId = p.id) and qt.delegationType ='peerResponseVideo' and qt.uploadStatus !='2' and p.isPeerApproved = 'Y' then qt.id ELSE NULL END) AS peerPending,

            count(distinct case when qt.questionId is not null and ((find_in_set(q.subjectId, p.areaOfExpertiseId) and qt.expertId is null) or qt.expertId = p.id) and qt.delegationType ='peerResponseVideo' and qt.uploadStatus !='2' and p.isPeerApproved = 'Y' and q.priorityStatus IN (1,2) then qt.id ELSE NULL END) AS highPPend,

            count(distinct case when qt.questionId is not null and ((find_in_set(q.subjectId, p.areaOfExpertiseId) and qt.expertId is null) or qt.expertId = p.id) and qt.delegationType ='peerResponseVideo' and qt.uploadStatus !='2' and p.isPeerApproved = 'Y' and q.priorityStatus IN (2) then qt.id ELSE NULL END) AS veryhighPPend,

            count(distinct case when qt.questionId is not null and ((find_in_set(q.subjectId, p.areaOfExpertiseId) and qt.expertId is null) or qt.expertId = p.id) and qt.delegationType ='tagging' and qt.uploadStatus !='2' and p.isVideoApproved = 'Y' then qt.id ELSE NULL END) AS tPending,

            count(distinct case when qt.questionId is not null and ((find_in_set(q.subjectId, p.areaOfExpertiseId) and qt.expertId is null) or qt.expertId = p.id) and qt.delegationType ='tagging' and qt.uploadStatus !='2' and p.isVideoApproved = 'Y' and q.priorityStatus IN (1,2) then qt.id ELSE NULL END) AS highTPend,
            count(distinct case when qt.questionId is not null and ((find_in_set(q.subjectId, p.areaOfExpertiseId) and qt.expertId is null) or qt.expertId = p.id) and qt.delegationType ='tagging' and qt.uploadStatus !='2' and p.isVideoApproved = 'Y' and q.priorityStatus IN (2) then qt.id ELSE NULL END) AS veryhighTPend

            from panel p, questions q inner join favourite_subject fs on fs.id = q.subjectid inner join questions_transection qt on qt.questionId = q.id " . $collegeJoin . " where q.deleted_at is null and p.deleted_at is null and p.areaOfExpertiseId != '' and ((find_in_set(q.subjectId, p.areaOfExpertiseId) and (qt.expertId is null)) or (qt.expertId = p.id)) and (qt.uploadStatus !='2')" . $filter_query . " group by q.subjectId, p.id" . $having_query . $order_query;
        }
        if ($data != '') {
            $query = mysqli_query($databaseConnection, $data . $limit_query);
            $count_query = mysqli_query($databaseConnection, $data);
            if (mysqli_num_rows($query) >= 1) {
                $count_result = mysqli_num_rows($count_query);
                $values = mysqli_fetch_all($query, MYSQLI_ASSOC);
                $to_encode = array(
                    'result' => "success",
                    'status' => 1,
                    'data' => $values,
                    'count' => $count_result
                );
            } else {
                $to_encode = array(
                    'result' => "error",
                    'status' => 0,
                    'query' => $data . $limit_query,
                    'errorCode' => "in Error while retrieving Panel information."
                );
            }
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "in Error You are not having access this page."
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving Panel information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getAssessmentFollowupEngineData'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $limit = $json['limit'];
        $start = ($json['page'] - 1) * $limit;
        $limit_query = $limit == 0 ? "" : " limit " . $start . "," . $limit;
        $data = '';
        $filter_query = "";
        $order_query = " order by fs.favourite_subject, p.name";
        if ($json['area'] != "") {
            $filter_query .= " and q.subjectId in('" . implode("', '", $json['area']) . "')";
            $having_query = " HAVING 1 ";
        } else if ($json['redirect'] == 'assessmentCompleteMore24' || $json['redirect'] == 'assessmentComplete24' || $json['redirect'] == 'assessmentComplete12') {

            $having_query = " HAVING 1 ";
        } else if ($json['area'] == '') {
            $having_query = " having totalAssementPending > 0 ";
        }
        if ($json['college'] != "" and sizeof($json['college']) > 0)
            $filter_query .= " and pd.college in ('" . implode("', '", array_map("addSlashToString", $json['college'])) . "')";
        if ($json['stream'] != "" and sizeof($json['stream']) > 0)
            $filter_query .= " and pd.specialization in ('" . implode("', '", $json['stream']) . "')";
        if ($json['year'] != "")
            $filter_query .= " and pd.year in (" . $json['year'] . ")";
        if ($json['panelName'] != "") {
            $filter_query .= " and p.name like '%" . $json['panelName'] . "%' ";
        }
        if ($json['lcd'] != "") {
            $filter_query .= " and p.lastContactDate >='" . $json['lcd'] . " 23:59:59'";
        }

        if ($json['lad'] != "") {
            if ($json['lad'] == '<=7') {
                $filter_query .= " and DATEDIFF(CURDATE(), DATE(p.lastActiveOnAssessment)) <= 7 ";
            } else if ($json['lad'] == '0-10') {
                $filter_query .= " and DATEDIFF(CURDATE(), DATE(p.lastActiveOnAssessment)) <= 10 ";
            } else if ($json['lad'] == '11-30') {
                $filter_query .= " and DATEDIFF(CURDATE(), DATE(p.lastActiveOnAssessment)) > 10 and DATEDIFF(CURDATE(), DATE(p.lastActiveOnAssessment)) <= 30 ";
            } else if ($json['lad'] == '31+') {
                $filter_query .= " and DATEDIFF(CURDATE(), DATE(p.lastActiveOnAssessment)) > 30 ";
            }
        }
        if ($json['highpriority'] != "") {
            if ($json['highpriority'] == '0') {
                $having_query .= " and (highAssPend = 0)";
            }
            if ($json['highpriority'] == '1+') {
                $having_query .= " and (highAssPend > 0)";
            }
        }

        if ($json['interview'] != "") {
            $filter_query .= " and i.preInterviewId in (" . implode(',', $json['interview']) . ") ";
        }

        if ($json['redirect'] == 'assessmentOpen12') {

            $filter_query .= " and fr.review_status=0 and TIMESTAMPDIFF(HOUR,fsq.createdAt,now())<=11 ";

        } else if ($json['redirect'] == 'assessmentOpen24') {

            $filter_query .= " and fr.review_status=0 and (TIMESTAMPDIFF(HOUR,fsq.createdAt,now()) >11 and TIMESTAMPDIFF(HOUR,fsq.createdAt,now())<=24) ";

        } else if ($json['redirect'] == 'assessmentOpenMore24') {

            $filter_query .= " and fr.review_status=0 and TIMESTAMPDIFF(HOUR,fsq.createdAt,now()) >24 ";

        } else if ($json['redirect'] == 'assessmentInprogress12') {

            $filter_query .= " and fr.review_status=1 and TIMESTAMPDIFF(HOUR,fsq.createdAt,now())<=11 ";

        } else if ($json['redirect'] == 'assessmentInprogress24') {

            $filter_query .= " and fr.review_status=1 and (TIMESTAMPDIFF(HOUR,fsq.createdAt,now()) >11 and TIMESTAMPDIFF(HOUR,fsq.createdAt,now())<=24) ";

        } else if ($json['redirect'] == 'assessmentInprogressMore24') {

            $filter_query .= " and fr.review_status=1 and TIMESTAMPDIFF(HOUR,fsq.createdAt,now()) >24 ";

        } else if ($json['redirect'] == 'assessmentComplete12') {

            $filter_query .= " and fr.review_status=2 and TIMESTAMPDIFF(HOUR,fr.updatedAt,now())<=11 ";

        } else if ($json['redirect'] == 'assessmentComplete24') {

            $filter_query .= " and fr.review_status=2 and (TIMESTAMPDIFF(HOUR,fr.updatedAt,now()) >11 and TIMESTAMPDIFF(HOUR,fr.updatedAt,now())<=24) ";

        } else if ($json['redirect'] == 'assessmentCompleteMore24') {

            $filter_query .= " and fr.review_status=2 and TIMESTAMPDIFF(HOUR,fr.updatedAt,now()) >24 ";

        }

        if ($json['redirect'] != 'assessmentCompleteMore24' && $json['redirect'] != 'assessmentComplete24' && $json['redirect'] != 'assessmentComplete12' && $json['redirect'] != 'assessmentCompletedMore24Sub' && $json['redirect'] != 'assessmentComplete24Sub' && $json['redirect'] != 'assessmentComplete12Sub') {

            $filter_query .= "AND fsq.review_status !='2'";
        }

        // withsubject filter
        if ($json['redirect'] == 'assessmentOpen12Sub') {

            $filter_query .= " and fsq.review_status=0 and TIMESTAMPDIFF(HOUR,fsq.createdAt,now())<=11 ";

        } else if ($json['redirect'] == 'assessmentOpen24Sub') {

            $filter_query .= " and fsq.review_status=0 and (TIMESTAMPDIFF(HOUR,fsq.createdAt,now()) >11 and TIMESTAMPDIFF(HOUR,fsq.createdAt,now())<=24) ";

        } else if ($json['redirect'] == 'assessmentOpenMore24Sub') {

            $filter_query .= " and fsq.review_status=0 and TIMESTAMPDIFF(HOUR,fsq.createdAt,now()) >24 ";

        } else if ($json['redirect'] == 'assessmentInprogress12Sub') {

            $filter_query .= " and fsq.review_status=1 and TIMESTAMPDIFF(HOUR,fsq.createdAt,now())<=11 ";

        } else if ($json['redirect'] == 'assessmentInprogress24Sub') {

            $filter_query .= " and fsq.review_status=1 and (TIMESTAMPDIFF(HOUR,fsq.createdAt,now()) >11 and TIMESTAMPDIFF(HOUR,fsq.createdAt,now())<=24) ";

        } else if ($json['redirect'] == 'assessmentInprogressMore24Sub') {

            $filter_query .= " and fsq.review_status=1 and TIMESTAMPDIFF(HOUR,fsq.createdAt,now()) >24 ";

        } else if ($json['redirect'] == 'assessmentComplete12Sub') {

            $filter_query .= " and fsq.review_status=2 and TIMESTAMPDIFF(HOUR,fr.updatedAt,now())<=11 ";

        } else if ($json['redirect'] == 'assessmentComplete24Sub') {

            $filter_query .= " and fsq.review_status=2 and (TIMESTAMPDIFF(HOUR,fr.updatedAt,now()) >11 and TIMESTAMPDIFF(HOUR,fr.updatedAt,now())<=24) ";

        } else if ($json['redirect'] == 'assessmentCompleteMore24Sub') {

            $filter_query .= " and fsq.review_status=2 and TIMESTAMPDIFF(HOUR,fr.updatedAt,now()) >24 ";

        }

        if ($userType == 'admin') {
            /*  $data = "SELECT t1.*,ROUND(AVG(t2.noOfQuestions))+1 as avgRate FROM (select q.subjectId,p.id as panelId,fs.favourite_subject as areaofexpertise,p.name as panelName,p.emailId,p.phonenumber,

             'N' as colorChange,

             DATEDIFF(CURDATE(), DATE(p.lastContactDate)) as lcd,

             CASE WHEN p.id is not null and p.lastActiveOnAssessment is not null THEN CONCAT(TIMESTAMPDIFF(DAY,p.lastActiveOnAssessment,NOW()),' Days')  ELSE 'Not Active' END AS LastActiveAssement, 

             CASE WHEN (fsq.questionId is not null) THEN ROUND(AVG(DATEDIFF(fr.updatedAt, fr.requestDate))) ELSE 0 END AS avgDelay,            

             count(distinct case when fsq.questionId is not null and ((find_in_set(q.subjectId, p.areaOfExpertiseId) and fsq.expertId is null) or fsq.expertId = p.id) and fsq.review_status IN (1,0) and p.isAssessmentApproved = 'Y' then fsq.id ELSE NULL END) AS totalAssementPending,  

             (SELECT count(distinct feedback_status_question.id) FROM feedback_status_question WHERE feedback_status_question.review_status = 2 AND feedback_status_question.expertId = p.id) AS totalAssementCompleted,           

             count(distinct case when fsq.questionId is not null and ((find_in_set(q.subjectId, p.areaOfExpertiseId) and fsq.expertId is null) or fsq.expertId = p.id) and fsq.review_status IN (1,0) and p.isAssessmentApproved = 'Y' and fr.priority IN (1,2) then fsq.id ELSE NULL END) AS highAssPend,           

             count(distinct case when fsq.questionId is not null and ((find_in_set(q.subjectId, p.areaOfExpertiseId) and fsq.expertId is null) or fsq.expertId = p.id) and fsq.review_status IN (1,0) and p.isAssessmentApproved = 'Y' and fr.priority='2' then fsq.id ELSE NULL END) AS veryHighAssPend           

             from panel p, feedback_status_question fsq INNER JOIN questions q on fsq.questionId = q.id LEFT join favourite_subject fs on fs.id = q.subjectid inner join feedback_request fr on fr.id = fsq.feedbackRequestId INNER JOIN professionaldetails pd  on pd.candidateId = fr.candidateId WHERE (find_in_set(q.subjectId, p.areaOfExpertiseId) OR fsq.expertId = p.id) AND p.expertStatus = 1 AND p.deleted_at IS null AND p.lastActiveOnAssessment IS NOT NULL AND p.isAssessmentApproved = 'Y' AND q.deleted_at is null and fsq.review_status !='2' " . $filter_query . " group by q.subjectId, p.id " . $having_query . $order_query." ) as t1 INNER JOIN (SELECT COUNT(DISTINCT id) as noOfQuestions,createdAt,feedbackGivenBy FROM expert_review er WHERE er.review_type = 'question' GROUP BY er.feedbackGivenBy,year(er.createdAt),month(er.createdAt),day(er.createdAt) ORDER BY er.feedbackGivenBy ASC) as t2 ON t1.panelId = t2.feedbackGivenBy GROUP BY t1.subjectId, t1.panelId ORDER BY t1.panelName,t1.areaofexpertise"; */

            //     $data = "select q.subjectId, p.id as panelId, fs.favourite_subject as areaofexpertise, p.name as panelName, p.emailId, p.phonenumber, DATEDIFF(CURDATE(), DATE(p.lastContactDate)) as lcd,  CASE WHEN p.id is not null and p.lastActiveOnAssessment is not null THEN p.lastActiveOnAssessment  ELSE 'Not Active' END AS LastActiveAssement, CASE WHEN (fsq.questionId is not null) THEN ROUND(AVG(DATEDIFF(fr.updatedAt, fr.requestDate))) ELSE 0 END AS avgDelay,
            //     count(distinct case when fsq.questionId is not null and ((find_in_set(q.subjectId, p.areaOfExpertiseId) and fsq.expertId is null) or fsq.expertId = p.id) and fsq.review_status IN (1,0) and p.isAssessmentApproved = 'Y' then fsq.id ELSE NULL END) AS totalAssementPending,
            //    count(distinct case when fsq.questionId is not null and ((find_in_set(q.subjectId, p.areaOfExpertiseId) and fsq.expertId is null) or fsq.expertId = p.id) and fsq.review_status IN (1,0) and p.isAssessmentApproved = 'Y' and fr.priority IN (1,2) then fsq.id ELSE NULL END) AS highAssPend,
            //    count(distinct case when fsq.questionId is not null and ((find_in_set(q.subjectId, p.areaOfExpertiseId) and fsq.expertId is null) or fsq.expertId = p.id) and fsq.review_status IN (1,0) and p.isAssessmentApproved = 'Y' and fr.priority='2' then fsq.id ELSE NULL END) AS veryHighAssPend
            //    from panel p, questions q inner join favourite_subject fs on fs.id = q.subjectid inner join feedback_status_question fsq on fsq.questionId = q.id inner join feedback_request fr on fr.id = fsq.feedbackRequestId inner join professionaldetails pd  on pd.candidateId = fr.candidateId  where q.deleted_at is null and p.deleted_at is null and p.areaOfExpertiseId != '' and ((find_in_set(q.subjectId, p.areaOfExpertiseId) and fsq.expertId is null) or  fsq.expertId = p.id) and (fsq.review_status !='2')" . $filter_query . " group by q.subjectId, p.id" . $having_query . $order_query; 
            $data = "select t3.* from (SELECT t1.*,ROUND(AVG(t2.noOfQuestions))+1 as avgRate FROM (select q.subjectId,p.id as panelId,fs.favourite_subject as areaofexpertise,p.name as panelName,p.emailId,p.phonenumber, 'N' as colorChange, DATEDIFF(CURDATE(), DATE(p.lastContactDate)) as lcd, CASE WHEN p.id is not null and p.lastActiveOnAssessment is not null THEN TIMESTAMPDIFF(DAY,p.lastActiveOnAssessment,NOW()) ELSE 0 END AS LastActiveAssement, CASE WHEN (fsq.questionId is not null) THEN SEC_TO_TIME(ROUND(AVG(TIMEDIFF(fr.updatedAt, fr.requestDate))/50)) ELSE 0 END AS avgDelay, count(distinct case when fsq.questionId is not null and ((find_in_set(q.subjectId, p.areaOfExpertiseId) and fsq.expertId is null) or fsq.expertId = p.id) and fsq.review_status IN (1,0) and p.isAssessmentApproved = 'Y' then fsq.id ELSE NULL END) AS totalAssementPending, count(distinct case when fsq.questionId is not null and ((find_in_set(q.subjectId, p.areaOfExpertiseId) and fsq.expertId is null) or fsq.expertId = p.id) and fsq.review_status IN (0) and p.isAssessmentApproved = 'Y' then fsq.id ELSE NULL END) AS totalAssementOpen, count(distinct case when fsq.questionId is not null and ((find_in_set(q.subjectId, p.areaOfExpertiseId) and fsq.expertId is null) or fsq.expertId = p.id) and fsq.review_status IN (1,0) and p.isAssessmentApproved = 'Y' and fr.priority IN (1,2) then fsq.id ELSE NULL END) AS highAssPend, count(distinct case when fsq.questionId is not null and ((find_in_set(q.subjectId, p.areaOfExpertiseId) and fsq.expertId is null) or fsq.expertId = p.id) and fsq.review_status IN (1,0) and p.isAssessmentApproved = 'Y' and fr.priority='2' then fsq.id ELSE NULL END) AS veryHighAssPend from panel p,feedback_status_question fsq inner join feedback_request fr on fr.id = fsq.feedbackRequestId INNER JOIN questions q on q.id = fsq.questionId inner join favourite_subject fs on fs.id = q.subjectid INNER JOIN professionaldetails pd on pd.candidateId = fr.candidateId inner join interview i on i.id=fr.interviewId where (find_in_set(q.subjectId, p.areaOfExpertiseId) OR fsq.expertId = p.id) AND p.expertStatus = 1 AND p.deleted_at IS null AND p.isAssessmentApproved = 'Y' and q.deleted_at is null " . $filter_query . " group by q.subjectId,p.id " . $having_query . $order_query . ") as t1 LEFT JOIN (SELECT COUNT(id) as noOfQuestions,createdAt,feedbackGivenBy FROM expert_review er WHERE er.review_type = 'question' GROUP BY er.feedbackGivenBy,year(er.createdAt),month(er.createdAt),day(er.createdAt)) as t2 ON t1.panelId = t2.feedbackGivenBy GROUP BY t1.subjectId, t1.panelId) as t3 order by t3.subjectId,t3.LastActiveAssement";

        }
        if ($data != '') {
            $query = mysqli_query($databaseConnection, $data . $limit_query);
            $count_query = mysqli_query($databaseConnection, $data);
            if (mysqli_num_rows($query) >= 1) {
                $count_result = mysqli_num_rows($count_query);
                // $values = mysqli_fetch_all($query, MYSQLI_ASSOC);
                $values = array();
                while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
                    $submitFeedbackDetails = array();

                    $submitFeedbackDetailsQuery = mysqli_query($databaseConnection, "SELECT count(fsq.id) as no_of_Question,fsq.feedbackRequestId,'N' as colorChange,fsq.expertId,u.id,u.firstName,u.emailId,u.mobileNumber,i.name,fr.interviewSessionId,GROUP_CONCAT(fsq.review_status) as review, min(fsq.review_status) as minStatus, max(fsq.review_status) as maxStatus FROM `feedback_status_question` fsq INNER JOIN feedback_request fr ON fr.id = fsq.feedbackRequestId LEFT JOIN interview i on fr.interviewId = i.id INNER JOIN users u ON fr.candidateId = u.id WHERE fsq.feedbackRequestId IN (SELECT fsq.feedbackRequestId FROM feedback_status_question fsq WHERE fsq.review_status IN (0,1) AND fsq.expertId =  " . $row['panelId'] . " Group by fsq.feedbackRequestId) AND fsq.expertId = " . $row['panelId'] . " AND fsq.review_status IN (0,1)  GROUP BY fsq.feedbackRequestId;");
                    if (mysqli_num_rows($submitFeedbackDetailsQuery) > 0) {
                        $submitFeedbackDetails = mysqli_fetch_all($submitFeedbackDetailsQuery, MYSQLI_ASSOC);
                    }
                    $row['pendingInterviewDetails'] = $submitFeedbackDetails;

                    $avgDetailsQuery = mysqli_query($databaseConnection, "Select case when temp.avgpickup is not null then SEC_TO_TIME(round(sum(temp.avgpickup)/50)) else 0 end as avgpickup,temp.feedbackGivenBy,SEC_TO_TIME(round(sum(temp.avgfeedback)/50)) as avgfeedback,temp.favourite_subject from (select TIMESTAMPDIFF(SECOND,er.createdAt,max(fsq.createdAt)) as avgpickup,er.feedbackGivenBy,TIMESTAMPDIFF(SECOND,t.requestdate,min(er.createdAt)) as avgfeedback,fv.favourite_subject from (select fr.id,fr.review_status,fr.requestDate from feedback_request fr where fr.review_status=2 order by id desc limit 50) as t inner join expert_review er on er.feedback_request_id=t.id inner join feedback_status_question fsq on fsq.feedbackRequestId = er.feedback_request_id inner join questions q on er.questionId=q.id inner join favourite_subject fv on fv.id =q.subjectId where er.review_type='question' and q.subjectId is not null and er.overAllRating !='videoIssue' and er.feedbackGivenby=" . $row['panelId'] . "  group by fv.id,t.id) as temp group by temp.feedbackGivenBy,temp.favourite_subject;");
                    if (mysqli_num_rows($avgDetailsQuery) > 0) {
                        $avgDetailsQueryResult = mysqli_fetch_all($avgDetailsQuery, MYSQLI_ASSOC);

                        $row['avgfeedback'] = $avgDetailsQueryResult[0]['avgfeedback'];
                        $row['avgpickup'] = $avgDetailsQueryResult[0]['avgpickup'];
                    } else {
                        $row['avgfeedback'] = 0;
                        $row['avgpickup'] = 0;
                    }
                    unset($submitFeedbackDetails);
                    $submitFeedbackDetails = array();

                    array_push($values, $row);
                }
                $to_encode = array(
                    'result' => "success",
                    'status' => 1,
                    'data' => $values,
                    'count' => $count_result,
                    'qry' => $data
                );
            } else {
                $to_encode = array(
                    'result' => "No Record Found",
                    'status' => 0,
                    'query' => $data . $limit_query
                );
            }
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "in Error You are not having access this page."
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving Panel information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['lastContactToExpertUpdate'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $panelId = $json['panelId'];
        $currentDateTime = date('Y-m-d H:i:s');
        if ($userType == 'admin') {
            $update = "UPDATE panel set lastContactDate = '" . $currentDateTime . "' where id = $panelId";
            $query = mysqli_query($databaseConnection, $update);
            if ($query) {
                $to_encode = array(
                    'result' => "success",
                    'status' => 1,
                );
            } else {
                $to_encode = array(
                    'result' => "error",
                    'status' => 0,
                    'query' => $update
                );
            }
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "in Error You are not having access this page."
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while updating panel"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getContentWorkData'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $limit = $json['limit'];
        $start = ($json['page'] - 1) * $limit;
        $limit_query = $limit == 0 ? "" : " limit " . $start . "," . $limit;
        $data = '';
        $filter_query = " ";
        $having_query = " having 1 ";
        $collegeJoin = " ";
        if ($json['area'] != "") {
            $filter_query .= " and q.subjectId ='" . $json['area'] . "'";
        }
        if ($json['varifiedExpert'] != "") {
            if ($json['varifiedExpert'] == '0') {
                $having_query .= " and verified = 0";
            }
            if ($json['varifiedExpert'] == '1') {
                $having_query .= " and verified = 1";
            }
            if ($json['varifiedExpert'] == '2') {
                $having_query .= " and verified = 2";
            }
            if ($json['varifiedExpert'] == '2+') {
                $having_query .= " and  verified > 2";
            }
        }
        if ($json['unverifiedExpert'] != "") {
            if ($json['unverifiedExpert'] == '0') {
                $having_query .= " and unverified = 0";
            }
            if ($json['unverifiedExpert'] == '1') {
                $having_query .= " and unverified > 0";
            }
        }
        if ($json['activeExpert'] != "") {
            if ($json['activeExpert'] == '0') {
                $having_query .= " and activeExpert = 0";
            }
            if ($json['activeExpert'] == '1') {
                $having_query .= " and activeExpert = 1";
            }
            if ($json['activeExpert'] == '2') {
                $having_query .= " and  activeExpert = 2";
            }
            if ($json['activeExpert'] == '2+') {
                $having_query .= " and activeExpert > 2";
            }
        }
        if ($json['jobPending'] != "") {
            if ($json['jobPending'] == '0') {
                $having_query .= " and pending = 0";
            }
            if ($json['jobPending'] == '1') {
                $having_query .= " and pending > 0";
            }
        }
        if ($json['from_date'] != "" && $json['to_date'] == "") {
            $filter_query .= " and (qt.updatedAt >= '" . $json['to_date'] . " 23:59:59')";
        }
        if ($json['from_date'] == "" && $json['to_date'] != "") {
            $filter_query .= " and (qt.updatedAt <= '" . $json['to_date'] . " 23:59:59') ";
        }
        if ($json['from_date'] != "" && $json['to_date'] != "") {
            $filter_query .= " and (qt.updatedAt >= '" . $json['from_date'] . " 00:00:00' and qt.updatedAt <= '" . $json['to_date'] . " 23:59:59') ";
        }
        if ($json['typeofWork'] != "" and sizeof($json['typeofWork']) > 0) {
            if ($json['typeofWork'] != [""]) {
                $typeofWorkStatus = $json['typeofWork'];
                $filter_ques = "0 ";
                foreach ($typeofWorkStatus as $Status) {
                    if ($Status == 'peerVideo') {
                        $filter_ques .= " OR (qt.delegationType='peerResponseVideo')";
                    }
                    if ($Status == 'qnsVideo') {
                        $filter_ques .= " OR (qt.delegationType='questionVideo')";
                    }
                    if ($Status == 'guidanceVideo') {
                        $filter_ques .= " OR (qt.delegationType='guidanceVideo')";
                    }
                    if ($Status == 'tagging') {
                        $filter_ques .= " OR (qt.delegationType='tagging')";
                    }
                }
                $filter_query .= " and (" . $filter_ques . ")";
            }
        }

        if (($json['college'] != "" and sizeof($json['college']) > 0) || ($json['stream'] != "" and sizeof($json['stream']) > 0) || $json['year'] != "") {
            $collegeJoin .= " inner join feedback_status_question fsq on fsq.questionId = qt.questionId inner join feedback_request fr on fr.id = fsq.feedbackRequestId inner join professionaldetails pd on pd.candidateId = fr.candidateId ";
        }
        if ($json['college'] != "" and sizeof($json['college']) > 0)
            $filter_query .= " and pd.college in ('" . implode("', '", array_map("addSlashToString", $json['college'])) . "')";
        if ($json['stream'] != "" and sizeof($json['stream']) > 0)
            $filter_query .= " and pd.specialization in ('" . implode("', '", $json['stream']) . "')";
        if ($json['year'] != "")
            $filter_query .= " and pd.year in (" . $json['year'] . ")";

        if ($userType == 'admin') {
            /* Change in query for content-work report 18-05-2021 Naraayn */
            $data = "SELECT fv.favourite_subject as subjectName, qt.delegationType AS typeOfWork,COUNT( DISTINCT CASE WHEN DATEDIFF(CURDATE(),Date(qt.updatedAt)) <=30 and qt.uploadStatus in(1,2) then qt.expertId ELSE NULL END) as activeExpert,COUNT( DISTINCT CASE WHEN qt.uploadStatus in(1,2) then qt.expertId ELSE NULL END) as activeExpertAtleastOnce,COUNT(DISTINCT CASE WHEN qt.uploadStatus = '2' THEN qt.questionId ELSE NULL END) AS compleatedJob,
            COUNT(DISTINCT CASE WHEN qt.uploadStatus = '1' THEN qt.questionId ELSE NULL END) AS inprogress,COUNT(DISTINCT CASE WHEN qt.uploadStatus = '0' THEN  qt.questionId ELSE NULL END ) AS pending,COUNT(DISTINCT CASE WHEN qt.uploadStatus = '0' and q.priorityStatus ='1' THEN  qt.questionId ELSE NULL END ) AS highPending,COUNT(DISTINCT CASE WHEN qt.uploadStatus = '0' and q.priorityStatus ='2' THEN  qt.questionId ELSE NULL END ) AS ultraHighPending,CASE WHEN (qt.delegationType='guidanceVideo' || qt.delegationType='questionVideo' || qt.delegationType='tagging') THEN (SELECT count(p.id)  FROM panel p  WHERE p.expertStatus = '1' and p.isVideoApproved='Y' and FIND_IN_SET(q.subjectId,p.areaOfExpertiseId )) WHEN (qt.delegationType='peerResponseVideo') THEN (SELECT count(p.id)  FROM panel p  WHERE p.expertStatus = '1' and p.isPeerApproved='Y' and FIND_IN_SET(q.subjectId,p.areaOfExpertiseId )) ELSE 0 END AS verified,
            CASE WHEN (qt.delegationType='guidanceVideo' || qt.delegationType='questionVideo' || qt.delegationType='tagging') THEN (SELECT count(p.id)  FROM panel p  WHERE p.expertStatus = '1' and p.isVideoApproved='N' and p.underTesting='Y' and FIND_IN_SET(q.subjectId,p.areaOfExpertiseId )) WHEN (qt.delegationType='peerResponseVideo') THEN (SELECT count(p.id)  FROM panel p  WHERE p.expertStatus = '1' and p.isPeerApproved='N' and p.underTesting='Y' and FIND_IN_SET(q.subjectId,p.areaOfExpertiseId )) ELSE 0 END AS unverified,CASE WHEN (qt.delegationType='guidanceVideo' || qt.delegationType='questionVideo' || qt.delegationType='tagging') THEN (SELECT count(p.id)  FROM panel p  WHERE p.expertStatus = '1' and p.isVideoApproved='N' and p.underTesting='N' and FIND_IN_SET(q.subjectId,p.areaOfExpertiseId )) WHEN (qt.delegationType='peerResponseVideo') THEN (SELECT count(p.id)  FROM panel p  WHERE p.expertStatus = '1' and p.isPeerApproved='N' and p.underTesting='N' and FIND_IN_SET(q.subjectId,p.areaOfExpertiseId )) ELSE 0 END AS rejected
            FROM questions q inner join favourite_subject fv on q.subjectId = fv.id left outer join questions_transection qt on q.id = qt.questionId " . $collegeJoin . " WHERE qt.questionId is not null and q.deleted_at is null " . $filter_query . " group by qt.delegationType,q.subjectId " . $having_query . " order by fv.favourite_subject";
        }
        if ($data != '') {
            $query = mysqli_query($databaseConnection, $data . $limit_query);
            if (mysqli_num_rows($query) >= 1) {
                $count = mysqli_query($databaseConnection, $data);
                $count_result = mysqli_num_rows($count);
                $values = mysqli_fetch_all($query, MYSQLI_ASSOC);

                $to_encode = array(
                    'result' => "success",
                    'status' => 1,
                    'data' => $values,
                    'count' => $count_result

                );
            } else {
                $to_encode = array(
                    'result' => "error",
                    'status' => 0,
                    'query' => $data . $limit_query,
                    'errorCode' => "in Error while retrieving content information."
                );
            }
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "in Error You are not having access this page."
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving content information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getAssessmentWorkData'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $limit = $json['limit'];
        $start = ($json['page'] - 1) * $limit;
        $limit_query = $limit == 0 ? "" : " limit " . $start . "," . $limit;
        $data = '';
        $filter_query = " ";
        $having_query = " having 1 ";
        if ($json['area'] != "") {
            $filter_query .= " and q.subjectId ='" . $json['area'] . "'";
        }
        if ($json['college'] != "" and sizeof($json['college']) > 0)
            $filter_query .= " and pd.college in ('" . implode("', '", array_map("addSlashToString", $json['college'])) . "')";
        if ($json['stream'] != "" and sizeof($json['stream']) > 0)
            $filter_query .= " and pd.specialization in ('" . implode("', '", $json['stream']) . "')";
        if ($json['year'] != "")
            $filter_query .= " and pd.year in (" . $json['year'] . ")";
        if ($json['varifiedExpert'] != "") {
            if ($json['varifiedExpert'] == '0') {
                $having_query .= " and verified = 0";
            }
            if ($json['varifiedExpert'] == '1') {
                $having_query .= " and verified = 1";
            }
            if ($json['varifiedExpert'] == '2') {
                $having_query .= " and verified = 2";
            }
            if ($json['varifiedExpert'] == '2+') {
                $having_query .= " and  verified > 2";
            }
        }
        if ($json['jobPending'] != "") {
            if ($json['jobPending'] == '0') {
                $having_query .= " and pending = 0";
            }
            if ($json['jobPending'] == '1') {
                $having_query .= " and pending > 0";
            }
        }
        if ($json['unverifiedExpert'] != "") {
            if ($json['unverifiedExpert'] == '0') {
                $having_query .= " and unverified = 0";
            }
            if ($json['unverifiedExpert'] == '1') {
                $having_query .= " and unverified > 0";
            }
        }
        if ($json['activeExpert'] != "") {
            if ($json['activeExpert'] == '0') {
                $having_query .= " and activeExpert = 0";
            }
            if ($json['activeExpert'] == '1') {
                $having_query .= " and activeExpert = 1";
            }
            if ($json['activeExpert'] == '2') {
                $having_query .= " and  activeExpert = 2";
            }
            if ($json['activeExpert'] == '2+') {
                $having_query .= " and activeExpert > 2";
            }
        }
        if ($json['from_date'] != "" && $json['to_date'] == "") {
            $filter_query .= " and (fr.updatedAt >= '" . $json['from_date'] . " 23:59:59')";
        }
        if ($json['from_date'] == "" && $json['to_date'] != "") {
            $filter_query .= " and (fr.updatedAt <= '" . $json['to_date'] . " 23:59:59')";
        }
        if ($json['from_date'] != "" && $json['to_date'] != "") {
            $filter_query .= " and (fr.updatedAt >= '" . $json['from_date'] . " 00:00:00' and fr.updatedAt <= '" . $json['to_date'] . " 23:59:59')";
        }
        if ($userType == 'admin') {
            /* Change in query for content-work report 6-30-2021 Naraayn */
            $data = "SELECT fv.favourite_subject as subjectName,count(distinct CASE WHEN DATEDIFF(CURDATE(),Date(fr.updatedAt)) <=30 and fsq.review_status in(1,2) THEN  fsq.expertId  ELSE Null END) as activeExpert,count(distinct CASE WHEN fsq.review_status in(1,2) THEN  fsq.expertId  ELSE Null END) as activeExpertAtleastOnce,
            COUNT(DISTINCT CASE WHEN fsq.review_status = '2' THEN fsq.id ELSE NUll END)  AS compleatedJob,
            COUNT(DISTINCT CASE WHEN fsq.review_status = '1' THEN fsq.id ELSE NUll END)  AS inprogress,
            COUNT(DISTINCT CASE WHEN fsq.review_status = '0' THEN fsq.id ELSE NUll END)  AS pending,
            COUNT(DISTINCT CASE WHEN fsq.review_status = '0' and fr.priority='1' THEN fsq.id ELSE NUll END)  AS highPending,
            COUNT(DISTINCT CASE WHEN fsq.review_status = '0' and fr.priority='2' THEN fsq.id ELSE NUll END)  AS ultraHighPending,
            (SELECT count(p.id)  FROM panel p  WHERE p.expertStatus = '1' and p.isAssessmentApproved='Y' and FIND_IN_SET(q.subjectId,p.areaOfExpertiseId ))  AS verified,
            (SELECT count(p.id)  FROM panel p  WHERE p.expertStatus = '1' and p.isAssessmentApproved='N' and p.underTesting='Y' and FIND_IN_SET(q.subjectId,p.areaOfExpertiseId )) AS unverified,
            (SELECT count(p.id)  FROM panel p  WHERE p.expertStatus = '1' and p.isAssessmentApproved='N' and p.underTesting='N' and FIND_IN_SET(q.subjectId,p.areaOfExpertiseId ))  AS rejected
            FROM questions q inner join favourite_subject fv on q.subjectId = fv.id inner join feedback_status_question fsq on q.id = fsq.questionId inner join feedback_request fr on fr.id = fsq.feedbackRequestId inner join professionaldetails pd  on pd.candidateId = fr.candidateId where q.deleted_at is null " . $filter_query . " group by q.subjectId " . $having_query . "  order by fv.favourite_subject";
        }
        if ($data != '') {
            $query = mysqli_query($databaseConnection, $data . $limit_query);
            if (mysqli_num_rows($query) >= 1) {
                $count = mysqli_query($databaseConnection, $data);
                $count_result = mysqli_num_rows($count);
                $values = mysqli_fetch_all($query, MYSQLI_ASSOC);

                $to_encode = array(
                    'result' => "success",
                    'status' => 1,
                    'data' => $values,
                    'count' => $count_result,

                );
            } else {
                $to_encode = array(
                    'result' => "error",
                    'status' => 0,
                    'query' => $data . $limit_query,
                    'errorCode' => "in Error while retrieving content information."
                );
            }
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "in Error You are not having access this page."
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving content information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['updateCompanyIdForCookies'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['candidateId'];
        $data = "SELECT * FROM `scodes` WHERE userId='" . $candidateId . "' and s_is_availed = 'Y'";
        $query = mysqli_query($databaseConnection, $data);
        if (mysqli_num_rows($query) >= 1) {
            $row = mysqli_fetch_assoc($query);
            $companyId = $row['companyId'];
        } else {
            $companyId = '0';
        }
        $to_encode = array(
            'status' => 1,
            'result' => "success",
            'companyId' => $companyId
        );
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "Error whire retrieving companyId information."
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['getAllInterviews'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        //$companyId = $json['companyId'];
        $candidateId = $json['candidateId'];
        $values = array();
        $interviews = array();
        $interviewValues = array();
        $panelValues = array();
        $menuInterviews = array();

        $menuQuery = mysqli_query($databaseConnection, "select * from menu where id in(1,6) order by sequence");
        while ($menuResult = mysqli_fetch_array($menuQuery, MYSQLI_ASSOC)) {
            if ($menuResult['id'] == '1') {
                $interviewData = "SELECT c.id as companyId," . $menuResult['id'] . " as productId,st.sector as sectorId,pr.id as preInterviewId,CASE WHEN pr.interviewName is null THEN c.name  ELSE pr.interviewName End as `name`,pr.targetAudience as targetAudience,pr.duration as duration,9 as categoryType,pr.interviewLevel as interviewLevel FROM `scps_transaction` st INNER JOIN aspiration_company c ON st.company = c.id INNER JOIN preInterview pr on pr.id=st.preInterviewId WHERE st.company NOT IN (0)  and pr.productId=1 and pr.interviewStatus in ('Active') and (pr.interviewExpireDate>=now() or pr.interviewExpireDate is null) GROUP BY st.preInterviewId ORDER BY pr.id desc";

                // $interviewData = "SELECT s.id,".$menuResult['id']." as productId,st.sector as sectorId,s.name as `name`,'All Stream' as targetAudience,'25-30 min' as duration,9 as categoryType,'Medium' as interviewLevel FROM `scps_transaction` st INNER JOIN sector s ON st.sector = s.id GROUP BY st.sector limit 2";



            } else if ($menuResult['id'] == '6') {
                $interviewData = "SELECT s.id," . $menuResult['id'] . " as productId,st.sector as sectorId,pr.interviewName as `name`,'All Stream' as targetAudience,'25-30 min' as duration,9 as categoryType,'Medium' as interviewLevel,st.preInterviewId as preInterviewId FROM `scps_transaction` st INNER JOIN sector s ON st.sector = s.id INNER JOIN preInterview pr on pr.id=st.preInterviewId where pr.productId=6 and pr.interviewStatus in ('Active') and (pr.interviewExpireDate>=now() or pr.interviewExpireDate is null) GROUP BY st.preInterviewId order by st.preInterviewId DESC";
            } else {
                $interviewData = "select i.id," . $menuResult['id'] . " as productId,i.name,i.role,i.duration,i.interviewLevel,i.categoryType,i.targetAudience, m.id as menu_id, fs.favourite_subject as subject_name from `interview` i left outer join favourite_subject fs on i.subject_id = fs.id left outer join menu_subject_transection mst on fs.id = mst.subject_id left outer join menu m on mst.menu_id = m.id where i.deleted_at is null  and i.isActive='Y' and i.categoryType in (1,2,6,7,8) and m.id = '" . $menuResult['id'] . "' order by i.categoryType desc,i.name";
            }
            // if( $menuResult['id'] == '1') {
            //     $interviewQuery = mysqli_query($databaseConnection, $interviewData);
            // }else{
            $interviewQuery = mysqli_query($databaseConnection, $interviewData . ' limit 4');
            // }


            $count_query = mysqli_query($databaseConnection, $interviewData);
            $count_result = mysqli_num_rows($count_query);

            $uniqueCountQuery = "select count(distinct i.id) as productProgress,p.id as productId from mergedVideos m inner join interview i on m.interviewId =i.id inner join product p on i.productId = p.id where m.candidateId='" . $candidateId . "' AND i.productId='" . $menuResult['id'] . "' and m.interviewSessionId is not null";
            $uniqueCountQueryResult = mysqli_query($databaseConnection, $uniqueCountQuery);
            if (mysqli_num_rows($uniqueCountQueryResult) >= 1) {
                $uniqueCountQueryValue = mysqli_fetch_array($uniqueCountQueryResult, MYSQLI_ASSOC);
                $attempted = $uniqueCountQueryValue['productProgress'];
            } else {
                $attempted = "0";
            }

            if (mysqli_num_rows($interviewQuery) >= 1) {
                while ($interviewValues = mysqli_fetch_array($interviewQuery, MYSQLI_ASSOC)) {

                    /*$totalAttendedInterviewData = "SELECT COUNT(DISTINCT interviewSessionId) AS totalAttendedInterview FROM mergedVideos WHERE interviewSessionId IS NOT NULL AND interviewId = '".$interviewValues['id']."';";
                    $totalAttendedInterviewQuery = mysqli_query($databaseConnection, $totalAttendedInterviewData);
                    $totalAttendedInterviewValues = mysqli_fetch_all($totalAttendedInterviewQuery, MYSQLI_ASSOC);
                    $interviewValues['totalAttendedInterview'] = $totalAttendedInterviewValues[0]['totalAttendedInterview'];*/

                    if ($interviewValues['categoryType'] == 2 || $interviewValues['categoryType'] == 3) {
                        $sql = "select e.* from event e where e.interviewId = '" . $interviewValues['id'] . "';";
                        $query = mysqli_query($databaseConnection, $sql);
                        $result = mysqli_fetch_assoc($query);

                        $checkRegistration = "select if((select count(*) from event_registration where userId = '" . $candidateId . "' and eventId = '" . $result['id'] . "' and categoryType =  '" . $interviewValues['categoryType'] . "')=1, 'Y', 'N') as registered;";
                        $checkRegistrationQuery = mysqli_query($databaseConnection, $checkRegistration);
                        if (mysqli_num_rows($checkRegistrationQuery) >= 1) {
                            $checkRegistrationValues = mysqli_fetch_all($checkRegistrationQuery, MYSQLI_ASSOC);
                            $interviewValues['startTime'] = $result['startTime'];
                            $interviewValues['endTime'] = $result['endTime'];
                            $interviewValues['registered'] = $checkRegistrationValues[0]['registered'];
                            $interviewValues['eventId'] = $result['id'];
                        }
                    } else {
                        $interviewValues['startTime'] = NULL;
                        $interviewValues['endTime'] = NULL;
                        $interviewValues['registered'] = NULL;
                        $interviewValues['eventId'] = NULL;
                    }
                    array_push($interviews, $interviewValues);
                    // sortBySubkey($interviews, 'totalAttendedInterview', SORT_DESC);
                }
                //$filterInterviews = unique_multidim_array($interviews,'id');
            } else {
                $interviews = array(
                    'result' => "info",
                    'status' => 0,
                    'errorCode' => "No courses avaialble."
                );
            }
            $menuInterviewData = array(
                'menu_id' => $menuResult['id'],
                'menuName' => $menuResult['name'] == 'Company Mock Interviews' ? 'Events/Jobs' : $menuResult['name'],
                'totalInterviewAvailable' => $count_result,
                'show' => $menuResult['id'] == '1' || /*$menuResult['id'] == '2' || */ $menuResult['id'] == '3' || $menuResult['id'] == '4' || $menuResult['id'] == '5' || $menuResult['id'] == '6' ? true : false, //show tabs after login
                'interviews' => $interviews,
                'attempted' => $attempted
            );
            array_push($menuInterviews, $menuInterviewData);
            unset($interviews);
            $interviews = array();
        }
        $to_encode = $menuInterviews;
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "Error whire retrieving interview information."
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['getSuggestedInterviewList'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        if ($json['typeInterview'] != "") {
            $interview = $json['typeInterview'];

            $data = "select id as interviewId,name as interviewName from `interview` where deleted_at is null and isActive ='Y' and name like '%" . addslashes($interview) . "%' limit 0, 20";
            $query = mysqli_query($databaseConnection, $data);
            if (mysqli_num_rows($query) >= 1) {
                $values = mysqli_fetch_all($query, MYSQLI_ASSOC);
                $to_encode = $values;
            } else {
                $to_encode = array(
                    'status' => 0,
                    'result' => "no info",
                    'errorCode' => "no interview info found",
                    'query' => $data
                );
            }
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "no info",
                'errorCode' => "No Key Press yet",
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving interview information."
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['gettopTrendingInterviews'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['candidateId'];
        $values = array();
        $interviews = array();
        $interviewValues = array();
        $panelValues = array();

        $interviewData = "select i.id,i.name,i.role,i.categoryType,i.duration,i.interviewLevel,i.targetAudience,i.productId, count(distinct fr.interviewSessionId) as totalAttendedInterview from `interview` i inner join feedback_request fr on fr.interviewId = i.id where i.productId != 1 AND i.deleted_at is null and i.isActive='Y' and i.categoryType in (1,2,6,7,8) group by fr.interviewId having totalAttendedInterview > 60";

        $interviewQuery = mysqli_query($databaseConnection, $interviewData);
        if (mysqli_num_rows($interviewQuery) >= 1) {
            while ($interviewValues = mysqli_fetch_array($interviewQuery, MYSQLI_ASSOC)) {

                if ($interviewValues['categoryType'] == 2 || $interviewValues['categoryType'] == 3) {
                    $sql = "select e.* from event e where e.interviewId = '" . $interviewValues['id'] . "';";
                    $query = mysqli_query($databaseConnection, $sql);
                    $result = mysqli_fetch_assoc($query);

                    $checkRegistration = "select if((select count(*) from event_registration where userId = '" . $candidateId . "' and eventId = '" . $result['id'] . "' and categoryType =  '" . $interviewValues['categoryType'] . "')=1, 'Y', 'N') as registered;";
                    $checkRegistrationQuery = mysqli_query($databaseConnection, $checkRegistration);
                    if (mysqli_num_rows($checkRegistrationQuery) >= 1) {
                        $checkRegistrationValues = mysqli_fetch_all($checkRegistrationQuery, MYSQLI_ASSOC);
                        $interviewValues['startTime'] = $result['startTime'];
                        $interviewValues['endTime'] = $result['endTime'];
                        $interviewValues['registered'] = $checkRegistrationValues[0]['registered'];
                        $interviewValues['eventId'] = $result['id'];
                    }
                } else {
                    $interviewValues['startTime'] = NULL;
                    $interviewValues['endTime'] = NULL;
                    $interviewValues['registered'] = NULL;
                    $interviewValues['eventId'] = NULL;
                }
                array_push($interviews, $interviewValues);
            }
            //$filterInterviews = unique_multidim_array($interviews,'id');
            $to_encode = $interviews;
        } else {
            $to_encode = array(
                'result' => "info",
                'status' => 0,
                'errorCode' => "No courses avaialble."
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "Error whire retrieving interview information."
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['registrationForEvent'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        //$interviewId = $json['interviewId'];
        $categoryType = $json['categoryType'];
        $eventId = $json['eventId'];

        if ($eventId == NULL) {
            $to_encode = array(
                'result' => "error",
                'errorCode' => "Registration failed.",
                'status' => 0
            );
        } else {
            $sql = "INSERT INTO `event_registration` (`userId`, `categoryType`, `eventId`, `registeredAt`) values ('$userId', '$categoryType', '$eventId', ROUND(UNIX_TIMESTAMP()*1000));";
            $sqlQuery = mysqli_query($databaseConnection, $sql);
            if ($sqlQuery) {
                $id = mysqli_insert_id($databaseConnection);
                $to_encode = array(
                    'result' => "Success",
                    'message' => "Registered successfully.",
                    'status' => 1,
                    'event_registration_id' => $id
                );
            } else {
                $to_encode = array(
                    'result' => "error",
                    'errorCode' => "Registration failed.",
                    'status' => 0,
                    'query' => $sqlQuery
                );
            }
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "Error whire registering student information."
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['getPanels'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $panelDetails = array();
        $panelValues = array();
        $values = array();
        $companyData = "select * from company where id = '0'";
        $companyQuery = mysqli_query($databaseConnection, $companyData);
        $companyDetails = mysqli_fetch_assoc($companyQuery);
        $panelData = "select * from panel where deleted_at is null AND companyId = '0'";
        $panelQuery = mysqli_query($databaseConnection, $panelData);
        if (mysqli_num_rows($panelQuery) >= 1) {

            while ($panelValues = $panelQuery->fetch_assoc()) {
                $interviewData = "select * from `interview` where panelId='" . $panelValues['id'] . "' and deleted_at is null  and isActive='Y'";
                $interviewQuery = mysqli_query($databaseConnection, $interviewData);
                if (mysqli_num_rows($interviewQuery) >= 1) {
                    $interviewValues = mysqli_fetch_all($interviewQuery, MYSQLI_ASSOC);
                    $panelValues['courses'] = $interviewValues;
                    array_push($panelDetails, $panelValues);
                } else {
                    $to_encode = array(
                        'result' => "info",
                        'status' => 0,
                        'errorCode' => "No courses avaialble."
                    );
                }
            }
            $values['panelData'] = $panelDetails;
            $values['companyDetails'] = $companyDetails['description'];
            $to_encode = $values;
        } else {
            $to_encode = array(
                'result' => "info",
                'status' => 0,
                'errorCode' => "No panel information found."
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "Error whire retrieving panel information."
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['getCompetitionInterviews'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['candidateId'];
        $values = array();
        $interviews = array();
        $interviewValues = array();
        $panelValues = array();

        $interviewData = "SELECT i.*,e.id as eventId,e.categoryType as eCategoryType,startTime,endTime FROM event e inner join interview i on e.interviewId = i.id and i.deleted_at is null and isActive='Y' and e.deleted_at is null and e.categoryType = 2 order by startTime;";
        //below query to show competions for upcoming 30 days
        //$interviewData = "SELECT i.*,e.id as eventId,e.categoryType as eCategoryType,startTime,endTime FROM event e inner join interview i on e.interviewId = i.id and i.deleted_at is null and isActive='Y' and e.deleted_at is null and e.categoryType = 2 and startTime < NOW() + INTERVAL 30 DAY order by startTime";
        //above query to show competions for upcoming 30 days
        $interviewQuery = mysqli_query($databaseConnection, $interviewData);
        if (mysqli_num_rows($interviewQuery) >= 1) {
            while ($interviewValues = mysqli_fetch_array($interviewQuery, MYSQLI_ASSOC)) {

                $checkRegistration = "select if((select count(*) from event_registration where userId = '" . $candidateId . "' and eventId = '" . $interviewValues['eventId'] . "' and categoryType =  '" . $interviewValues['eCategoryType'] . "')=1, 'Y', 'N') as registered;";
                $checkRegistrationQuery = mysqli_query($databaseConnection, $checkRegistration);
                if (mysqli_num_rows($checkRegistrationQuery) >= 1) {
                    $checkRegistrationValues = mysqli_fetch_all($checkRegistrationQuery, MYSQLI_ASSOC);
                    $interviewValues['registered'] = $checkRegistrationValues[0]['registered'];
                }
                array_push($interviews, $interviewValues);
            }
            $to_encode = $interviews;
        } else {
            $to_encode = array(
                'result' => "info",
                'status' => 0,
                'errorCode' => "No courses avaialble."
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "Error whire retrieving interview information."
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['getCompanyPanels'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $companyId = $json['companyId'];
        $panelDetails = array();
        $panelValues = array();
        $values = array();
        $companyData = "select * from company where id = '" . $companyId . "'";
        $companyQuery = mysqli_query($databaseConnection, $companyData);
        $companyDetails = mysqli_fetch_assoc($companyQuery);
        $panelData = "select * from panel where deleted_at is null AND companyId = '" . $companyId . "'";
        $panelQuery = mysqli_query($databaseConnection, $panelData);
        if (mysqli_num_rows($panelQuery) >= 1) {

            while ($panelValues = $panelQuery->fetch_assoc()) {
                $interviewData = "select * from `interview` where panelId='" . $panelValues['id'] . "' and deleted_at is null  and isActive='Y'";
                $interviewQuery = mysqli_query($databaseConnection, $interviewData);
                if (mysqli_num_rows($interviewQuery) >= 1) {
                    $interviewValues = mysqli_fetch_all($interviewQuery, MYSQLI_ASSOC);
                    $panelValues['courses'] = $interviewValues;
                    array_push($panelDetails, $panelValues);
                } else {
                    $to_encode = array(
                        'result' => "info",
                        'status' => 0,
                        'errorCode' => "No courses avaialble."
                    );
                }
            }
            $values['panelData'] = $panelDetails;
            $values['companyDetails'] = $companyDetails['description'];
            $to_encode = $values;
        } else {
            $to_encode = array(
                'result' => "info",
                'status' => 0,
                'errorCode' => "No panel information found."
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "Error whire retrieving panel information."
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['getPeerResponse'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $isPeerResponse = $json['isPeerResponse'];
        $data = "SELECT m.candidateId, m.interviewId, i.name, i.targetAudience, m.youtubeId, m.interviewSessionId, pr.peerHeading, pr.name as peerName FROM mergedVideos m inner join interview i on m.interviewId = i.id inner join peer_response pr on m.mergeId = pr.mergeId";
        $query = mysqli_query($databaseConnection, $data);
        if (mysqli_num_rows($query) >= 1) {
            $values = array();
            while ($row = $query->fetch_assoc()) {
                $getStudentDetails = "SELECT `qualification`, `specialization`, c.collegeName as `college` FROM `professionaldetails` p inner join `colleges` c on p.college = c.id and `candidateId` = '" . $row['candidateId'] . "'";
                $studentDataQuery = mysqli_query($databaseConnection, $getStudentDetails);
                if (mysqli_num_rows($studentDataQuery) >= 1) {
                    $studentDataValues = mysqli_fetch_assoc($studentDataQuery);
                    $row['qualification'] = $studentDataValues['qualification'];
                    $row['specialization'] = $studentDataValues['specialization'];
                    $row['college'] = $studentDataValues['college'];
                    $row['url'] = "/peer?i=" . $row['interviewId'] . "&c=" . $row['candidateId'] . "&s=" . $row['interviewSessionId'] . "&q=" . $row['youtubeId'];
                    $values[] = $row;
                } else {
                    $to_encode = array(
                        'result' => "info",
                        'status' => 0,
                        'errorCode' => "No details avaialble."
                    );
                }
            }
            $to_encode = $values;
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "success",
                'message' => "No Peer Response avaialble"
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "Error whire retrieving Peer Response information."
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['createPanel'])) {
    //$data = @file_get_contents("php://input");
    //$json = json_decode($data, true);
    //if (isset($json)) {
    /*$name = $json['name'];
        $qualification = $json['qualification'];
        $oraganisation = $json['oraganisation'];
        $experience = $json['experience'];
        $companiesWorked = $json['companiesWorked'];
        $linkedinProfile = $json['linkedinProfile'];
        $specilization = $json['specilization'];
        $emailId = $json['emailId'];
        $phonenumber = $json['phonenumber'];
        $panelTitle = $json['panelTitle'];
        $panelDescription = $json['panelDescription'];*/
    $name = $_POST['name'];
    $qualification = $_POST['qualification'];
    $oraganisation = $_POST['oraganisation'];
    $experience = $_POST['experience'];
    $companiesWorked = $_POST['companiesWorkedFor'];
    $linkedinProfile = $_POST['linkedinProfile'];
    $specilization = $_POST['specilization'];
    $emailId = $_POST['emailId'];
    $phonenumber = $_POST['phonenumber'];
    $feedbackRatePerQuestion = $_POST['feedbackRatePerQuestion'];
    $panelDescription = $_POST['panelDescription'];
    $query = "INSERT INTO `panel` (`name`, `qualification`, `oraganisation`, `experience`, `specilization`, `emailId`, `phonenumber`, `panelTitle`, `panelDescription`, `companiesWorked`, `linkedinProfile`, `feedbackRatePerQuestion`) VALUES ('$name', '$qualification', '$oraganisation', '$experience', '$specilization', '$emailId', '$phonenumber', '$name', '$panelDescription', '$companiesWorked', '$linkedinProfile', '$feedbackRatePerQuestion');";
    $usersQuery = mysqli_query($databaseConnection, $query);
    if ($usersQuery) {
        $userId = mysqli_insert_id($databaseConnection);

        $filename = 'panel_' . $userId; //panel_id
        $extension = pathinfo($_FILES["picture"]["name"], PATHINFO_EXTENSION); //png
        $basename = $filename . '.' . $extension;
        $file_tmp = $_FILES['picture']['tmp_name'];
        move_uploaded_file($file_tmp, "../pracschool_app/public/images/" . $basename);
        $to_encode = array(
            'result' => "Success",
            'message' => "panel Created.",
            'status' => 1
        );
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "panel Creation failed.",
            'status' => 0,
            'query' => $query
        );
    }
    /*} else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Panel Creation failed.",
            'status' => 0
        );
    }*/

    echo json_encode($to_encode);
} elseif (isset($_GET['saveSkipQuestion'])) {
    // sourabh 25/12/2023 - modified so that feedback_request entry gets created on skip also
    /* this method is added by Narayan to save skip question in April */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {

        $interviewId = $json['interviewId'];
        $questionId = $json['questionId'];
        $candidateId = $json['candidateId'];
        $interviewSessionId = $json['interviewSessionId'];

        $questionAttemptStatus = $json['questionAttemptStatus'];

        $attemptStatus = 'Skip';

        if ($questionAttemptStatus == 'original') {
            $attemptStatus = 'Idk';
        } else if ($questionAttemptStatus == 'idk1') {
            $attemptStatus = 'Idk1';
        } else if ($questionAttemptStatus == 'idk2') {
            $attemptStatus = 'Idk2';
        }

        $query = "UPDATE interview_questions_transection set attemptStatus = '" . $attemptStatus . "' where interviewId = '" . $interviewId . "' and questionId = '" . $questionId . "' ";
        $UpdateResult = mysqli_query($databaseConnection, $query);
        if ($UpdateResult) {
            $to_encode = array(
                'result' => "Success",
                'message' => "Skip Question Saved.",
                'status' => 1
            );

            $CheckQuery = mysqli_query($databaseConnection, "Select id from feedback_request where interviewId = '" . $interviewId . "' and candidateId = '" . $candidateId . "' and interviewId = '" . $interviewId . "';");
            if (mysqli_num_rows($CheckQuery) == 0) {
                $suggestion = "Expert will not be able to provide you proper feedback, if you dont complete the interview. In case you find any question difficult, you can tell that you dont know the answer and it will be great if you tell them asto why you dont know the answer. It is advised to quickly revise the concept before giving interview. To revise the concept, pls view the tutorial video. Link of tutorial video : https://goprac.com/interviewDetails?id=" . $interviewId;

                //$insertRequestQuery = "INSERT INTO `feedback_request` (`candidateId`,`interviewId`,`interviewSessionId`,`requestDate`,`review_status`,`createdBy`,`rejectedBy`, `reasonOfRejection`,`suggestion`) VALUES('$candidateId','$interviewId','$interviewSessionId',NOW(),-4,4,4,'incompleteInterview','". addslashes($suggestion)."')";
                //Shrikant commented : 5/3/2024
                $insertRequestQuery = "INSERT INTO `feedback_request` (`candidateId`,`interviewId`,`interviewSessionId`,`requestDate`,`review_status`,`createdBy`,`rejectedBy`, `reasonOfRejection`) VALUES('$candidateId','$interviewId','$interviewSessionId',NOW(),-4,4,4,'incompleteInterview')";

                // $insertRequestQuery = "INSERT INTO `feedback_request` (`candidateId`,`interviewId`,`requestDate`,`review_status`,`createdBy`,`rejectedBy`, `reasonOfRejection`,`suggestion`) VALUES('$candidateId','$interviewId',NOW(),-4,4,4,'incompleteInterview','". addslashes($suggestion)."')";

                $feedback_requestResult = mysqli_query($databaseConnection, $insertRequestQuery);
                $feedback_requestId = mysqli_insert_id($databaseConnection);
                array_push($to_encode, $feedback_requestId);

            }

        } else {
            $to_encode = array(
                'result' => "error",
                'errorCode' => "Skip Question save failed.",
                'status' => 0,
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Skip Question failed.",
            'status' => -1
        );
    }
    echo json_encode($to_encode);

} elseif (isset($_GET['saveSkipQuestionExpertReview'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {

        $interviewId = $json['interviewId'];
        $questionId = $json['questionId'];
        $candidateId = $json['candidateId'];

        $feedbackRequestId = mysqli_query($databaseConnection, "Select id from feedback_request where candidateId = '" . $candidateId . "' and interviewId = '" . $interviewId . "';");
        $feedbackRequestIdResult = mysqli_fetch_assoc($feedbackRequestId)['id'];

        foreach ($questionId as $qId) {
            $query = "INSERT INTO expert_review(interviewId,candidateId,questionId,review_type,overallRating,questionTag,feedback_request_id) VALUES ($interviewId,$candidateId,$qId,'question',0,'skipped',$feedbackRequestIdResult)";
            $UpdateResult = mysqli_query($databaseConnection, $query);
            $expertReviewId = mysqli_insert_id($databaseConnection);

            $skillQuery = mysqli_query($databaseConnection, "SELECT key_skill_id from questions where id in (" . $qId . ")");
            if (mysqli_num_rows($skillQuery) > 0) {
                $key_skill_id = mysqli_fetch_assoc($skillQuery)['key_skill_id'];

                $observation_area = mysqli_query($databaseConnection, "SELECT id FROM observation_area where key_skill in (" . $key_skill_id . ") and observation_type is null");

                while ($values = mysqli_fetch_assoc($observation_area)) {

                    $query1 = mysqli_query($databaseConnection, "INSERT INTO expert_review_observation_details(expertReviewId,observationAreaId,observationValueId,questionId) VALUES ($expertReviewId," . $values['id'] . ",580,$qId)");

                }
            }
        }
        if ($UpdateResult) {


            $to_encode = array(
                'result' => "Success",
                'message' => "Skip Question Saved.",
                'status' => 1
            );
        } else {
            $to_encode = array(
                'result' => "error",
                'errorCode' => "Skip Question save failed.",
                'status' => 0,
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Skip Question failed.",
            'status' => -1
        );
    }
    echo json_encode($to_encode);

} elseif (isset($_GET['saveLastQuestionResponded'])) {
    /* this method is added by Narayan to save Last QuestionAttempted or skip by User in April */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {

        $interviewId = $json['interviewId'];
        $candidateId = $json['candidateId'];
        $interviewSessionId = $json['interviewSessionId'];

        $query = "
        INSERT INTO `candidate_interview_transection`(`candidateId`, `interviewId`, `interviewSessionId`, `completion_status`, `totalRespond`, `totalSkip`, `totalQuestion`) SELECT m.candidateId,m.interviewId,m.interviewSessionId,CASE WHEN i.categoryType = 9  AND  count(m.interviewSessionId)  >= 1 THEN 1 WHEN
         i.categoryType != 9 and
        ((SELECT COUNT(iqt.questionId) FROM interview_questions_transection iqt inner join questions qs on qs.id = iqt.questionId WHERE iqt.interviewId=m.interviewId and qs.deleted_at is null and iqt.deleted_at is null and iqt.deleted_at is null) -1) =  count(m.interviewSessionId) THEN 1 ELSE 0 END as Status ,
        CASE WHEN i.categoryType = 9 THEN  (SELECT COUNT( CASE WHEN iqt.attemptStatus ='Respond' THEN iqt.questionId ELSE NULL END) FROM interview_questions_transection iqt inner join questions qs on qs.id = iqt.questionId WHERE iqt.interviewId=m.interviewId and qs.deleted_at is null  and iqt.deleted_at is null) ELSE count(m.interviewSessionId) END as Respond,
        CASE WHEN i.categoryType = 9 THEN  (SELECT COUNT( CASE WHEN iqt.attemptStatus ='Skip' THEN iqt.questionId ELSE NULL END) FROM interview_questions_transection iqt inner join questions qs on qs.id = iqt.questionId WHERE iqt.interviewId=m.interviewId and qs.deleted_at is null  and iqt.deleted_at is null) ELSE 0 END as Skip, CASE WHEN i.categoryType = 9 THEN  (SELECT COUNT( CASE WHEN iqt.attemptStatus is not null THEN iqt.questionId ELSE NULL END) FROM interview_questions_transection iqt inner join questions qs on qs.id = iqt.questionId WHERE iqt.interviewId=m.interviewId and qs.deleted_at is null  and iqt.deleted_at is null) ELSE (SELECT COUNT(iqt.questionId) FROM interview_questions_transection iqt inner join questions qs on qs.id = iqt.questionId WHERE iqt.interviewId=m.interviewId and qs.deleted_at is null and iqt.deleted_at is null and iqt.deleted_at is null) -1 END as TotalQuestion From mergedVideos m left outer join interview i  on m.interviewId = i.id  where m.interviewSessionId = '" . $interviewSessionId . "' and m.candidateId = '" . $candidateId . "' and m.interviewId = '" . $interviewId . "' group by m.interviewSessionId,m.interviewId,m.candidateId order by mergeId;";
        $InsertResult = mysqli_query($databaseConnection, $query);
        if ($InsertResult) {
            $to_encode = array(
                'result' => "Success",
                'message' => "Last Respond Question Saved.",
                'status' => 1
            );
        } else {

            $query = "INSERT INTO `candidate_interview_transection`(`candidateId`, `interviewId`, `interviewSessionId`, `completion_status`, `totalRespond`, `totalSkip`, `totalQuestion`) SELECT '" . $candidateId . "' as candidateId ,'" . $interviewId . "' as interviewId ,   '" . $interviewSessionId . "' as interviewSessionId ,'0' as Status, '0' as Respond,CASE WHEN i.categoryType = 9 THEN  (SELECT COUNT( CASE WHEN iqt.attemptStatus ='Skip' THEN iqt.questionId ELSE NULL END) FROM interview_questions_transection iqt inner join questions qs on qs.id = iqt.questionId WHERE iqt.interviewId= '" . $interviewId . "'  and qs.deleted_at is null  and iqt.deleted_at is null) ELSE 0 END as Skip, CASE WHEN i.categoryType = 9 THEN  (SELECT COUNT( CASE WHEN iqt.attemptStatus is not null THEN iqt.questionId ELSE NULL END) FROM interview_questions_transection iqt inner join questions qs on qs.id = iqt.questionId WHERE iqt.interviewId='" . $interviewId . "' and qs.deleted_at is null  and iqt.deleted_at is null) ELSE (SELECT COUNT(iqt.questionId) FROM interview_questions_transection iqt inner join questions qs on qs.id = iqt.questionId WHERE iqt.interviewId=m.interviewId and qs.deleted_at is null and iqt.deleted_at is null and iqt.deleted_at is null) -1 END as TotalQuestion From interview i where  i.id = '" . $interviewId . "'";
            $InsertResult = mysqli_query($databaseConnection, $query);

            $suggestion = "Expert will not be able to provide you proper feedback, if you dont complete the interview. In case you find any question difficult, you can tell that you dont know the answer and it will be great if you tell them asto why you dont know the answer. It is advised to quickly revise the concept before giving interview. To revise the concept, pls view the tutorial video. Link of tutorial video : https://goprac.com/interviewDetails?id=" . $interviewId;
            //Shrikant changed : 5/3/2024
            // $updatequery4 = "UPDATE feedback_request set review_status = '-4' , createdBy ='".$candidateId."' , rejectedBy ='4'  ,  ReasonOfRejection ='incompleteInterview',suggestion = '". addslashes($suggestion)."'  where  interviewSessionId ='".$interviewSessionId."'  and interviewId ='".$interviewId."' and candidateId = '".$candidateId."' ";
            $updatequery4 = "UPDATE feedback_request set review_status = '-4' , createdBy ='" . $candidateId . "' , rejectedBy ='4'  ,  ReasonOfRejection ='incompleteInterview' where  interviewSessionId ='" . $interviewSessionId . "'  and interviewId ='" . $interviewId . "' and candidateId = '" . $candidateId . "' ";

            $Update4Result = mysqli_query($databaseConnection, $updatequery4);

            $to_encode = array(
                'result' => "error",
                'errorCode' => "Last Respond Question Save failed.",
                'status' => 0,
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Respond Question failed.",
            'status' => -1
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['saveRespondQuestion'])) {
    /* this method is added by Narayan to save Respond question in April */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {

        $interviewId = $json['interviewId'];
        $questionId = $json['questionId'];

        $query = "UPDATE interview_questions_transection set attemptStatus = 'Respond' where interviewId = '" . $interviewId . "' and questionId = '" . $questionId . "' ";
        $UpdateResult = mysqli_query($databaseConnection, $query);
        if ($UpdateResult) {


            $to_encode = array(
                'result' => "Success",
                'message' => "Respond Question Saved.",
                'status' => 1
            );
        } else {
            $to_encode = array(
                'result' => "error",
                'errorCode' => "Respond Question save failed.",
                'status' => 0,
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Respond Question failed.",
            'status' => -1
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['saveWhiteboard'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['candidateId'];
        $interviewId = $json['interviewId'];
        $preInterviewId = $json['preInterviewId'];
        $questionId = $json['questionId'];
        // $questionVideoId = $json['questionVideoId'];
        $information = $json['information'];
        $streamId = $json['streamId'];
        $cropTime = $json['cropTime'];
        $publishStartTime = $json['publishStartTime'];
        $whiteboardStartTime = $json['whiteboardStartTime']; // by rp
        $interviewSessionId = $json['interviewSessionId'];
        $videoLength = $json['videoLength'];
        $totalTime = $json['totalTime'];
        $saidWords = $json['saidwords'];
        $questionVersion = $json['questionVersion'];

        $attemptStatus = 'Respond';

        if ($questionVersion == 'idk1') {
            $attemptStatus = 'Respond1';
        } else if ($questionVersion == 'idk2') {
            $attemptStatus = 'Respond2';
        }

        $query = "INSERT INTO `whiteboard` (`candidateId`, `interviewId`, `questionId`,`questionVideoId`,`streamId`,`cropTime`, `publishStartTime`, `interviewSessionId`, `whiteboardStartTime`) VALUES ('$candidateId', '$interviewId', '$questionId',(select youtubeId from questions where id=" . $questionId . "),'$streamId','$cropTime','$publishStartTime','$interviewSessionId', '$whiteboardStartTime');";

        if ($server == 'live') {
            error_log($query . "\n", 3, "../../../home/ubuntu/interviewInfo.log");
        }

        $whiteBoardQuery = mysqli_query($databaseConnection, $query);
        if ($whiteBoardQuery) {
            $whiteBoardId = mysqli_insert_id($databaseConnection);

            end($information[0]);
            $key = key($information[0]);
            $val = str_replace("'", "''", $information[0][$key]);
            $val = $information[0][$key];
            $whiteboardDetailsQuery = "INSERT INTO whiteboard_details (`whiteBoardId`, `time`, `text`) VALUES ('$whiteBoardId','$key','" . addslashes($val) . "');";
            mysqli_query($databaseConnection, $whiteboardDetailsQuery);

            $to_encode = array(
                'result' => "Success",
                'message' => "Whiteboard Saved.",
                'status' => 1
            );

            flush();
            sleep(1);
            error_log("StreamId Before API Calling : " . $streamId, 0);

            $answerSubmitQuery = "INSERT INTO `mergedVideos` (`mergeId`, `created`, `mergeStatus`, `outputVideoURL`, `uploadStatus`, `youtubeId`, `candidateId`, `interviewId`, `questionId`, `questionVideoId`, `interviewSessionId`, `vidLength`, `totalTime`) VALUES (NULL, NOW(), NULL, '$streamId', 'open', NULL, '$candidateId', '$interviewId', '$questionId', (select youtubeId from questions where id=" . $questionId . "), '$interviewSessionId', '$videoLength', '$totalTime');";


            if ($server == 'live') {
                error_log($answerSubmitQuery . "\n", 3, "../../../home/ubuntu/interviewInfo.log");
            }

            mysqli_query($databaseConnection, $answerSubmitQuery);
            $mergeId = mysqli_insert_id($databaseConnection);

            $query = "UPDATE interview_questions_transection set attemptStatus = '" . $attemptStatus . "' where interviewId = '" . $interviewId . "' and questionId = '" . $questionId . "' ";
            $UpdateResult = mysqli_query($databaseConnection, $query);
            /* this Added by Narayan in April for Requesting Feedback at the submit of First Question  and default staus will be rejected*/

            $CheckQuery = mysqli_query($databaseConnection, "Select id from feedback_request where interviewSessionId = '" . $interviewSessionId . "' and candidateId = '" . $candidateId . "' and interviewId = '" . $interviewId . "';");
            if (mysqli_num_rows($CheckQuery) == 0) {
                $suggestion = "Expert will not be able to provide you proper feedback, if you dont complete the interview. In case you find any question difficult, you can tell that you dont know the answer and it will be great if you tell them asto why you dont know the answer. It is advised to quickly revise the concept before giving interview. To revise the concept, pls view the tutorial video. Link of tutorial video : https://goprac.com/interviewDetails?id=" . $interviewId;
                //Shrikant changed : 5/3/2024
                // $insertRequestQuery = "INSERT INTO `feedback_request` (`candidateId`,`interviewId`,`interviewSessionId`,`requestDate`,`review_status`,`createdBy`,`rejectedBy`, `reasonOfRejection`,`suggestion`) VALUES('$candidateId','$interviewId','$interviewSessionId',NOW(),-4,4,4,'incompleteInterview','". addslashes($suggestion)."')";
                $insertRequestQuery = "INSERT INTO `feedback_request` (`candidateId`,`interviewId`,`interviewSessionId`,`requestDate`,`review_status`,`createdBy`,`rejectedBy`, `reasonOfRejection`,`preInterviewId`) VALUES('$candidateId','$interviewId','$interviewSessionId',NOW(),-4,4,4,'incompleteInterview','$preInterviewId')";

                $feedback_requestResult = mysqli_query($databaseConnection, $insertRequestQuery);
                $feedback_requestId = mysqli_insert_id($databaseConnection);
                array_push($to_encode, $feedback_requestId);
            }

            $vidWatchQry = mysqli_query($databaseConnection, "INSERT INTO `video_watched_details`(`mergeId`, `saidWords`) VALUES ('$mergeId', NULLIF('" . addslashes(trim($saidWords)) . "', ''))");
        } else {
            $to_encode = array(
                'result' => "error",
                'errorCode' => "Whiteboard save failed.",
                'status' => 0,
                'query' => $query
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Panel Creation failed.",
            'status' => -1
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getWhiteboard'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['candidateId'];
        $interviewId = $json['interviewId'];
        $questionId = $json['questionId'];
        $data = "select * from `whiteboard` where candidateId='" . $candidateId . "' and interviewId='" . $interviewId . "' and questionId='" . $questionId . "'";
        $query = mysqli_query($databaseConnection, $data);
        if (mysqli_num_rows($query) >= 1) {
            $values = mysqli_fetch_all($query, MYSQLI_ASSOC);
            $to_encode = $values;
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "noinfo",
                'errorCode' => "no whiteboard info found",
                'query' => $data
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error whire retrieving whiteboard information."
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['getSuggestedEmailId'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $emailId = $json['emailId'];

        $data = "select emailId from `users` where emailId like '%" . addslashes($emailId) . "%' limit 5";
        $query = mysqli_query($databaseConnection, $data);
        if (mysqli_num_rows($query) >= 1) {
            $values = mysqli_fetch_all($query, MYSQLI_ASSOC);
            $to_encode = $values;
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "noinfo",
                'errorCode' => "no users info found",
                'query' => $data
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving user information."
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getAllParentChildQuestion'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $questionId = $json['questionId'];
        $questionType = $json['questionType'];

        if ($questionType == 'Parent') {
            $query = "SELECT id, youtubeId,subjectId, questionText, isFollowUp, answerDuration,key_skill_id,questionLevel FROM questions  WHERE id = '" . $questionId . "' UNION SELECT id, youtubeId,subjectId,questionText, isFollowUp, answerDuration,key_skill_id,questionLevel FROM questions WHERE id in (SELECT lv FROM (SELECT @pv:=(SELECT GROUP_CONCAT(id SEPARATOR ',') FROM questions WHERE isFollowUp IN (@pv)) AS lv FROM questions JOIN (SELECT @pv:='" . $questionId . "')tmp WHERE isFollowUp IN (@pv)) a) ORDER BY isFollowUp <> 'Y', isFollowUp;";
        } else {
            $query = "SELECT T2.id, T2.youtubeId,T2.subjectId, T2.questionText, T2.isFollowUp, T2.answerDuration,T2.key_skill_id,T2.questionLevel FROM ( SELECT @r AS _id, (SELECT @r := isFollowUp FROM questions WHERE id = _id) AS isFollowUp, @l := @l + 1 AS lvl FROM (SELECT @r := '" . $questionId . "', @l := 'Y') vars, questions h WHERE @r <> 'Y') T1 JOIN questions T2 ON T1._id = T2.id UNION SELECT id, youtubeId,subjectId,questionText, isFollowUp, answerDuration,key_skill_id,questionLevel FROM questions WHERE id in (SELECT lv FROM (SELECT @pv:=(SELECT GROUP_CONCAT(id SEPARATOR ',') FROM questions WHERE isFollowUp IN (@pv)) AS lv FROM questions JOIN (SELECT @pv:='" . $questionId . "')tmp WHERE isFollowUp IN (@pv)) a) ORDER BY isFollowUp <> 'Y', isFollowUp;";
        }

        $result = mysqli_query($databaseConnection, $query);
        if (mysqli_num_rows($result) >= 1) {
            $values = mysqli_fetch_all($result, MYSQLI_ASSOC);
            $to_encode = $values;
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "noinfo",
                'errorCode' => "in Error while retrieving data.",
                'query' => $query
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving data."
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getAllParentQuestion'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $questionId = $json['questionId'];
        $questionType = $json['questionType'];

        $query = "SELECT T2.id, T2.youtubeId,T2.subjectId, T2.questionText, T2.isFollowUp, T2.answerDuration,T2.key_skill_id,T2.questionLevel FROM ( SELECT @r AS _id, (SELECT @r := isFollowUp FROM questions WHERE id = _id) AS isFollowUp, @l := @l + 1 AS lvl FROM (SELECT @r := '" . $questionId . "', @l := 'Y') vars, questions h WHERE @r <> 'Y') T1 JOIN questions T2 ON T1._id = T2.id order by T2.isFollowUp = 'Y' desc, T2.isFollowUp";
        $result = mysqli_query($databaseConnection, $query);
        if (mysqli_num_rows($result) >= 1) {
            $values = mysqli_fetch_all($result, MYSQLI_ASSOC);
            $to_encode = $values;
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "noinfo",
                'errorCode' => "in Error while retrieving data.",
                'query' => $query
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving data."
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['submitFollowUp'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $questionId = $json['questionId'];
        $questionIds = implode(',', array_map(function ($q) {
            return $q['id'];
        }, $questionId));


        $allquestionIds = $json['allquestionIds'];

        $filteredQuestions = implode(',', array_map(function ($q) {
            return $q['id'];
        }, $allquestionIds));



        for ($i = 0; $i < sizeof($allquestionIds); $i++) {
            $updateChildQues = "update questions set isFollowUp = Null where id = '" . addslashes($allquestionIds[$i]['id']) . "'";
            mysqli_query($databaseConnection, $updateChildQues);
        }

        for ($i = 0; $i < sizeof($questionId); $i++) {
            $updateChildQues = "update questions set isFollowUp = '" . addslashes($questionId[$i]['isFollowUp']) . "' where id = '" . addslashes($questionId[$i]['id']) . "'";
            mysqli_query($databaseConnection, $updateChildQues);
        }
        $updateParentQues = "update questions set isFollowup = 'Y' where id in (select * from (select isFollowUp as ID from questions Q where isFollowUp REGEXP '^[0-9]+$' and id in (" . $questionIds . ")) as X) and isFollowup = 'N';";
        $followUpRes = mysqli_query($databaseConnection, $updateParentQues);
        $updateFollowUpQuery = 'CALL updateFollowUp()';
        $updateFollowUp = mysqli_query($databaseConnection, $updateFollowUpQuery);

        if ($followUpRes) {
            $updateClusterLevel = updateClusterLevel($databaseConnection, $questionIds);
            $to_encode = array(
                'status' => 1,
                'result' => "success",
                'msg' => "data updated successfully"
            );
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "noinfo",
                'errorCode' => "in Error while updating data.",
                'query' => $followUpQuery
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while updating data."
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getInterviewProfileData'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $limit = $json['limit'];
        $start = ($json['page'] - 1) * $limit;
        $limit_query = $limit == 0 ? "" : " limit " . $start . "," . $limit;
        $filter_query = " ";
        $candidate_stream = " ";
        $having_query = " having 1 ";
        $streams = $json['stream'];

        if ($json['subject'] != "") {
            $filter_query .= " and i.subject_id ='" . $json['subject'] . "'";
        }
        if ($json['stream'] != "" and sizeof($json['stream']) > 0) {
            $filter_query .= " and " . getMultipleFindInSet($json['stream'], "i.stream");
            if (($key = array_search('17', $streams)) !== false) {
                unset($streams[$key]);
            }

        }
        if ($streams != "" and sizeof($streams) > 0) {
            $candidate_stream .= " and pd.specialization in ('" . implode("', '", $streams) . "') ";
        }
        if ($json['interviewName'] != "") {
            $filter_query .= " and i.name like'%" . $json['interviewName'] . "%'";
        }
        if ($json['product'] != "") {
            $filter_query .= " and i.productId = '" . $json['product'] . "'";
        }
        if ($json['category'] != "" and sizeof($json['category']) > 0) {
            $filter_query .= " and " . getMultipleFindInSet($json['category'], "i.categoryType");
        }
        if ($json['noOfGuidanceVideo'] != "") {
            if ($json['noOfGuidanceVideo'] == 'full') {
                $having_query .= " and  GV = QT and GV > 0 ";
            } else {
                $having_query .= " and  GV ='" . $json['noOfGuidanceVideo'] . "'";
            }
        }
        $data = '';
        if ($userType == 'admin' || $userType == 'mentor') {
            $data = "SELECT i.id,c.name as CategoryName,i.interviewLevel as Level_of_Difficulty,i.description as interviewDescription,fv.favourite_subject as areaOfInterview,p.name as productName,i.duration,i.name as interviewName,i.stream as stream ,i.assessmentParameters as AssessmentSkills, count(distinct (CASE WHEN i.categoryType = 9 THEN (CASE WHEN iqt.deleted_at is null and q.deleted_at is null and q.expertAdvice is not null and iqt.attemptStatus = 'Respond'  THEN iqt.questionId ELSE NULL END) ELSE  (CASE WHEN iqt.deleted_at is null and q.deleted_at is null and q.expertAdvice is not null THEN iqt.questionId ELSE NULL END) END)) as GV, count(distinct (CASE WHEN i.categoryType = 9 THEN  (CASE WHEN iqt.deleted_at is null and q.deleted_at is null and iqt.attemptStatus = 'Respond'  and (q.peerResponseVideo is not null or q.mbr_id != '0') THEN iqt.questionId WHEN iqt.deleted_at is null and q.deleted_at is null and q.peerResponseVideo is null and q.mbr_id != 0  and iqt.attemptStatus = 'Respond' THEN iqt.questionId ELSE NULL END) ELSE (CASE WHEN iqt.deleted_at is null and q.deleted_at is null and (q.peerResponseVideo is not null or q.mbr_id != '0') THEN iqt.questionId WHEN iqt.deleted_at is null and q.deleted_at is null and q.peerResponseVideo is null and q.mbr_id != 0 THEN iqt.questionId ELSE NULL END) END)) as PRV, count(distinct (CASE WHEN i.categoryType = 9 THEN  (CASE WHEN iqt.deleted_at is null and q.deleted_at is null and iqt.attemptStatus='Respond' THEN iqt.questionId ELSE NULL END) ELSE (CASE WHEN iqt.deleted_at is null and q.deleted_at is null  THEN iqt.questionId ELSE NULL END) -1 END)) as QT , i.categoryType , i.createdBy  FROM `interview` i inner join favourite_subject fv on fv.id = i.subject_id inner join interview_questions_transection iqt on iqt.interviewId = i.id inner join questions q on iqt.questionId = q.id inner join product p on p.id=i.productId inner join category c on c.id = i.categoryType WHERE i.isActive='Y' and i.deleted_at is null and i.productId is not null" . $filter_query . " group by i.id " . $having_query . " order by i.name";
        }

        $countData = "SELECT i.id,count(distinct (CASE WHEN iqt.deleted_at is null and q.deleted_at is null and q.expertAdvice is not null THEN iqt.questionId ELSE NULL END)) as GV ,(count(distinct (CASE WHEN iqt.deleted_at is null and q.deleted_at is null  THEN iqt.questionId ELSE NULL END)) -1) as QT FROM `interview` i inner join favourite_subject fv on fv.id = i.subject_id inner join interview_questions_transection iqt on iqt.interviewId = i.id inner join questions q on iqt.questionId = q.id inner join product p on p.id=i.productId inner join category c on c.id = i.categoryType WHERE i.isActive='Y' and i.deleted_at is null and i.productId is not null" . $filter_query . " group by i.id " . $having_query . " order by i.name";


        if ($data != '') {
            $query = mysqli_query($databaseConnection, $data . $limit_query);
            $count_query = mysqli_query($databaseConnection, "select count(*) as count_result from ($data) as temp;");
            if (mysqli_num_rows($query) >= 1) {
                $count_result = mysqli_fetch_assoc($count_query);
                $values = array();

                while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
                    $row['GuidanceRatio'] = $row['GV'] . '/' . $row['QT'];
                    $row['PeerResponseRatio'] = $row['PRV'] . '/' . $row['QT'];
                    $uniqueCandidateCount = mysqli_query($databaseConnection, "select count(distinct(m.candidateId)) as uniqueCandidate from mergedVideos m inner join professionaldetails pd on pd.candidateId = m.candidateId where m.interviewSessionId is not null and m.interviewId='" . $row['id'] . "' " . $candidate_stream . " ");
                    $uniqueCandidateCountResult = mysqli_fetch_assoc($uniqueCandidateCount);

                    $row['uniqueCandidate'] = $uniqueCandidateCountResult['uniqueCandidate'];
                    $streamQuery = mysqli_query($databaseConnection, "SELECT i.stream, group_concat(s.stream SEPARATOR ', ') AS streamName FROM interview i, stream s WHERE FIND_IN_SET(s.id, i.stream) and i.id = '" . $row['id'] . "';");
                    $streamResult = mysqli_fetch_array($streamQuery, MYSQLI_ASSOC);

                    $row['streamName'] = $streamResult['streamName'];
                    $subject_query = mysqli_query($databaseConnection, "SELECT group_concat(DISTINCT fs.favourite_subject SEPARATOR ', ') AS SubjectName  FROM interview_questions_transection iqt inner join questions q on q.id = iqt.questionId inner join favourite_subject fs on fs.id = q.subjectId where q.deleted_at is null and iqt.deleted_at is null and iqt.interviewId = '" . $row['id'] . "' order by iqt.sequence DESC;");
                    $subjectResult = mysqli_fetch_array($subject_query, MYSQLI_ASSOC);
                    $row['SubjectName'] = $subjectResult['SubjectName'];
                    if ($row['categoryType'] == '9') {
                        $quesSql = "Select q.id as quesId,q.questionText,q.expertApproval,fv.favourite_subject as questionSubject,q.followUp,q.isWbRequired,q.questionType,q.questionLevel,tp.name as topic,c.name as concept,q.clusterLevel,CASE WHEN iqt.attemptStatus is null THEN 'Blue' WHEN iqt.attemptStatus ='Respond' THEN 'Green' when iqt.attemptStatus ='Skip'  THEN 'Red' ELSE 'Blue' END as AttemptStatus from  interview i inner join interview_questions_transection iqt on i.id = iqt.interviewId  inner join questions q on q.id=iqt.questionId left outer join topic tp on q.topic_id=tp.id left outer join favourite_subject fv on fv.id=q.subjectId left outer join concepts c on c.id = q.conceptId   where i.id='" . $row['id'] . "' and q.deleted_at is null and iqt.deleted_at is null group by iqt.sequence order by iqt.sequence";

                        //left outer join mergedVideos m on m.interviewId = i.id and m.questionId = q.id and m.candidateId = '".$row['createdBy']."'


                    } else {
                        $quesSql = "Select q.id as quesId,q.questionText,q.expertApproval,fv.favourite_subject as questionSubject,q.followUp,q.isWbRequired,q.questionType,q.questionLevel,tp.name as topic,c.name as concept,q.clusterLevel,'Blue' as AttemptStatus from  interview i inner join interview_questions_transection iqt on i.id = iqt.interviewId  inner join questions q on q.id=iqt.questionId left outer join topic tp on q.topic_id=tp.id left outer join favourite_subject fv on fv.id=q.subjectId left outer join concepts c on c.id = q.conceptId  where i.id='" . $row['id'] . "' and q.deleted_at is null and iqt.deleted_at is null group by iqt.sequence order by iqt.sequence";

                    }
                    $interviewDetail = mysqli_query($databaseConnection, $quesSql);
                    $interview = array();
                    while ($interviewDetails = mysqli_fetch_array($interviewDetail, MYSQLI_ASSOC)) {
                        $streamquery = mysqli_query($databaseConnection, "SELECT group_concat(s.stream SEPARATOR ', ') AS questionStream  FROM questions q , stream s WHERE FIND_IN_SET(s.id, q.eligibleStreamId) and q.id = '" . $interviewDetails['quesId'] . "';");
                        $streamresult = mysqli_fetch_array($streamquery, MYSQLI_ASSOC);
                        $interviewDetails['questionStream'] = $streamresult['questionStream'];
                        $key_skillquery = mysqli_query($databaseConnection, "SELECT group_concat(ks.key_skill SEPARATOR ', ') AS questionSkill  FROM questions q , key_skill ks WHERE FIND_IN_SET(ks.id, q.key_skill_id) and q.id = '" . $interviewDetails['quesId'] . "';");
                        $key_skillresult = mysqli_fetch_array($key_skillquery, MYSQLI_ASSOC);
                        $interviewDetails['questionSkill'] = $key_skillresult['questionSkill'];
                        array_push($interview, $interviewDetails);
                    }
                    $row['interviewDetails'] = $interview;
                    array_push($values, $row);
                }

                $to_encode = array(
                    'result' => "success",
                    'status' => 1,
                    'data' => $values,
                    'count' => $count_result['count_result'],
                    'query' => $data . $limit_query

                );
            } else {
                $to_encode = array(
                    'result' => "error",
                    'status' => 0,
                    'query' => $data . $limit_query,
                    'errorCode' => "in Error while retrieving interview information."
                );
            }
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "in Error You are not having access this page."
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving Product information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['ExportInterviewProfileData'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $filter_query = " ";
        $having_query = " having 1 ";
        $candidate_stream = " ";
        $streams = $json['stream'];

        if ($json['subject'] != "") {
            $filter_query .= " and i.subject_id ='" . $json['subject'] . "'";
        }
        if ($json['stream'] != "" and sizeof($json['stream']) > 0) {
            $filter_query .= " and " . getMultipleFindInSet($json['stream'], "i.stream");
            if (($key = array_search('17', $streams)) !== false) {
                unset($streams[$key]);
            }
        }
        if ($streams != "" and sizeof($streams) > 0) {
            $candidate_stream .= " and pd.specialization in ('" . implode("', '", $streams) . "') ";

        }
        if ($json['interviewName'] != "") {
            $filter_query .= " and i.name like'%" . $json['interviewName'] . "%'";
        }
        if ($json['product'] != "") {
            $filter_query .= " and i.productId = '" . $json['product'] . "'";
        }
        if ($json['category'] != "" and sizeof($json['category']) > 0) {
            $filter_query .= " and " . getMultipleFindInSet($json['category'], "i.categoryType");
        }
        if ($json['noOfGuidanceVideo'] != "") {
            if ($json['noOfGuidanceVideo'] == 'full') {
                $having_query .= " and  GV = QT and GV > 0 ";
            } else {
                $having_query .= " and  GV ='" . $json['noOfGuidanceVideo'] . "'";
            }
        }


        $data = '';
        if ($userType == 'admin' || $userType == 'mentor') {

            $data = "SELECT i.id as InterviewId,i.name as InterviewName,c.name as CategoryName,i.interviewLevel as Level_of_Difficulty, p.name as productName,fv.favourite_subject as areaOfInterview,i.duration as InterviewDuration,CONCAT('https://goprac.com/interviewDetails?id=',i.id) as InterviewUrl,i.assessmentParameters as AssessmentSkills ,(select group_concat(DISTINCT fvs.favourite_subject order by qs.subjectId SEPARATOR ', ') from interview_questions_transection iq  inner join questions qs on iq.questionId = qs.id inner join favourite_subject fvs on fvs.id = qs.subjectId where iq.interviewId=i.id and qs.deleted_at is null and iq.deleted_at is null) as SubjectNameOfUsedQuestions,i.description as InterviewDescription,(SELECT GROUP_CONCAT((CASE WHEN qs.questionType='Start' THEN CONCAT('Start- ',if(fvs.favourite_subject is not null,fvs.favourite_subject,'Not Available'),' ',qs.id) WHEN qs.questionType='Universal' THEN CONCAT('Universal- ',if(fvs.favourite_subject is not null,fvs.favourite_subject,'Not Available'),' ',qs.id) WHEN qs.questionType='Climax' THEN CONCAT('Climax- ',if(fvs.favourite_subject is not null,fvs.favourite_subject,'Not Available'),' ',qs.id) ELSE NULL END) order by iq.sequence  SEPARATOR ', ') as IntProfile from interview_questions_transection iq inner join questions qs on iq.questionId =qs.id left outer join favourite_subject fvs on fvs.id = qs.subjectId where iq.interviewId=i.id and iq.deleted_at is null and qs.deleted_at is null group by iq.interviewId) as InterviewProfile ,

            count(distinct (CASE WHEN i.categoryType = 9 THEN (CASE WHEN iqt.deleted_at is null and q.deleted_at is null and q.expertAdvice is not null and iqt.attemptStatus = 'Respond'  THEN iqt.questionId ELSE NULL END) ELSE  (CASE WHEN iqt.deleted_at is null and q.deleted_at is null and q.expertAdvice is not null THEN iqt.questionId ELSE NULL END) END)) as GV,
             count(distinct (CASE WHEN i.categoryType = 9 THEN  (CASE WHEN iqt.deleted_at is null and q.deleted_at is null and iqt.attemptStatus='Respond' THEN iqt.questionId ELSE NULL END) ELSE (CASE WHEN iqt.deleted_at is null and q.deleted_at is null  THEN iqt.questionId ELSE NULL END -1) END))  as QT
            FROM `interview` i inner join favourite_subject fv on fv.id = i.subject_id inner join interview_questions_transection iqt on iqt.interviewId = i.id inner join questions q on iqt.questionId = q.id inner join product p on p.id=i.productId inner join category c on i.categoryType=c.id WHERE i.isActive='Y' and i.deleted_at is null and i.productId is not null" . $filter_query . " group by i.id " . $having_query . " order by i.name";
        }
        if ($data != '') {
            $query = mysqli_query($databaseConnection, $data);
            if (mysqli_num_rows($query) >= 1) {
                $values = array();
                while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
                    $row['GuidanceRatio'] = $row['GV'] . "/" . $row['QT'];
                    $streamQuery = mysqli_query($databaseConnection, "SELECT i.stream, group_concat(s.stream SEPARATOR ', ') AS streamName FROM interview i, stream s WHERE FIND_IN_SET(s.id, i.stream) and i.id = '" . $row['InterviewId'] . "';");
                    $streamResult = mysqli_fetch_array($streamQuery, MYSQLI_ASSOC);
                    $row['StreamName'] = $streamResult['streamName'];

                    $uniqueCandidateCount = mysqli_query($databaseConnection, "select count(distinct(m.candidateId)) as uniqueCandidate from mergedVideos m inner join professionaldetails pd on pd.candidateId = m.candidateId where m.interviewSessionId is not null and m.interviewId='" . $row['InterviewId'] . "' " . $candidate_stream . " ");
                    $uniqueCandidateCountResult = mysqli_fetch_assoc($uniqueCandidateCount);

                    $row['uniqueCandidateTaken'] = $uniqueCandidateCountResult['uniqueCandidate'];

                    array_push($values, $row);
                }

                $to_encode = array(
                    'result' => "success",
                    'status' => 1,
                    'data' => $values,
                    'query' => $data

                );
            } else {
                $to_encode = array(
                    'result' => "error",
                    'status' => 0,
                    'query' => $data . $limit_query,
                    'errorCode' => "in Error while retrieving interview information."
                );
            }
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "in Error You are not having access this page."
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving Product information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['addExistingQuestionInInterview'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $questionId = $json['questionIds'];
        $sequence = $json['sequence'];
        $interviewId = $json['interviewId'];

        for ($i = 0; $i < sizeof($questionId); $i++) {
            $insertQuery = "INSERT INTO interview_questions_transection(`interviewId`, `questionId`, `sequence`) VALUES ('" . $interviewId . "', '" . $questionId[$i] . "', '" . $sequence[$i] . "')";
            $questionsInsert = mysqli_query($databaseConnection, $insertQuery);
        }
        if ($questionsInsert) {

            $to_encode = array(
                'status' => 1,
                'result' => "success",
                'errorCode' => "data updated successfully",
                'query' => $insertQuery
            );
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "Error",
                'errorCode' => "in Error while updating data.",
                'query' => $insertQuery
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while updating data."
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['updateQuestionSequenceInInterview'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $questionId = $json['questionIds'];
        $sequence = $json['sequence'];
        $interviewId = $json['interviewId'];
        for ($i = 0; $i < sizeof($questionId); $i++) {
            $updateQuery = "UPDATE interview_questions_transection SET `sequence`= '" . $sequence[$i] . "' where `interviewId`= '" . $interviewId . "' and `questionId` = '" . $questionId[$i] . "' ";
            $questionSequence = mysqli_query($databaseConnection, $updateQuery);
        }
        if ($questionSequence) {

            $to_encode = array(
                'status' => 1,
                'result' => "success",
                'errorCode' => "data updated successfully",
                'query' => $updateQuery
            );
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "Error",
                'errorCode' => "in Error while updating data.",
                'query' => $updateQuery
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while updating data."
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['createDynamicInterview'])) {
    /* this method is written by Narayan for creating dynamic interview march 2022*/
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $companyId = $json['companyId'];
        $roleId = $json['roleId'];
        $productId = $json['productId'];
        $sectorId = $json['sectorId'];
        $userName = $json['userName'];
        $currentAssessmentType = $json['currentAssessmentType'];
        $preInterviewId = $json['preInterviewId'];

        // Handle Authentication and Authorization for Restricted preInterview
        // Ensure proper charset for correct escaping
        $databaseConnection->set_charset('utf8mb4'); // important when using real_escape_string [3]

        // ===== Block A: validate inputs and resolve userEmail (registered or guest) =====
        $preInterviewIdForAuth = null;
        if (isset($preInterviewId) && $preInterviewId !== '' && is_numeric($preInterviewId)) {
            $preInterviewIdForAuth = (int)$preInterviewId; // safe integer casting [4]
        }

        $userEmail = null;

        // If userId is present and numeric, try DB first (raw query)
        if (isset($userId) && $userId !== '' && is_numeric($userId)) {
            $userId = (int)$userId; // cast [4]
            $userEmailSql = "SELECT emailId FROM users WHERE id = {$userId} LIMIT 1";
            if ($res = mysqli_query($databaseConnection, $userEmailSql)) {
                if ($row = mysqli_fetch_assoc($res)) {
                    $userEmail = $row['emailId'];
                }
                mysqli_free_result($res); // free to avoid out-of-sync [7][11]
            } else {
                error_log("Query failed (userEmail): " . mysqli_error($databaseConnection));
            }
        }

        // Fallback: guest email from request body (validated)
        if ($userEmail === null && isset($json['email']) && is_string($json['email'])) {
            $candidateEmail = trim($json['email']);
            if (filter_var($candidateEmail, FILTER_VALIDATE_EMAIL)) {
                $userEmail = $candidateEmail;
            }
        }

        // Debug
        error_log("[CDI] inputs userId=" . var_export($userId,true) . ", preInterviewId=" . var_export($preInterviewId,true) . ", preInterviewIdForAuth=" . var_export($preInterviewIdForAuth,true));
        error_log("[CDI] userEmail(raw)=" . var_export($userEmail,true));

        // Optional: drain any pending extra results if earlier code used CALL/multi_query
        while (mysqli_more_results($databaseConnection) && mysqli_next_result($databaseConnection)) {
            if ($tmp = mysqli_store_result($databaseConnection)) { mysqli_free_result($tmp); }
        } // helps prevent out-of-sync after procedures [7][11]

        // ===== Block B: Restricted + Practice authorization (access = 'i') =====
        if ($preInterviewIdForAuth !== null) {
            // 1) Fetch flags
            $piId = (int)$preInterviewIdForAuth; // cast [4]
            $piSql = "SELECT restrictedOnly, interviewType FROM preInterview WHERE id = {$piId} LIMIT 1";
            $restrictedOnly = null; $interviewType = null;

            if ($res = mysqli_query($databaseConnection, $piSql)) {
                if ($row = mysqli_fetch_assoc($res)) {
                    $restrictedOnly = $row['restrictedOnly'];
                    $interviewType  = $row['interviewType'];
                }
                mysqli_free_result($res); // free before next query [7][11]
            } else {
                error_log("Query failed (piSql): " . mysqli_error($databaseConnection));
                echo "line 4977";
            }

            if ($restrictedOnly !== null) {
                $flag = strtoupper(trim((string)$restrictedOnly));
                if ($flag === '') { $flag = 'N'; }
                $isPractice = (strcasecmp((string)$interviewType, 'Practice') === 0);

                error_log("[CDI] flags restrictedOnly=" . var_export($restrictedOnly,true) . ", interviewType=" . var_export($interviewType,true));

                // 2) Only auth-check when restricted + practice
                if ($flag === 'Y' && $isPractice) {
                    if ($userEmail === null || $userEmail === '') {
                        echo json_encode(['result'=>'error','status'=>0,'errorCode'=>'Email required for authorization']);
                        exit;
                    }

                    // Normalize and escape email
                    $normEmail = strtolower(trim($userEmail));
                    $escEmail  = mysqli_real_escape_string($databaseConnection, $normEmail); // escape string [3]

                    // Safe integer cast already done for preInterviewId
                    $authSql = "
                        SELECT 1
                        FROM candidateInterviewMapping
                        WHERE preInterviewId = {$piId}
                        AND emailId = '{$escEmail}'
                        AND deleted = 'N'
                        AND access = 'i'
                        LIMIT 1";

                    if ($res = mysqli_query($databaseConnection, $authSql)) {
                        $rows = mysqli_num_rows($res);
                        mysqli_free_result($res); // free [7]

                        error_log("[CDI] auth rows=" . var_export($rows,true));

                        if ((int)$rows !== 1) {
                            echo json_encode([
                                'result' => 'error',
                                'status' => -2,
                                'errorCode' => 'UNAUTHORIZED ACCESS: Access denied.'
                            ]);
                            exit;
                        }
                    } else {
                        error_log("Query failed (authSql): " . mysqli_error($databaseConnection));
                        echo "line 4961";
                        // Soft-fail: proceed to keep legacy behavior
                    }
                }
                // else: open or not practice → proceed
            } else {
                // No preInterview row; soft-fail and proceed
            }
        }

        // ===== End Block B =====

        // existing logic....

        if (isset($json['interviewId']) && $json['interviewId'] !== '') {
            $interviewId = $json['interviewId'];
        } else {
            $interviewId = "";
        }

        if (!($interviewId == "")) {
            $interviewStructure = array();
            $questions = [];

            // get interviewStructure //
            $interviewStructure_sql = "SELECT DISTINCT sectionName
            FROM interview_questions_transection
            WHERE interviewId = $interviewId
            ORDER BY sequence";

            $result = mysqli_query($databaseConnection, $interviewStructure_sql);

            if ($result === false) {
                echo mysqli_error($databaseConnection);
            }

            if (mysqli_num_rows($result) > 0) {
                while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
                    array_push($interviewStructure, $row['sectionName']);
                }
            }



            // get questions //

            // iqt.id AS transactionId,
            // iqt.interviewId,
            // iqt.questionId,
            // iqt.sequence,


            // iqt.attemptStatus,
            // q.deleted_at AS questionDeletedAt,

            // SQL query
            $sql = "
            SELECT
                q.id,
                q.youtubeId,
                q.thumbnail,
                q.quesAudio,
                q.quesDiagram,
                q.questionText,
                q.idk1,
                q.idk1Ans,
                q.idk2,
                q.idk2Ans,
                q.questionDesc,
                q.questionType,
                q.key_skill_id,
                q.topic_id,
                q.questionDuration,
                q.thinkingTime,
                q.answerDuration,
                q.extensionTime,
                q.streamId,
                q.isActive,
                q.isFollowUp,
                q.followUp,
                q.peerResponseVideo,
                q.expertApproval,
                q.priorityStatus,
                q.shortExpectedAns,
                q.questionLevel,
                q.isWbRequired,
                q.instruction,
                q.questionTag,
                q.source,
                q.eligibleStreamId,
                q.subjectId,
                q.conceptId,
                q.domainId,
                q.tutorialLink,
                q.remarks,
                q.peerResponseStatus,
                q.mbr_id,
                q.expertAdvice,
                q.questionCreator,
                q.questionReviewer,
                q.noOfImages,
                q.noOfVideos,
                q.updatedAt,
                q.clusterLevel,
                iqt.noOfSkip AS Skip,
                iqt.noOfRespond AS Respond,
                iqt.SectionName,
                fs.favourite_subject
            FROM
                interview_questions_transection AS iqt
            JOIN
                questions AS q ON iqt.questionId = q.id
            JOIN
                favourite_subject AS fs ON q.subjectId = fs.id
            WHERE
                iqt.interviewId = $interviewId;
            ";

            $result = mysqli_query($databaseConnection, $sql);

            if ($result === false) {
                die("Error executing query: " . mysqli_error($databaseConnection));
            }

            // $values1['clusterChild'] = 0;
            // $values1['childNumber'] = 0;
            // $values1['SectionName'] = $interviewStructure[$i]; 
            // $values1['DepthRequired'] = $sectionDepth[$i];
            // $values1['Skip'] = $totalSkipRequired[$i]; x
            // $values1['Respond'] = $totalRespondRequired[$i]; x
            // $values1['questionHtml'] = nl2br($values1['questionText']); x

            // Fetch result as an associative array
            while ($row = mysqli_fetch_assoc($result)) {

                $depthRequired = [];


                // get depthRequired for each question
                $depthRequired_sql = "SELECT 
                iqt.questionId,
                iqt.id,
                istr.depthRequired,
                iqt.interviewId,
                isec.id
                FROM
                interview_questions_transection iqt
                JOIN
                interviewSection isec ON iqt.sectionName = isec.name
                JOIN
                interviewStructure istr ON isec.id = istr.sectionId
                WHERE
                iqt.interviewId = '$interviewId' AND
                istr.preInterviewId = '$preInterviewId' AND
                iqt.questionId= '" . $row['id'] . "'";

                // echo $depthRequired_sql;


                $depthRequired_result = mysqli_query($databaseConnection, $depthRequired_sql);

                if ($depthRequired_result === false) {
                    die("Error executing query: " . mysqli_error($databaseConnection));
                }

                if (mysqli_num_rows($depthRequired_result) > 0) {
                    while ($depth = mysqli_fetch_array($depthRequired_result, MYSQLI_ASSOC)) {
                        $depthRequired[] = $depth['depthRequired'];
                    }
                }

                // var_dump($depthRequired);

                $row['DepthRequired'] = $depthRequired[0];
                $row['questionHtml'] = nl2br($row['questionText']);
                $questions[] = $row;
            }

            $questions = calculateChildInfo($questions);

            foreach ($questions as &$item) {
                // Check if "favourite_subject" is set
                if (isset($item['favourite_subject'])) {
                    // Rename the key and create a new "subjectName" array
                    $item['subjectName'] = ['favourite_subject' => $item['favourite_subject']];
                    // Remove the old key
                    unset($item['favourite_subject']);
                }
            }


            $interviewNewData = "select i.*  from `interview` i  where i.id='" . $interviewId . "'";
            $interviewNewQuery = mysqli_query($databaseConnection, $interviewNewData);
            $values = mysqli_fetch_all($interviewNewQuery, MYSQLI_ASSOC);


            $newtutorial = "select * from `interview_tutorial` where interviewId='" . $interviewId . "' and isActive = 'Y'";
            $newtutorialQuery = mysqli_query($databaseConnection, $newtutorial);
            if (mysqli_num_rows($newtutorialQuery) >= 1) {
                $newtutorialValues = mysqli_fetch_all($newtutorialQuery, MYSQLI_ASSOC);
                $values[0]['tutorialLink'] = $newtutorialValues;
            } else {
                $values[0]['tutorialLink'] = null;
            }

            $confirmQuery = "select AVConfirm from users where id = '" . $userId . "'";
            $confirmQueryResult = mysqli_query($databaseConnection, $confirmQuery);
            $confirmQueryValues = mysqli_fetch_all($confirmQueryResult, MYSQLI_ASSOC);
            $values[0]['isconfirmChecked'] = $confirmQueryValues[0]['AVConfirm'];

            $connecttomentorquery = mysqli_query($databaseConnection, "select pd.connecttomentor,pd.timetocontact,pd.connecttomentorname from professionaldetails pd where pd.candidateId  = '" . $userId . "'");
            $connecttomentorResult = mysqli_fetch_all($connecttomentorquery, MYSQLI_ASSOC);
            if ($connecttomentorResult[0]['connecttomentor'] != null && $connecttomentorResult[0]['timetocontact'] != null) {
                $values[0]['connecttomentorsubmitted'] = 1;
            } else {
                $values[0]['connecttomentorsubmitted'] = 0;
            }


            // resume interview data
            // $resumeQuery = "SELECT *
            //     FROM
            //         interview_questions_transection iqt
            //     WHERE
            //         interviewId = '$interviewId'
            //         AND
            //             attemptStatus IS NOT NULL
            //         AND sequence = (
            //         SELECT
            //             MAX(sequence)
            //         FROM
            //             interview_questions_transection
            //         WHERE
            //             interviewId = '$interviewId'
            //             AND attemptStatus IS NOT NULL)

            //         AND sequence < (
            //         SELECT
            //             MAX(sequence)
            //         FROM
            //             interview_questions_transection
            //         WHERE
            //             interviewId = '$interviewId')";


            // // echo $resumeQuery;

            // $resumeResult = mysqli_query($databaseConnection, $resumeQuery);

            // if (mysqli_num_rows($resumeResult) > 0) {

            //     // Rows were found, you can fetch the data
            //     while ($row = mysqli_fetch_assoc($resumeResult)) {
            //         $resumeData = array(
            //             'status' => 1,
            //             'result' => $row,
            //         );
            //     }


            // }else{
            //     $resumeData = array(
            //         'status' => -1,
            //     );
            // }

            $resumeQuery = "SELECT questionId as id, `sequence`, noOfRespond,sectionName,attemptStatus
            FROM interview_questions_transection iqt
            WHERE interviewId = '$interviewId' ";
            $result = mysqli_query($databaseConnection, $resumeQuery);

            if ($result) {
                $resumeData = array();

                while ($row = mysqli_fetch_assoc($result)) {
                    // echo $row;
                    $resumeData[] = $row;
                }

                if (!empty($resumeData)) {
                    $resumeData = array(
                        'status' => 1,
                        'result' => $resumeData,
                    );
                } else {
                    $resumeData = array(
                        'status' => -1,
                    );
                }
                // Free the result set
                mysqli_free_result($result);
            } else {
                $resumeData = array(
                    // 'qry' => "Error executing query: " . mysqli_error($databaseConnection),
                    'status' => -1,
                );
            }

            $sessionIdQuery = "SELECT interviewSessionId
            FROM feedback_request
            WHERE interviewId = '$interviewId' ";

            $result = mysqli_query($databaseConnection, $sessionIdQuery);

            if ($result) {
                if (mysqli_num_rows($result) > 0) {
                    $row = mysqli_fetch_assoc($result);
                    $sessionId = array(
                        'sessionId' => $row['interviewSessionId'],
                    );
                } else {
                    $sessionId = array(
                        'sessionId' => NULL,
                    );
                }

                mysqli_free_result($result);
            } else {
                // Handle the case where the query was not successful
                $error = mysqli_error($databaseConnection);
                // Log or output the error as needed
                $sessionId = array(
                    'sessionId' => NULL,
                    'error' => $error,
                );
            }

            $isExist_sql = "SELECT id FROM interviewSchedule WHERE interviewId = '" . $interviewId . "'";
            // echo $isExist_sql;
            $isExist_query = mysqli_query($databaseConnection, $isExist_sql);

            // Check if the query was successful and if it returned any rows
            if ($isExist_query) {
                $isExist_values = mysqli_fetch_all($isExist_query, MYSQLI_ASSOC);

                if (!empty($isExist_values)) {
                    // Data exists, update interviewSchedule
                } else {
                    // No data returned, insert into interviewSchedule
                    $interviewScheduleInsert = "INSERT INTO interviewSchedule (interviewId, candidate_id, company_id, preInterviewId,scheduleTime,firstScheduleDate) VALUES ('" . $interviewId . "', '" . $userId . "', '" . $companyId . "', '" . $preInterviewId . "',NOW(),NOW())";
                    $interviewScheduleInsertQuery = mysqli_query($databaseConnection, $interviewScheduleInsert);

                    if (!$interviewScheduleInsertQuery) {
                        // Insert query failed
                        echo "Insert query failed: " . mysqli_error($databaseConnection);
                    }
                }
            } else {
                // Query was not successful
                echo "Query failed: " . mysqli_error($databaseConnection);
            }

            // var_dump($questions);
            // var_dump($resumeData);

            $to_encode = $values;
            array_push($to_encode, $questions);
            array_push($to_encode, $interviewStructure);
            array_push($to_encode, $resumeData);
            array_push($to_encode, $sessionId);

        } else {
            // $company_fav_subjects = explode(',', $json['company_fav_subjects']);

            $subjects = $json['company_fav_subjects'];
            $topics = $json['topics'];

            $company_fav_subjects = array();

            foreach ($subjects as $item) {
                $key = key($item);
                $value = $item[$key];
                $company_fav_subjects[$key] = $value;
            }

            $result = array();
            /* this method is written for getting Subject  Sequence */

            //new methods for dynamic sections

            $SubjectSequence = getInterviewSubjectSequence_new($databaseConnection, $preInterviewId, $company_fav_subjects);

            // $topicSequence = getInterviewTopicSequence_new($databaseConnection,$preInterviewId,$SubjectSequence);

            // print_r($topics);
            if (empty($topics)) {
                $topicSequence = getInterviewTopicSequence_new($databaseConnection, $preInterviewId, $SubjectSequence);
            } else {
                $topicSequence = array_reduce($topics, function ($carry, $item) {
                    foreach ($item as $key => $value) {
                        if (isset($carry[$key])) {
                            $carry[$key] .= ',' . $value;
                        } else {
                            $carry[$key] = $value;
                        }
                    }
                    return $carry;
                }, array());

            }
            // print_r($topicSequence);
            // exit();


            $interviewStructure = getInterviewStructure_new($databaseConnection, $preInterviewId);

            $totalQuestionRequired = getTotalQuestionSectionWise_new($databaseConnection, $preInterviewId);

            $totalRespondRequired = getTotalRespondSectionWise_new($databaseConnection, $preInterviewId);

            $totalSkipRequired = getTotalSkipSectionWise_new($databaseConnection, $preInterviewId);

            $sectionDepth = getDepthRequiredSectionWise_new($databaseConnection, $preInterviewId);

            $clusterPreference = getClusterPreferenceSectionWise_new($databaseConnection, $preInterviewId);

            $questions = getQuestionsForDynamicInterview($databaseConnection, $userId, $SubjectSequence, $interviewStructure, $totalQuestionRequired, $totalRespondRequired, $totalSkipRequired, $sectionDepth, $clusterPreference, $topicSequence);

            // echo json_encode($questions);
            // exit();

            $streamNameQuery = mysqli_query($databaseConnection, "select s.stream,s.id  from professionaldetails pd inner join stream s on pd.specialization = s.id where pd.candidateId ='" . $userId . "' ;");
            if (mysqli_num_rows($streamNameQuery) >= 1) {
                $streamNameResult = mysqli_fetch_assoc($streamNameQuery);
                $stream = $streamNameResult['stream'];
                $streamId = $streamNameResult['id'];
            } else {
                $stream = NULL;
                $streamId = NULL;
            }

            $SubjectNameQuery = mysqli_query($databaseConnection, "select fv.id from favourite_subject fv where  favourite_subject in (select name from sector where id = '" . $sectorId . "')");

            if ($SubjectNameQuery) {
                $SubjectNameResult = mysqli_fetch_assoc($SubjectNameQuery);
                $SubjectId = $SubjectNameResult['id'];
            } else {
                $SubjectNameQuery = mysqli_query($databaseConnection, "select fv.id from favourite_subject fv where  favourite_subject in (select name from sector where id = 1)");
                $SubjectNameResult = mysqli_fetch_assoc($SubjectNameQuery);
                $SubjectId = $SubjectNameResult['id'];
            }


            $roleNameQuery = mysqli_query($databaseConnection, "select name as Role ,DATE_FORMAT(NOW() ,'%D_%b_%Y_%T') as interviewDate from relavant_role  where id =  '" . $roleId . "' ");
            $interviewNameResult = mysqli_fetch_assoc($roleNameQuery);

            $interviewDate = $interviewNameResult['interviewDate'];
            if ($interviewDate == NULL) {
                $interviewDatelong = $round(microtime(true) * 1000);
                $interviewDate = date('d-m-Y H:i:s', $interviewDatelong);
            }
            $roleName = $interviewNameResult['Role'];

            if ($companyId != '') {
                $companyNameQuery = mysqli_query($databaseConnection, "select case when interviewName is null then (select name from aspiration_company where id=company_id) else interviewName end as name from preInterview where id ='" . $preInterviewId . "' ;");

                $companyNameResult = mysqli_fetch_assoc($companyNameQuery);
                $companyName = $companyNameResult['name'];
                $interviewName = $companyName . "_" . $userId . "_" . $interviewDate;

            } else {
                $sectorNameQuery = mysqli_query($databaseConnection, "select case when interviewName is null then (select name as sectorName from sector where id=sectorId) else interviewName end as sectorName from preInterview where id = '" . $preInterviewId . "';");
                $sectorNameResult = mysqli_fetch_assoc($sectorNameQuery);
                $sectorName = $sectorNameResult['sectorName'];
                $interviewName = $sectorName . "_" . $userId . "_Emp_" . $interviewDate;
            }

            $allQuestionId = array_column($questions, 'id');
            $questionIds = implode(',', $allQuestionId);

            $timeQuery = mysqli_query($databaseConnection, "SELECT SUM(answerDuration) as totalTime FROM `questions` WHERE id in ( $questionIds)");
            $timeResult = mysqli_fetch_assoc($timeQuery);



            $assessmentQuery = mysqli_query($databaseConnection, "SELECT group_concat(distinct ks.key_skill SEPARATOR ', ') as assessmentParameters FROM questions q, key_skill ks WHERE q.id in ( $questionIds) and FIND_IN_SET(ks.id, q.key_skill_id);");
            $assessmentResult = mysqli_fetch_assoc($assessmentQuery);
            if ($companyId != '') {
                $sql = "INSERT INTO `interview` (`categoryType`, `name`, `isActive`, `targetAudience`, `stream`, `duration`, `productId`, `assessmentParameters`, `createdBy`,`companyId`,`sector_id`,`subject_id`,`interviewLevel`,`roleId`,`assessmenttype`,`preInterviewId`) VALUES ('9', '" . addslashes($interviewName) . "', 'Y', '" . $stream . "', '" . $streamId . "', '" . roundMultipleOfX($timeResult['totalTime'], 5) . "', '" . $productId . "', '" . $assessmentResult['assessmentParameters'] . "', '$userId',$companyId,$sectorId,$SubjectId,'As per Industry Standard','" . $roleId . "','" . $currentAssessmentType . "','" . $preInterviewId . "')";

            } else {
                $sql = "INSERT INTO `interview` (`categoryType`, `name`, `isActive`, `targetAudience`, `stream`, `duration`, `productId`, `assessmentParameters`, `createdBy`,`sector_id`,`subject_id`,`interviewLevel`,`roleId`,`assessmenttype`,`preInterviewId`) VALUES ('9',  '" . addslashes($interviewName) . "', 'Y', '" . $stream . "', '" . $streamId . "', '" . roundMultipleOfX($timeResult['totalTime'], 5) . "', '" . $productId . "', '" . $assessmentResult['assessmentParameters'] . "', '$userId',$sectorId,$SubjectId,'As per Industry Standard','" . $roleId . "','" . $currentAssessmentType . "','" . $preInterviewId . "')";
            }
            $interviewQuery = mysqli_query($databaseConnection, $sql);

            if ($interviewQuery) {
                $interviewId = mysqli_insert_id($databaseConnection);
                $tutorialData = "SELECT q.tutorialLink,q.remarks,td.name as topicName from questions q left outer join topic td on q.topic_id = td.id where q.`tutorialLink` is not null and q.tutorialLink !='' and q.remarks is not null and q.remarks !='' and q.id in( $questionIds) group by q.tutorialLink";
                $tutorialQuery = mysqli_query($databaseConnection, $tutorialData);
                if (mysqli_num_rows($tutorialQuery) > 0) {
                    $numberOfLinks = mysqli_num_rows($tutorialQuery);
                    while ($row = mysqli_fetch_array($tutorialQuery, MYSQLI_ASSOC)) {
                        if (trim($row["tutorialLink"] != '')) {
                            $link = "INSERT INTO interview_tutorial(interviewId, tutorial_link, remarks, topic_name) VALUES ('" . $interviewId . "', '" . addslashes($row["tutorialLink"]) . "', '" . addslashes($row["remarks"]) . "', '" . addslashes($row["topicName"]) . "')";
                            mysqli_query($databaseConnection, $link);
                        }
                    }
                }
                for ($i = 0; $i < sizeof($questions); $i++) {
                    $quesSequesnce = "INSERT INTO interview_questions_transection(interviewId, questionId, sequence,sectionName,noOfRespond,noOfSKip) VALUES ('" . $interviewId . "', '" . addslashes($questions[$i]['id']) . "', '" . ($i + 1) . "', '" . $questions[$i]['SectionName'] . "','" . $questions[$i]['Respond'] . "','" . $questions[$i]['Skip'] . "')";
                    mysqli_query($databaseConnection, $quesSequesnce);
                }

                // sourabh - 04/01/24
                $isExist_sql = "SELECT id FROM interviewSchedule WHERE interviewId IS NULL AND preInterviewId = '" . $preInterviewId . "'";
                $isExist_query = mysqli_query($databaseConnection, $isExist_sql);

                // Check if the query was successful and if it returned any rows
                if ($isExist_query) {
                    $isExist_values = mysqli_fetch_all($isExist_query, MYSQLI_ASSOC);

                    if (!empty($isExist_values)) {
                        // echo "exists";
                        // echo $interviewId;
                        // echo $interviewScheduleUpdate;
                        // exit();

                        // Data exists, update interviewSchedule
                        $interviewScheduleSelect = "SELECT id FROM interviewSchedule WHERE candidate_id='" . $userId . "' AND company_id='" . $companyId . "' AND preInterviewId= '" . $preInterviewId . "' AND interviewId IS NULL";
                        $interviewScheduleSelectQuery = mysqli_query($databaseConnection, $interviewScheduleSelect);

                        if (mysqli_num_rows($interviewScheduleSelectQuery) > 0) {
                            $interviewScheduleUpdate = "UPDATE interviewSchedule SET interviewId='" . $interviewId . "' WHERE candidate_id='" . $userId . "' AND company_id='" . $companyId . "' AND preInterviewId= '" . $preInterviewId . "' AND interviewId IS NULL";
                            $interviewScheduleUpdateQuery = mysqli_query($databaseConnection, $interviewScheduleUpdate);

                            if (!$interviewScheduleUpdateQuery) {
                                echo "Update query failed: " . mysqli_error($databaseConnection);
                            }
                        } else {
                            $query = "select emailId from users where id=" . $json['userId'] . "";
                            $queryToCheckData = mysqli_query($databaseConnection, $query);
                            if (mysqli_num_rows($queryToCheckData) > 0) {
                                $emailId = mysqli_fetch_assoc($queryToCheckData)['emailId'];
                                $interviewScheduleUpdate = "UPDATE interviewSchedule SET interviewId='" . $interviewId . "', candidate_id='" . $userId . "' WHERE emailId='" . $emailId . "' AND company_id='" . $companyId . "' AND preInterviewId= '" . $preInterviewId . "' AND interviewId IS NULL";
                                // echo $interviewScheduleUpdate;
                                $interviewScheduleUpdateQuery = mysqli_query($databaseConnection, $interviewScheduleUpdate);

                                if (!$interviewScheduleUpdateQuery) {
                                    echo "Update query failed: ";
                                    //  . mysqli_error($databaseConnection);
                                }
                            } else {
                                echo "Error Finding User ";
                            }

                        }

                    } else {
                        // echo "not exists insert";
                        // echo $interviewId;
                        // exit();
                        // No data returned, insert into interviewSchedule
                        $interviewScheduleInsert = "INSERT INTO interviewSchedule (interviewId, candidate_id, company_id, preInterviewId,scheduleTime,firstScheduleDate) VALUES ('" . $interviewId . "', '" . $userId . "', '" . $companyId . "', '" . $preInterviewId . "',NOW(),NOW())";
                        $interviewScheduleInsertQuery = mysqli_query($databaseConnection, $interviewScheduleInsert);

                        if (!$interviewScheduleInsertQuery) {
                            // Insert query failed
                            echo "Insert query failed: " . mysqli_error($databaseConnection);
                        }
                    }
                } else {
                    // Query was not successful
                    echo "Query failed: " . mysqli_error($databaseConnection);
                }


                // shrikant added on 23/12/2023
                // $interviewScheduleUpdate="update interviewSchedule set interviewId='". $interviewId ."' where candidate_id='". $userId ."' and company_id='". $companyId ."' and preInterviewId= '". $preInterviewId ."'";
                // $interviewScheduleUpdateQuery = mysqli_query($databaseConnection, $interviewScheduleUpdate);


                $interviewNewData = "select i.*  from `interview` i  where i.id='" . $interviewId . "'";
                $interviewNewQuery = mysqli_query($databaseConnection, $interviewNewData);
                $values = mysqli_fetch_all($interviewNewQuery, MYSQLI_ASSOC);


                $newtutorial = "select * from `interview_tutorial` where interviewId='" . $interviewId . "' and isActive = 'Y'";
                $newtutorialQuery = mysqli_query($databaseConnection, $newtutorial);
                if (mysqli_num_rows($newtutorialQuery) >= 1) {
                    $newtutorialValues = mysqli_fetch_all($tutorialQuery, MYSQLI_ASSOC);
                    $values[0]['tutorialLink'] = $newtutorialValues;
                } else {
                    $values[0]['tutorialLink'] = null;
                }

                // sibin 2 sept 2022  get subject name in dynamic interview fr skip 
                for ($i = 0; $i < sizeof($questions); $i++) {
                    $id = $questions[$i]['subjectId'];
                    $subject = mysqli_query($databaseConnection, "select fs.favourite_subject from favourite_subject fs where fs.id in ($id)");
                    $subjectValue = mysqli_fetch_assoc($subject);
                    $questions[$i]['subjectName'] = $subjectValue;
                }
                $confirmQuery = "select AVConfirm from users where id = '" . $userId . "'";
                $confirmQueryResult = mysqli_query($databaseConnection, $confirmQuery);
                $confirmQueryValues = mysqli_fetch_all($confirmQueryResult, MYSQLI_ASSOC);
                $values[0]['isconfirmChecked'] = $confirmQueryValues[0]['AVConfirm'];

                $connecttomentorquery = mysqli_query($databaseConnection, "select pd.connecttomentor,pd.timetocontact,pd.connecttomentorname from professionaldetails pd where pd.candidateId  = '" . $userId . "'");
                $connecttomentorResult = mysqli_fetch_all($connecttomentorquery, MYSQLI_ASSOC);
                if ($connecttomentorResult[0]['connecttomentor'] != null && $connecttomentorResult[0]['timetocontact'] != null) {
                    $values[0]['connecttomentorsubmitted'] = 1;
                } else {
                    $values[0]['connecttomentorsubmitted'] = 0;
                }
                $resumeData = array(
                    'status' => -1,
                );
                $sessionId = array(
                    'sessionId' => round(microtime(true) * 1000)
                );
                $to_encode = $values;
                array_push($to_encode, $questions);
                array_push($to_encode, $interviewStructure);
                array_push($to_encode, $resumeData);
                array_push($to_encode, $sessionId);



            } else {
                $to_encode = array(
                    'result' => "error",
                    'errorCode' => "Interview Creation failed.",
                    'status' => 0
                );
            }

        }
        // 
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error where retrieving Question information."
        );
    }
    echo json_encode($to_encode);
}elseif (isset($_GET['createDynamicInterview2'])) {
    /* this method is written by Narayan for creating dynamic interview march 2022*/
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $companyId = $json['companyId'];
        $roleId = $json['roleId'];
        $productId = $json['productId'];
        $sectorId = $json['sectorId'];
        $userName = $json['userName'];
        $currentAssessmentType = $json['currentAssessmentType'];
        $preInterviewId = $json['preInterviewId'];

        // Handle Authentication and Authorization for Restricted preInterview
        // Ensure proper charset for correct escaping
        $databaseConnection->set_charset('utf8mb4'); // important when using real_escape_string [3]

        // ===== Block A: validate inputs and resolve userEmail (registered or guest) =====
        $preInterviewIdForAuth = null;
        if (isset($preInterviewId) && $preInterviewId !== '' && is_numeric($preInterviewId)) {
            $preInterviewIdForAuth = (int)$preInterviewId; // safe integer casting [4]
        }

        $userEmail = null;

        // If userId is present and numeric, try DB first (raw query)
        if (isset($userId) && $userId !== '' && is_numeric($userId)) {
            $userId = (int)$userId; // cast [4]
            $userEmailSql = "SELECT emailId FROM users WHERE id = {$userId} LIMIT 1";
            if ($res = mysqli_query($databaseConnection, $userEmailSql)) {
                if ($row = mysqli_fetch_assoc($res)) {
                    $userEmail = $row['emailId'];
                }
                mysqli_free_result($res); // free to avoid out-of-sync [7][11]
            } else {
                error_log("Query failed (userEmail): " . mysqli_error($databaseConnection));
            }
        }

        // Fallback: guest email from request body (validated)
        if ($userEmail === null && isset($json['email']) && is_string($json['email'])) {
            $candidateEmail = trim($json['email']);
            if (filter_var($candidateEmail, FILTER_VALIDATE_EMAIL)) {
                $userEmail = $candidateEmail;
            }
        }

        // Debug
        error_log("[CDI] inputs userId=" . var_export($userId,true) . ", preInterviewId=" . var_export($preInterviewId,true) . ", preInterviewIdForAuth=" . var_export($preInterviewIdForAuth,true));
        error_log("[CDI] userEmail(raw)=" . var_export($userEmail,true));

        // Optional: drain any pending extra results if earlier code used CALL/multi_query
        while (mysqli_more_results($databaseConnection) && mysqli_next_result($databaseConnection)) {
            if ($tmp = mysqli_store_result($databaseConnection)) { mysqli_free_result($tmp); }
        } // helps prevent out-of-sync after procedures [7][11]

        // ===== Block B: Restricted + Practice authorization (access = 'i') =====
        if ($preInterviewIdForAuth !== null) {
            // 1) Fetch flags
            $piId = (int)$preInterviewIdForAuth; // cast [4]
            $piSql = "SELECT restrictedOnly, interviewType FROM preInterview WHERE id = {$piId} LIMIT 1";
            $restrictedOnly = null; $interviewType = null;

            if ($res = mysqli_query($databaseConnection, $piSql)) {
                if ($row = mysqli_fetch_assoc($res)) {
                    $restrictedOnly = $row['restrictedOnly'];
                    $interviewType  = $row['interviewType'];
                }
                mysqli_free_result($res); // free before next query [7][11]
            } else {
                error_log("Query failed (piSql): " . mysqli_error($databaseConnection));
                echo "line 4977";
            }

            if ($restrictedOnly !== null) {
                $flag = strtoupper(trim((string)$restrictedOnly));
                if ($flag === '') { $flag = 'N'; }
                $isPractice = (strcasecmp((string)$interviewType, 'Practice') === 0);

                error_log("[CDI] flags restrictedOnly=" . var_export($restrictedOnly,true) . ", interviewType=" . var_export($interviewType,true));

                // 2) Only auth-check when restricted + practice
                if ($flag === 'Y' && $isPractice) {
                    if ($userEmail === null || $userEmail === '') {
                        echo json_encode(['result'=>'error','status'=>0,'errorCode'=>'Email required for authorization']);
                        exit;
                    }

                    // Normalize and escape email
                    $normEmail = strtolower(trim($userEmail));
                    $escEmail  = mysqli_real_escape_string($databaseConnection, $normEmail); // escape string [3]

                    // Safe integer cast already done for preInterviewId
                    $authSql = "
                        SELECT 1
                        FROM candidateInterviewMapping
                        WHERE preInterviewId = {$piId}
                        AND emailId = '{$escEmail}'
                        AND deleted = 'N'
                        AND access = 'i'
                        LIMIT 1";

                    if ($res = mysqli_query($databaseConnection, $authSql)) {
                        $rows = mysqli_num_rows($res);
                        mysqli_free_result($res); // free [7]

                        error_log("[CDI] auth rows=" . var_export($rows,true));

                        if ((int)$rows !== 1) {
                            echo json_encode([
                                'result' => 'error',
                                'status' => -2,
                                'errorCode' => 'UNAUTHORIZED ACCESS: Access denied.'
                            ]);
                            exit;
                        }
                    } else {
                        error_log("Query failed (authSql): " . mysqli_error($databaseConnection));
                        echo "line 4961";
                        // Soft-fail: proceed to keep legacy behavior
                    }
                }
                // else: open or not practice → proceed
            } else {
                // No preInterview row; soft-fail and proceed
            }
        }

        // ===== End Block B =====

        // existing logic....

        if (isset($json['interviewId']) && $json['interviewId'] !== '') {
            $interviewId = $json['interviewId'];
        } else {
            $interviewId = "";
        }

        if (!($interviewId == "")) {
            $interviewStructure = array();
            $questions = [];

            // get interviewStructure //
            $interviewStructure_sql = "SELECT DISTINCT sectionName
            FROM interview_questions_transection
            WHERE interviewId = $interviewId
            ORDER BY sequence";

            $result = mysqli_query($databaseConnection, $interviewStructure_sql);

            if ($result === false) {
                echo mysqli_error($databaseConnection);
            }

            if (mysqli_num_rows($result) > 0) {
                while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
                    array_push($interviewStructure, $row['sectionName']);
                }
            }



            // get questions //

            // iqt.id AS transactionId,
            // iqt.interviewId,
            // iqt.questionId,
            // iqt.sequence,


            // iqt.attemptStatus,
            // q.deleted_at AS questionDeletedAt,

            // SQL query
            $sql = "
            SELECT
                q.id,
                q.youtubeId,
                q.thumbnail,
                q.quesAudio,
                q.quesDiagram,
                q.scenario
                q.questionText,
                q.idk1,
                q.idk1Ans,
                q.idk2,
                q.idk2Ans,
                q.questionDesc,
                q.questionType,
                q.key_skill_id,
                q.topic_id,
                q.questionDuration,
                q.thinkingTime,
                q.answerDuration,
                q.extensionTime,
                q.streamId,
                q.isActive,
                q.isFollowUp,
                q.followUp,
                q.peerResponseVideo,
                q.expertApproval,
                q.priorityStatus,
                q.shortExpectedAns,
                q.questionLevel,
                q.isWbRequired,
                q.instruction,
                q.questionTag,
                q.source,
                q.eligibleStreamId,
                q.subjectId,
                q.conceptId,
                q.domainId,
                q.tutorialLink,
                q.remarks,
                q.peerResponseStatus,
                q.mbr_id,
                q.expertAdvice,
                q.questionCreator,
                q.questionReviewer,
                q.noOfImages,
                q.noOfVideos,
                q.updatedAt,
                q.clusterLevel,
                iqt.noOfSkip AS Skip,
                iqt.noOfRespond AS Respond,
                iqt.SectionName,
                fs.favourite_subject
            FROM
                interview_questions_transection AS iqt
            JOIN
                questions AS q ON iqt.questionId = q.id
            JOIN
                favourite_subject AS fs ON q.subjectId = fs.id
            WHERE
                iqt.interviewId = $interviewId;
            ";

            $result = mysqli_query($databaseConnection, $sql);

            if ($result === false) {
                die("Error executing query: " . mysqli_error($databaseConnection));
            }

            // $values1['clusterChild'] = 0;
            // $values1['childNumber'] = 0;
            // $values1['SectionName'] = $interviewStructure[$i]; 
            // $values1['DepthRequired'] = $sectionDepth[$i];
            // $values1['Skip'] = $totalSkipRequired[$i]; x
            // $values1['Respond'] = $totalRespondRequired[$i]; x
            // $values1['questionHtml'] = nl2br($values1['questionText']); x

            // Fetch result as an associative array
            while ($row = mysqli_fetch_assoc($result)) {

                $depthRequired = [];


                // get depthRequired for each question
                $depthRequired_sql = "SELECT 
                iqt.questionId,
                iqt.id,
                istr.depthRequired,
                iqt.interviewId,
                isec.id
                FROM
                interview_questions_transection iqt
                JOIN
                interviewSection isec ON iqt.sectionName = isec.name
                JOIN
                interviewStructure istr ON isec.id = istr.sectionId
                WHERE
                iqt.interviewId = '$interviewId' AND
                istr.preInterviewId = '$preInterviewId' AND
                iqt.questionId= '" . $row['id'] . "'";

                // echo $depthRequired_sql;


                $depthRequired_result = mysqli_query($databaseConnection, $depthRequired_sql);

                if ($depthRequired_result === false) {
                    die("Error executing query: " . mysqli_error($databaseConnection));
                }

                if (mysqli_num_rows($depthRequired_result) > 0) {
                    while ($depth = mysqli_fetch_array($depthRequired_result, MYSQLI_ASSOC)) {
                        $depthRequired[] = $depth['depthRequired'];
                    }
                }

                // var_dump($depthRequired);

                $row['DepthRequired'] = $depthRequired[0];
                $row['questionHtml'] = nl2br($row['questionText']);
                $questions[] = $row;
            }

            $questions = calculateChildInfo($questions);

            foreach ($questions as &$item) {
                // Check if "favourite_subject" is set
                if (isset($item['favourite_subject'])) {
                    // Rename the key and create a new "subjectName" array
                    $item['subjectName'] = ['favourite_subject' => $item['favourite_subject']];
                    // Remove the old key
                    unset($item['favourite_subject']);
                }
            }


            $interviewNewData = "select i.*  from `interview` i  where i.id='" . $interviewId . "'";
            $interviewNewQuery = mysqli_query($databaseConnection, $interviewNewData);
            $values = mysqli_fetch_all($interviewNewQuery, MYSQLI_ASSOC);


            $newtutorial = "select * from `interview_tutorial` where interviewId='" . $interviewId . "' and isActive = 'Y'";
            $newtutorialQuery = mysqli_query($databaseConnection, $newtutorial);
            if (mysqli_num_rows($newtutorialQuery) >= 1) {
                $newtutorialValues = mysqli_fetch_all($newtutorialQuery, MYSQLI_ASSOC);
                $values[0]['tutorialLink'] = $newtutorialValues;
            } else {
                $values[0]['tutorialLink'] = null;
            }

            $confirmQuery = "select AVConfirm from users where id = '" . $userId . "'";
            $confirmQueryResult = mysqli_query($databaseConnection, $confirmQuery);
            $confirmQueryValues = mysqli_fetch_all($confirmQueryResult, MYSQLI_ASSOC);
            $values[0]['isconfirmChecked'] = $confirmQueryValues[0]['AVConfirm'];

            $connecttomentorquery = mysqli_query($databaseConnection, "select pd.connecttomentor,pd.timetocontact,pd.connecttomentorname from professionaldetails pd where pd.candidateId  = '" . $userId . "'");
            $connecttomentorResult = mysqli_fetch_all($connecttomentorquery, MYSQLI_ASSOC);
            if ($connecttomentorResult[0]['connecttomentor'] != null && $connecttomentorResult[0]['timetocontact'] != null) {
                $values[0]['connecttomentorsubmitted'] = 1;
            } else {
                $values[0]['connecttomentorsubmitted'] = 0;
            }


            // resume interview data
            // $resumeQuery = "SELECT *
            //     FROM
            //         interview_questions_transection iqt
            //     WHERE
            //         interviewId = '$interviewId'
            //         AND
            //             attemptStatus IS NOT NULL
            //         AND sequence = (
            //         SELECT
            //             MAX(sequence)
            //         FROM
            //             interview_questions_transection
            //         WHERE
            //             interviewId = '$interviewId'
            //             AND attemptStatus IS NOT NULL)

            //         AND sequence < (
            //         SELECT
            //             MAX(sequence)
            //         FROM
            //             interview_questions_transection
            //         WHERE
            //             interviewId = '$interviewId')";


            // // echo $resumeQuery;

            // $resumeResult = mysqli_query($databaseConnection, $resumeQuery);

            // if (mysqli_num_rows($resumeResult) > 0) {

            //     // Rows were found, you can fetch the data
            //     while ($row = mysqli_fetch_assoc($resumeResult)) {
            //         $resumeData = array(
            //             'status' => 1,
            //             'result' => $row,
            //         );
            //     }


            // }else{
            //     $resumeData = array(
            //         'status' => -1,
            //     );
            // }

            $resumeQuery = "SELECT questionId as id, `sequence`, noOfRespond,sectionName,attemptStatus
            FROM interview_questions_transection iqt
            WHERE interviewId = '$interviewId' ";
            $result = mysqli_query($databaseConnection, $resumeQuery);

            if ($result) {
                $resumeData = array();

                while ($row = mysqli_fetch_assoc($result)) {
                    // echo $row;
                    $resumeData[] = $row;
                }

                if (!empty($resumeData)) {
                    $resumeData = array(
                        'status' => 1,
                        'result' => $resumeData,
                    );
                } else {
                    $resumeData = array(
                        'status' => -1,
                    );
                }
                // Free the result set
                mysqli_free_result($result);
            } else {
                $resumeData = array(
                    // 'qry' => "Error executing query: " . mysqli_error($databaseConnection),
                    'status' => -1,
                );
            }

            $sessionIdQuery = "SELECT interviewSessionId
            FROM feedback_request
            WHERE interviewId = '$interviewId' ";

            $result = mysqli_query($databaseConnection, $sessionIdQuery);

            if ($result) {
                if (mysqli_num_rows($result) > 0) {
                    $row = mysqli_fetch_assoc($result);
                    $sessionId = array(
                        'sessionId' => $row['interviewSessionId'],
                    );
                } else {
                    $sessionId = array(
                        'sessionId' => NULL,
                    );
                }

                mysqli_free_result($result);
            } else {
                // Handle the case where the query was not successful
                $error = mysqli_error($databaseConnection);
                // Log or output the error as needed
                $sessionId = array(
                    'sessionId' => NULL,
                    'error' => $error,
                );
            }

            $isExist_sql = "SELECT id FROM interviewSchedule WHERE interviewId = '" . $interviewId . "'";
            // echo $isExist_sql;
            $isExist_query = mysqli_query($databaseConnection, $isExist_sql);

            // Check if the query was successful and if it returned any rows
            if ($isExist_query) {
                $isExist_values = mysqli_fetch_all($isExist_query, MYSQLI_ASSOC);

                if (!empty($isExist_values)) {
                    // Data exists, update interviewSchedule
                } else {
                    // No data returned, insert into interviewSchedule
                    $interviewScheduleInsert = "INSERT INTO interviewSchedule (interviewId, candidate_id, company_id, preInterviewId,scheduleTime,firstScheduleDate) VALUES ('" . $interviewId . "', '" . $userId . "', '" . $companyId . "', '" . $preInterviewId . "',NOW(),NOW())";
                    $interviewScheduleInsertQuery = mysqli_query($databaseConnection, $interviewScheduleInsert);

                    if (!$interviewScheduleInsertQuery) {
                        // Insert query failed
                        echo "Insert query failed: " . mysqli_error($databaseConnection);
                    }
                }
            } else {
                // Query was not successful
                echo "Query failed: " . mysqli_error($databaseConnection);
            }

            // var_dump($questions);
            // var_dump($resumeData);

            $to_encode = $values;
            array_push($to_encode, $questions);
            array_push($to_encode, $interviewStructure);
            array_push($to_encode, $resumeData);
            array_push($to_encode, $sessionId);

        } else {
            // $company_fav_subjects = explode(',', $json['company_fav_subjects']);

            $subjects = $json['company_fav_subjects'];
            $topics = $json['topics'];

            $company_fav_subjects = array();

            foreach ($subjects as $item) {
                $key = key($item);
                $value = $item[$key];
                $company_fav_subjects[$key] = $value;
            }

            $result = array();
            /* this method is written for getting Subject  Sequence */

            //new methods for dynamic sections

            $SubjectSequence = getInterviewSubjectSequence_new($databaseConnection, $preInterviewId, $company_fav_subjects);

            // $topicSequence = getInterviewTopicSequence_new($databaseConnection,$preInterviewId,$SubjectSequence);

            // print_r($topics);
            if (empty($topics)) {
                $topicSequence = getInterviewTopicSequence_new($databaseConnection, $preInterviewId, $SubjectSequence);
            } else {
                $topicSequence = array_reduce($topics, function ($carry, $item) {
                    foreach ($item as $key => $value) {
                        if (isset($carry[$key])) {
                            $carry[$key] .= ',' . $value;
                        } else {
                            $carry[$key] = $value;
                        }
                    }
                    return $carry;
                }, array());

            }
            // print_r($topicSequence);
            // exit();


            $interviewStructure = getInterviewStructure_new($databaseConnection, $preInterviewId);

            $totalQuestionRequired = getTotalQuestionSectionWise_new($databaseConnection, $preInterviewId);

            $totalRespondRequired = getTotalRespondSectionWise_new($databaseConnection, $preInterviewId);

            $totalSkipRequired = getTotalSkipSectionWise_new($databaseConnection, $preInterviewId);

            $sectionDepth = getDepthRequiredSectionWise_new($databaseConnection, $preInterviewId);

            $clusterPreference = getClusterPreferenceSectionWise_new($databaseConnection, $preInterviewId);

            $questions = getQuestionsForDynamicInterview2($databaseConnection, $userId, $SubjectSequence, $interviewStructure, $totalQuestionRequired, $totalRespondRequired, $totalSkipRequired, $sectionDepth, $clusterPreference, $topicSequence);

            // echo json_encode($questions);
            // exit();

            $streamNameQuery = mysqli_query($databaseConnection, "select s.stream,s.id  from professionaldetails pd inner join stream s on pd.specialization = s.id where pd.candidateId ='" . $userId . "' ;");
            if (mysqli_num_rows($streamNameQuery) >= 1) {
                $streamNameResult = mysqli_fetch_assoc($streamNameQuery);
                $stream = $streamNameResult['stream'];
                $streamId = $streamNameResult['id'];
            } else {
                $stream = NULL;
                $streamId = NULL;
            }

            $SubjectNameQuery = mysqli_query($databaseConnection, "select fv.id from favourite_subject fv where  favourite_subject in (select name from sector where id = '" . $sectorId . "')");

            if ($SubjectNameQuery) {
                $SubjectNameResult = mysqli_fetch_assoc($SubjectNameQuery);
                $SubjectId = $SubjectNameResult['id'];
            } else {
                $SubjectNameQuery = mysqli_query($databaseConnection, "select fv.id from favourite_subject fv where  favourite_subject in (select name from sector where id = 1)");
                $SubjectNameResult = mysqli_fetch_assoc($SubjectNameQuery);
                $SubjectId = $SubjectNameResult['id'];
            }


            $roleNameQuery = mysqli_query($databaseConnection, "select name as Role ,DATE_FORMAT(NOW() ,'%D_%b_%Y_%T') as interviewDate from relavant_role  where id =  '" . $roleId . "' ");
            $interviewNameResult = mysqli_fetch_assoc($roleNameQuery);

            $interviewDate = $interviewNameResult['interviewDate'];
            if ($interviewDate == NULL) {
                $interviewDatelong = $round(microtime(true) * 1000);
                $interviewDate = date('d-m-Y H:i:s', $interviewDatelong);
            }
            $roleName = $interviewNameResult['Role'];

            if ($companyId != '') {
                $companyNameQuery = mysqli_query($databaseConnection, "select case when interviewName is null then (select name from aspiration_company where id=company_id) else interviewName end as name from preInterview where id ='" . $preInterviewId . "' ;");

                $companyNameResult = mysqli_fetch_assoc($companyNameQuery);
                $companyName = $companyNameResult['name'];
                $interviewName = $companyName . "_" . $userId . "_" . $interviewDate;

            } else {
                $sectorNameQuery = mysqli_query($databaseConnection, "select case when interviewName is null then (select name as sectorName from sector where id=sectorId) else interviewName end as sectorName from preInterview where id = '" . $preInterviewId . "';");
                $sectorNameResult = mysqli_fetch_assoc($sectorNameQuery);
                $sectorName = $sectorNameResult['sectorName'];
                $interviewName = $sectorName . "_" . $userId . "_Emp_" . $interviewDate;
            }

            $allQuestionId = array_column($questions, 'id');
            $questionIds = implode(',', $allQuestionId);

            $timeQuery = mysqli_query($databaseConnection, "SELECT SUM(answerDuration) as totalTime FROM `questions` WHERE id in ( $questionIds)");
            $timeResult = mysqli_fetch_assoc($timeQuery);



            $assessmentQuery = mysqli_query($databaseConnection, "SELECT group_concat(distinct ks.key_skill SEPARATOR ', ') as assessmentParameters FROM questions q, key_skill ks WHERE q.id in ( $questionIds) and FIND_IN_SET(ks.id, q.key_skill_id);");
            $assessmentResult = mysqli_fetch_assoc($assessmentQuery);
            if ($companyId != '') {
                $sql = "INSERT INTO `interview` (`categoryType`, `name`, `isActive`, `targetAudience`, `stream`, `duration`, `productId`, `assessmentParameters`, `createdBy`,`companyId`,`sector_id`,`subject_id`,`interviewLevel`,`roleId`,`assessmenttype`,`preInterviewId`) VALUES ('9', '" . addslashes($interviewName) . "', 'Y', '" . $stream . "', '" . $streamId . "', '" . roundMultipleOfX($timeResult['totalTime'], 5) . "', '" . $productId . "', '" . $assessmentResult['assessmentParameters'] . "', '$userId',$companyId,$sectorId,$SubjectId,'As per Industry Standard','" . $roleId . "','" . $currentAssessmentType . "','" . $preInterviewId . "')";

            } else {
                $sql = "INSERT INTO `interview` (`categoryType`, `name`, `isActive`, `targetAudience`, `stream`, `duration`, `productId`, `assessmentParameters`, `createdBy`,`sector_id`,`subject_id`,`interviewLevel`,`roleId`,`assessmenttype`,`preInterviewId`) VALUES ('9',  '" . addslashes($interviewName) . "', 'Y', '" . $stream . "', '" . $streamId . "', '" . roundMultipleOfX($timeResult['totalTime'], 5) . "', '" . $productId . "', '" . $assessmentResult['assessmentParameters'] . "', '$userId',$sectorId,$SubjectId,'As per Industry Standard','" . $roleId . "','" . $currentAssessmentType . "','" . $preInterviewId . "')";
            }
            $interviewQuery = mysqli_query($databaseConnection, $sql);

            if ($interviewQuery) {
                $interviewId = mysqli_insert_id($databaseConnection);
                $tutorialData = "SELECT q.tutorialLink,q.remarks,td.name as topicName from questions q left outer join topic td on q.topic_id = td.id where q.`tutorialLink` is not null and q.tutorialLink !='' and q.remarks is not null and q.remarks !='' and q.id in( $questionIds) group by q.tutorialLink";
                $tutorialQuery = mysqli_query($databaseConnection, $tutorialData);
                if (mysqli_num_rows($tutorialQuery) > 0) {
                    $numberOfLinks = mysqli_num_rows($tutorialQuery);
                    while ($row = mysqli_fetch_array($tutorialQuery, MYSQLI_ASSOC)) {
                        if (trim($row["tutorialLink"] != '')) {
                            $link = "INSERT INTO interview_tutorial(interviewId, tutorial_link, remarks, topic_name) VALUES ('" . $interviewId . "', '" . addslashes($row["tutorialLink"]) . "', '" . addslashes($row["remarks"]) . "', '" . addslashes($row["topicName"]) . "')";
                            mysqli_query($databaseConnection, $link);
                        }
                    }
                }
                for ($i = 0; $i < sizeof($questions); $i++) {
                    $quesSequesnce = "INSERT INTO interview_questions_transection(interviewId, questionId, sequence,sectionName,noOfRespond,noOfSKip) VALUES ('" . $interviewId . "', '" . addslashes($questions[$i]['id']) . "', '" . ($i + 1) . "', '" . $questions[$i]['SectionName'] . "','" . $questions[$i]['Respond'] . "','" . $questions[$i]['Skip'] . "')";
                    mysqli_query($databaseConnection, $quesSequesnce);
                }

                // sourabh - 04/01/24
                $isExist_sql = "SELECT id FROM interviewSchedule WHERE interviewId IS NULL AND preInterviewId = '" . $preInterviewId . "'";
                $isExist_query = mysqli_query($databaseConnection, $isExist_sql);

                // Check if the query was successful and if it returned any rows
                if ($isExist_query) {
                    $isExist_values = mysqli_fetch_all($isExist_query, MYSQLI_ASSOC);

                    if (!empty($isExist_values)) {
                        // echo "exists";
                        // echo $interviewId;
                        // echo $interviewScheduleUpdate;
                        // exit();

                        // Data exists, update interviewSchedule
                        $interviewScheduleSelect = "SELECT id FROM interviewSchedule WHERE candidate_id='" . $userId . "' AND company_id='" . $companyId . "' AND preInterviewId= '" . $preInterviewId . "' AND interviewId IS NULL";
                        $interviewScheduleSelectQuery = mysqli_query($databaseConnection, $interviewScheduleSelect);

                        if (mysqli_num_rows($interviewScheduleSelectQuery) > 0) {
                            $interviewScheduleUpdate = "UPDATE interviewSchedule SET interviewId='" . $interviewId . "' WHERE candidate_id='" . $userId . "' AND company_id='" . $companyId . "' AND preInterviewId= '" . $preInterviewId . "' AND interviewId IS NULL";
                            $interviewScheduleUpdateQuery = mysqli_query($databaseConnection, $interviewScheduleUpdate);

                            if (!$interviewScheduleUpdateQuery) {
                                echo "Update query failed: " . mysqli_error($databaseConnection);
                            }
                        } else {
                            $query = "select emailId from users where id=" . $json['userId'] . "";
                            $queryToCheckData = mysqli_query($databaseConnection, $query);
                            if (mysqli_num_rows($queryToCheckData) > 0) {
                                $emailId = mysqli_fetch_assoc($queryToCheckData)['emailId'];
                                $interviewScheduleUpdate = "UPDATE interviewSchedule SET interviewId='" . $interviewId . "', candidate_id='" . $userId . "' WHERE emailId='" . $emailId . "' AND company_id='" . $companyId . "' AND preInterviewId= '" . $preInterviewId . "' AND interviewId IS NULL";
                                // echo $interviewScheduleUpdate;
                                $interviewScheduleUpdateQuery = mysqli_query($databaseConnection, $interviewScheduleUpdate);

                                if (!$interviewScheduleUpdateQuery) {
                                    echo "Update query failed: ";
                                    //  . mysqli_error($databaseConnection);
                                }
                            } else {
                                echo "Error Finding User ";
                            }

                        }

                    } else {
                        // echo "not exists insert";
                        // echo $interviewId;
                        // exit();
                        // No data returned, insert into interviewSchedule
                        $interviewScheduleInsert = "INSERT INTO interviewSchedule (interviewId, candidate_id, company_id, preInterviewId,scheduleTime,firstScheduleDate) VALUES ('" . $interviewId . "', '" . $userId . "', '" . $companyId . "', '" . $preInterviewId . "',NOW(),NOW())";
                        $interviewScheduleInsertQuery = mysqli_query($databaseConnection, $interviewScheduleInsert);

                        if (!$interviewScheduleInsertQuery) {
                            // Insert query failed
                            echo "Insert query failed: " . mysqli_error($databaseConnection);
                        }
                    }
                } else {
                    // Query was not successful
                    echo "Query failed: " . mysqli_error($databaseConnection);
                }


                // shrikant added on 23/12/2023
                // $interviewScheduleUpdate="update interviewSchedule set interviewId='". $interviewId ."' where candidate_id='". $userId ."' and company_id='". $companyId ."' and preInterviewId= '". $preInterviewId ."'";
                // $interviewScheduleUpdateQuery = mysqli_query($databaseConnection, $interviewScheduleUpdate);


                $interviewNewData = "select i.*  from `interview` i  where i.id='" . $interviewId . "'";
                $interviewNewQuery = mysqli_query($databaseConnection, $interviewNewData);
                $values = mysqli_fetch_all($interviewNewQuery, MYSQLI_ASSOC);


                $newtutorial = "select * from `interview_tutorial` where interviewId='" . $interviewId . "' and isActive = 'Y'";
                $newtutorialQuery = mysqli_query($databaseConnection, $newtutorial);
                if (mysqli_num_rows($newtutorialQuery) >= 1) {
                    $newtutorialValues = mysqli_fetch_all($tutorialQuery, MYSQLI_ASSOC);
                    $values[0]['tutorialLink'] = $newtutorialValues;
                } else {
                    $values[0]['tutorialLink'] = null;
                }

                // sibin 2 sept 2022  get subject name in dynamic interview fr skip 
                for ($i = 0; $i < sizeof($questions); $i++) {
                    $id = $questions[$i]['subjectId'];
                    $subject = mysqli_query($databaseConnection, "select fs.favourite_subject from favourite_subject fs where fs.id in ($id)");
                    $subjectValue = mysqli_fetch_assoc($subject);
                    $questions[$i]['subjectName'] = $subjectValue;
                }
                $confirmQuery = "select AVConfirm from users where id = '" . $userId . "'";
                $confirmQueryResult = mysqli_query($databaseConnection, $confirmQuery);
                $confirmQueryValues = mysqli_fetch_all($confirmQueryResult, MYSQLI_ASSOC);
                $values[0]['isconfirmChecked'] = $confirmQueryValues[0]['AVConfirm'];

                $connecttomentorquery = mysqli_query($databaseConnection, "select pd.connecttomentor,pd.timetocontact,pd.connecttomentorname from professionaldetails pd where pd.candidateId  = '" . $userId . "'");
                $connecttomentorResult = mysqli_fetch_all($connecttomentorquery, MYSQLI_ASSOC);
                if ($connecttomentorResult[0]['connecttomentor'] != null && $connecttomentorResult[0]['timetocontact'] != null) {
                    $values[0]['connecttomentorsubmitted'] = 1;
                } else {
                    $values[0]['connecttomentorsubmitted'] = 0;
                }
                $resumeData = array(
                    'status' => -1,
                );
                $sessionId = array(
                    'sessionId' => round(microtime(true) * 1000)
                );
                $to_encode = $values;
                array_push($to_encode, $questions);
                array_push($to_encode, $interviewStructure);
                array_push($to_encode, $resumeData);
                array_push($to_encode, $sessionId);



            } else {
                $to_encode = array(
                    'result' => "error",
                    'errorCode' => "Interview Creation failed.",
                    'status' => 0
                );
            }

        }
        // 
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error where retrieving Question information."
        );
    }
    echo json_encode($to_encode);
}
elseif (isset($_GET['getIncompleteInterview'])) {
    // Author: sourabh 23/12/2023
    // Desc: checks if an incomplete interview exists for given preInterview
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $to_encode = array(
            'status' => -1,
            'result' => "success"
        );
        $userId = $json['userId'];
        $preInterviewId = $json['preInterviewId'];

        $interviewId;
        $incomplete = FALSE;

        $userId = mysqli_real_escape_string($databaseConnection, $userId);
        $preInterviewId = mysqli_real_escape_string($databaseConnection, $preInterviewId);

        // gets the interviewId by preInterviewId
        $interviewId_sql = "SELECT id
        FROM interview i
        WHERE createdBy = '" . $userId . "' AND preInterviewId = '" . $preInterviewId . "'
        ORDER BY id DESC
        LIMIT 1";

        $result = mysqli_query($databaseConnection, $interviewId_sql);
        if ($result) {
            $row = mysqli_fetch_assoc($result);
            if ($row) {
                $interviewId = $row['id'];
            } else {

                // echo "No interview found.";
                $interviewId = null;
                $to_encode = array(
                    'status' => -1,
                    'result' => "success",
                    // 'error' => mysqli_error($databaseConnection),
                    'msg' => "No Incomplete Interview found."
                );
            }
            mysqli_free_result($result);
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                // 'error' => mysqli_error($databaseConnection),
                'msg' => "Error while finding interview."
            );
        }
        if ($interviewId) {
            $incomplete_sql = "SELECT
                review_status
            FROM
            feedback_request fr
            WHERE
                fr.interviewId = '$interviewId'";

            $result = mysqli_query($databaseConnection, $incomplete_sql);

            if ($result) {
                while ($row = mysqli_fetch_assoc($result)) {
                    if ($row['review_status'] == -4) {
                        $incomplete = TRUE;
                    }
                }
                mysqli_free_result($result);
                if ($incomplete) {
                    $to_encode = array(
                        'status' => 1,
                        'result' => "success",
                        'data' => array(
                            "incompleteInterviewId" => $interviewId
                        )
                    );
                }
            } else {
                $to_encode = array(
                    'status' => 0,
                    'result' => "error",
                    'error' => mysqli_error($databaseConnection),
                    'msg' => "Error while finding the incomplete  interview status."
                );
            }
        }
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getIncompleteInterviewActivity'])) {
    // Author: sourabh 02/01/2024
    // Desc: checks if an incomplete interview exists and is active for given interviewid
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        // $to_encode = array(
        //     'status' => -1,
        //     'result' => "success"
        // );
        $to_encode;
        // $userId = $json['userId'];
        $interviewId = $json['interviewId'];

        $incomplete = FALSE;
        $inprogress = FALSE;

        // $userId = mysqli_real_escape_string($databaseConnection, $userId);
        $interviewId = mysqli_real_escape_string($databaseConnection, $interviewId);


        if ($interviewId) {
            $incomplete_sql = "SELECT
                review_status
            FROM
            feedback_request fr
            WHERE
                fr.interviewId = '$interviewId'";

            $result = mysqli_query($databaseConnection, $incomplete_sql);

            if ($result) {
                while ($row = mysqli_fetch_assoc($result)) {
                    if ($row['review_status'] == -4) {
                        $last_activity_at;
                        $last_active_sql = "SELECT last_activity_at FROM interview i WHERE i.id = '$interviewId'";
                        $last_active_result = mysqli_query($databaseConnection, $last_active_sql);
                        if ($last_active_result) {
                            while ($row = mysqli_fetch_assoc($last_active_result)) {
                                if ($row['last_activity_at'] != null) {
                                    $last_activity_at = $row['last_activity_at'];
                                } else {
                                    $last_activity_at = null;
                                }
                            }
                            mysqli_free_result($last_active_result);
                        }
                        // print_r($last_activity_at);
                        if ($last_activity_at != null) {
                            // echo gettype($last_activity_at);
                            $lastActivityDateTime = new DateTime($last_activity_at);

                            // Current date and time - 10 seconds
                            $currentDateTime = new DateTime();
                            $currentDateTime->modify('-60 seconds');

                            if ($currentDateTime > $lastActivityDateTime) {
                                // echo "The current time (after removing 10 seconds) is greater than the other time value.";
                                $incomplete = TRUE;
                            } else if ($currentDateTime < $lastActivityDateTime) {
                                // echo "The current time (after removing 10 seconds) is less than the other time value.";
                                $inprogress = TRUE;
                            }
                            //else {
                            //     echo "The current time (after removing 10 seconds) is equal to the other time value.";
                            // }
                        }
                    }
                }
                mysqli_free_result($result);
                // print_r($incomplete);
                // print_r($inprogress);
                if ($inprogress) {
                    $to_encode = array(
                        'status' => 'success',
                        'code' => "inprogress",
                        'data' => array(
                            "incompleteInterviewId" => $interviewId
                        )
                    );
                }
                if ($incomplete) {
                    $to_encode = array(
                        'status' => "success",
                        'code' => 'incomplete',
                        'data' => array(
                            "incompleteInterviewId" => $interviewId
                        )
                    );
                }
            } else {
                $to_encode = array(
                    'status' => 0,
                    'result' => "error",
                    'error' => mysqli_error($databaseConnection),
                    'msssage' => "Error while finding the incomplete  interview status."
                );
            }
        } else {
            $to_encode = array(
                'status' => -1,
                'result' => "error",
                'message' => "interviewId does not exist"
            );

        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['resetCookieData'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        // $userId = $json['userId'];
        try {
            $userData = getDecrypt($json['token']);
            if ($userData != 'Error') {
                $userId = $userData->userId;
            } else {
                throw new Exception('CookieManipulation');
            }
            $dataUser = "SELECT firstName,usertype,id FROM `users` WHERE id='" . $userId . "' ";
            $Userquery = mysqli_query($databaseConnection, $dataUser);
            if (mysqli_num_rows($Userquery) >= 1) {
                $userRow = mysqli_fetch_assoc($Userquery);
                $name = $userRow['firstName'];
                $userId = $userRow['id'];
                $userType = $userRow['usertype'];
                $to_encode = array(
                    'result' => "success",
                    'status' => "1",
                    'name' => $name,
                    'userId' => $userId,
                    'usertype' => $userType
                );
            } else {
                $to_encode = array(
                    'result' => "error",
                    'errorCode' => "user Id Not Exit.",
                    'status' => "0"
                );
            }
        } catch (Exception $e) {
            if ($e->getMessage() == "CookieManipulation") {
                $to_encode = array(
                    'result' => "error",
                    'errorCode' => "manipulation",
                    'status' => "-99",
                    'msg' => $e->getMessage(),
                );
            } else {
                $to_encode = array(
                    'result' => "error",
                    'errorCode' => "user Id does not exist.",
                    'status' => "-70",
                    'msg' => $e->getMessage(),
                );
            }
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Invalid user details.",
            'status' => '-1'
        );
    }
    echo json_encode($to_encode);

} elseif (isset($_GET['createInterview'])) {
    /*$data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {*/

    $categoryType = $_POST['categoryType'];
    //$panelId = $json['panelId'];
    $name = addslashes($_POST['name']);
    $description = addslashes($_POST['description']);
    $duration = addslashes($_POST['duration']);
    $interviewLevel = $_POST['interviewLevel'];
    $targetAudience = str_replace(',', ', ', $_POST['targetAudience']);
    $streamSql = "SELECT group_concat(s.id SEPARATOR ',') as streamName from stream s WHERE FIND_IN_SET(s.stream,'" . $_POST['targetAudience'] . "')";
    $streamResult = mysqli_query($databaseConnection, $streamSql);
    $streamRow = mysqli_fetch_array($streamResult, MYSQLI_ASSOC);
    $targetAudiences = $streamRow['streamName'];

    //$role = $json['role'];
    // $industry = explode(',', $_POST['industry']);
    $subject_id = $_POST['subjectId'];
    $productId = $_POST['productId'];
    $sectorId = $_POST['sectorId'];
    $companyId = $_POST['companyId'];
    $assment = $_POST['assessmentParameters'];
    $isActive = 'Y';

    $sqlAss = "SELECT group_concat(ks.key_skill SEPARATOR ',') as key_skill_name  FROM key_skill ks WHERE FIND_IN_SET(ks.id,'" . $assment . "')";
    $assResult = mysqli_query($databaseConnection, $sqlAss);
    $assRow = mysqli_fetch_array($assResult, MYSQLI_ASSOC);
    $assessmentParameters = str_replace(',', ', ', $assRow['key_skill_name']);
    $questionId = json_decode($_POST['questionId'], true);
    $candidate_emailId = addslashes($_POST['candidate_emailId']);
    //$questionIds = implode(',', array_column($questionId, 'id'));
    $questionIds = implode(',', array_map(function ($q) {
        return $q['id'];
    }, $questionId));
    $messages = array();
    if ($_POST['otherSubject'] != "") {
        $subjectQuery = mysqli_query($databaseConnection, "insert into favourite_subject(favourite_subject) values ('" . addslashes($_POST['otherSubject']) . "');");
        $subject_id = mysqli_insert_id($databaseConnection);
    }

    if ($_POST['othersCompanyName'] != "") {
        $othersCompanyName = mysqli_query($databaseConnection, "INSERT INTO `aspiration_company`(`name`) VALUES ('" . addslashes($_POST['othersCompanyName']) . "');");
        $companyId = mysqli_insert_id($databaseConnection);
    }
    if ($_POST['sectorId'] == "") {
        $getSector = mysqli_query($databaseConnection, "SELECT GROUP_CONCAT(DISTINCT sector) as sector FROM `scps_transaction` WHERE FIND_IN_SET(subject,(SELECT GROUP_CONCAT(questions.subjectId) as s_id FROM questions WHERE questions.id IN ($questionIds)));");
        $sectorId = mysqli_fetch_all($getSector, MYSQLI_ASSOC)[0]['sector'];
    }
    /*if ($_POST['otherConcept'] != "") {
            $conceptQuery = mysqli_query($databaseConnection, "insert into concepts(name, subject_id) values ('".addslashes($_POST['otherConcept'])."', '".$subject_id."');");
            $concept_id = mysqli_insert_id($databaseConnection);
        }*/
    /*if ($json['otherRole'] != "") {
            $relavantRoleQuery = mysqli_query($databaseConnection, "insert into relavant_role(name) values ('".$json['otherRole']."');");
            $relavantRoleId = mysqli_insert_id($databaseConnection);
            $role = $json['otherRole'];
        }*/
    /*if ($_POST['otherIndustry'] != "") {
            array_pop($industry);
            $json['otherIndustry'] = explode(",",$json['otherIndustry']);
            for($i=0; $i<count($json['otherIndustry']); $i++) {
                if(trim($json['otherIndustry'][$i]) != '') {
                    $domainQuery = mysqli_query($databaseConnection, "insert into favourite_domain(name) values ('".addslashes($json['otherIndustry'][$i])."');");
                    $domain_id = mysqli_insert_id($databaseConnection);
                    array_push($industry, $json['otherIndustry'][$i]);
                }
            }
        }*/




    $sql = "INSERT INTO `interview` (`categoryType`, `name`, `description`, `isActive`, `interviewLevel`, `targetAudience`, `duration`, `productId`, `subject_id`, `assessmentParameters`,`stream`,`sector_id`, `companyId`) VALUES ('$categoryType', '$name', '$description', '$isActive', '$interviewLevel', '" . $targetAudience . "', '$duration', '$productId', '$subject_id', '" . $assessmentParameters . "','" . $targetAudiences . "','$sectorId','$companyId')";


    $interviewQuery = mysqli_query($databaseConnection, $sql);
    if ($interviewQuery) {
        $interviewId = mysqli_insert_id($databaseConnection);
        $tutorialData = "SELECT q.tutorialLink,q.remarks,td.name as topicName from questions q left outer join topic td on q.topic_id = td.id where q.`tutorialLink` is not null and q.tutorialLink !='' and q.remarks is not null and q.remarks !='' and q.id in( $questionIds) group by q.tutorialLink";
        $tutorialQuery = mysqli_query($databaseConnection, $tutorialData);
        if (mysqli_num_rows($tutorialQuery) > 0) {
            $numberOfLinks = mysqli_num_rows($tutorialQuery);
            while ($row = mysqli_fetch_array($tutorialQuery, MYSQLI_ASSOC)) {
                if (trim($row["tutorialLink"] != '')) {
                    $link = "INSERT INTO interview_tutorial(interviewId, tutorial_link, remarks, topic_name) VALUES ('" . $interviewId . "', '" . addslashes($row["tutorialLink"]) . "', '" . addslashes($row["remarks"]) . "', '" . addslashes($row["topicName"]) . "')";
                    mysqli_query($databaseConnection, $link);
                }
            }
        }
        for ($i = 0; $i < sizeof($questionId); $i++) {
            $quesSequesnce = "INSERT INTO interview_questions_transection(interviewId, questionId, sequence) VALUES ('" . $interviewId . "', '" . addslashes($questionId[$i]['id']) . "', '" . ($i + 1) . "')";
            mysqli_query($databaseConnection, $quesSequesnce);

            $updateChildQues = "update questions set isFollowUp = '" . addslashes($questionId[$i]['isFollowUp']) . "' where id = '" . addslashes($questionId[$i]['id']) . "'";
            mysqli_query($databaseConnection, $updateChildQues);
        }
        $updateParentQues = "update questions set isFollowup = 'Y' where id in (select * from (select isFollowUp as ID from questions Q where isFollowUp REGEXP '^[0-9]+$' and id in (" . $questionIds . ")) as X) and isFollowup = 'N';";
        mysqli_query($databaseConnection, $updateParentQues);
        $updateFollowUpQuery = 'CALL updateFollowUp()';
        $updateFollowUp = mysqli_query($databaseConnection, $updateFollowUpQuery);
        $updateClusterLevel = updateClusterLevel($databaseConnection, $questionIds);

        if ($_POST['assignOrPublishInterview'] == 'publishInterview') {
            $sqlQuery = mysqli_query($databaseConnection, "select * from menu_subject_transection where menu_id = '" . $_POST['productId'] . "' and subject_id = '" . $subject_id . "'");
            if (mysqli_num_rows($sqlQuery) == 0) {
                $insertSqlQuery = mysqli_query($databaseConnection, "INSERT INTO `menu_subject_transection` (`menu_id`, `subject_id`) VALUES ('" . $_POST['productId'] . "', '" . $subject_id . "');");
                $menuInsertId = mysqli_insert_id($databaseConnection);
            }
        } else {
            //REPLACE('".$candidate_emailId."', ';', ','));
            $getCandidateId = mysqli_query($databaseConnection, "SELECT group_concat(u.id SEPARATOR ',') AS candidateId, group_concat(u.emailId SEPARATOR ',') as candidateEmails, group_concat(u.firstName SEPARATOR ',') as candidateNames FROM users u WHERE FIND_IN_SET(u.emailId, '" . $candidate_emailId . "');");
            $candidateId = mysqli_fetch_array($getCandidateId, MYSQLI_ASSOC);
            $assignInterviewQuery = mysqli_query($databaseConnection, "update menteelist set addedInterviewId = IFNULL( IF( FIND_IN_SET('" . $interviewId . "', addedInterviewId), addedInterviewId, CONCAT(addedInterviewId, ',', '" . $interviewId . "') ) , '" . $interviewId . "') where candidateId IN (" . $candidateId['candidateId'] . ");");

            $candidateEmails = explode(",", $candidateId['candidateEmails']);
            $candidateNames = explode(",", $candidateId['candidateNames']);

            for ($i = 0; $i < sizeof($candidateNames); $i++) {
                $message = "<p>Dear " . $candidateNames[$i] . ",</p>
                                <p>Please find your recommended practice interview below:</p>
                                <p>" . $name . ": " . $emailApiHost . "/interviewDetails?id=" . $interviewId . "</p>
                                <p>Please give this interview within 3 days so that we can arrange for your expert feedback.</p>
                                <p>In case of any doubt please contact us at 9731107508 / info@goprac.com</p>
                                <p>Regards,</p>
                                <p>GoPrac Team, Bangalore</p>
                                <p>Forum of Industry Professionals</p>
                                ";
                array_push($messages, $message);
            }
            sendEmailToMultiUser($candidateEmails, 'info@goprac.com', 'Greetings from GoPrac !', $messages);
        }

        $to_encode = array(
            'result' => "Success",
            'message' => "Interview Created.",
            'status' => 1,
            'interviewId' => $interviewId,
            'questionIds' => $questionIds,
            'query' => $tutorialData
        );
    } else {
        $checkSql = "SELECT * FROM `interview` WHERE name = '$name'";
        if (mysqli_num_rows(mysqli_query($databaseConnection, $checkSql)) > 0) {
            $to_encode = array(
                "status" => -2,
                "msg" => 'interview "' . $name . '" already exists'
            );
        } else {
            $to_encode = array(
                'result' => "error",
                'errorCode' => "Interview Creation failed.",
                'status' => 0,
                'query' => $sql,
            );
        }
    }
    /*} else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Interview Creation failed.",
            'status' => - 1,
            'query' => $sql
        );
    }*/
    echo json_encode($to_encode);
} elseif (isset($_GET['createInterviewByExpert'])) {
    $data = @file_get_contents("php://input");
    $_POST = json_decode($data, true);
    $categoryType = $_POST['categoryType'];
    $name = addslashes($_POST['name']);
    $description = addslashes($_POST['description']);
    $duration = addslashes($_POST['duration']);
    $interviewLevel = $_POST['interviewLevel'];
    $targetAudience = str_replace(',', ', ', $_POST['targetAudience']);
    $streamSql = "SELECT group_concat(s.id SEPARATOR ',') as streamName from stream s WHERE FIND_IN_SET(s.stream,'" . $_POST['targetAudience'] . "')";
    $streamResult = mysqli_query($databaseConnection, $streamSql);
    $streamRow = mysqli_fetch_array($streamResult, MYSQLI_ASSOC);
    $targetAudiences = $streamRow['streamName'];

    $subject_id = $_POST['subjectId'];
    $productId = $_POST['productId'];
    $assment = $_POST['assessmentParameters'];
    $isActive = 'Y';

    $sqlAss = "SELECT group_concat(ks.key_skill SEPARATOR ',') as key_skill_name  FROM key_skill ks WHERE FIND_IN_SET(ks.id,'" . $assment . "')";
    $assResult = mysqli_query($databaseConnection, $sqlAss);
    $assRow = mysqli_fetch_array($assResult, MYSQLI_ASSOC);
    $assessmentParameters = str_replace(',', ', ', $assRow['key_skill_name']);
    $questionId = json_decode($_POST['questionId'], true);
    $questionIds = implode(',', array_map(function ($q) {
        return $q['id'];
    }, $questionId));
    $messages = array();

    $sql = "INSERT INTO `interview` (`categoryType`, `name`, `description`, `isActive`, `interviewLevel`, `targetAudience`, `duration`, `productId`, `subject_id`, `assessmentParameters`,`stream`) VALUES ('$categoryType', '$name', '$description', '$isActive', '$interviewLevel', '" . $targetAudience . "', '$duration', '$productId', '$subject_id', '" . $assessmentParameters . "','" . $targetAudiences . "')";


    $interviewQuery = mysqli_query($databaseConnection, $sql);
    if ($interviewQuery) {
        $interviewId = mysqli_insert_id($databaseConnection);
        $tutorialData = "SELECT q.tutorialLink,q.remarks,td.name as topicName from questions q left outer join topic td on q.topic_id = td.id where q.`tutorialLink` is not null and q.tutorialLink !='' and q.remarks is not null and q.remarks !='' and q.id in( $questionIds) group by q.tutorialLink";
        $tutorialQuery = mysqli_query($databaseConnection, $tutorialData);
        if (mysqli_num_rows($tutorialQuery) > 0) {
            $numberOfLinks = mysqli_num_rows($tutorialQuery);
            while ($row = mysqli_fetch_array($tutorialQuery, MYSQLI_ASSOC)) {
                if (trim($row["tutorialLink"] != '')) {
                    $link = "INSERT INTO interview_tutorial(interviewId, tutorial_link, remarks, topic_name) VALUES ('" . $interviewId . "', '" . addslashes($row["tutorialLink"]) . "', '" . addslashes($row["remarks"]) . "', '" . addslashes($row["topicName"]) . "')";
                    mysqli_query($databaseConnection, $link);
                }
            }
        }
        for ($i = 0; $i < sizeof($questionId); $i++) {
            $quesSequesnce = "INSERT INTO interview_questions_transection(interviewId, questionId, sequence) VALUES ('" . $interviewId . "', '" . addslashes($questionId[$i]['id']) . "', '" . ($i + 1) . "')";
            mysqli_query($databaseConnection, $quesSequesnce);

            $updateChildQues = "update questions set isFollowUp = '" . addslashes($questionId[$i]['isFollowUp']) . "' where id = '" . addslashes($questionId[$i]['id']) . "'";
            mysqli_query($databaseConnection, $updateChildQues);
        }
        // $updateParentQues = "update questions set isFollowup = 'Y' where id in (select * from (select isFollowUp as ID from questions Q where isFollowUp REGEXP '^[0-9]+$' and id in (" . $questionIds . ")) as X) and isFollowup = 'N';";
        // mysqli_query($databaseConnection, $updateParentQues);
        // $updateFollowUpQuery = 'CALL updateFollowUp()';
        // $updateFollowUp = mysqli_query($databaseConnection, $updateFollowUpQuery);
        $query = "SELECT * FROM questions q JOIN questions_transection qt ON qt.questionId = q.id WHERE delegationType = 'peerResponseVideo' AND q.id IN (" . $questionIds . ");";
        $queryResult = mysqli_query($databaseConnection, $query);
        $queryValue = mysqli_fetch_all($queryResult, MYSQLI_ASSOC);

        $to_encode = array(
            'result' => "Success",
            'message' => "Interview Created.",
            'status' => 1,
            'interviewId' => $interviewId,
            'questionIds' => $questionIds,
            'data' => $queryValue,
            // 'query' => $tutorialData
        );
    } else {
        $checkSql = "SELECT * FROM `interview` WHERE name = '$name'";
        $checkSqlData = mysqli_query($databaseConnection, $checkSql);
        if (mysqli_num_rows($checkSqlData) > 0) {
            $checkSqlValue = mysqli_fetch_all($checkSqlData, MYSQLI_ASSOC);
            $query = "SELECT * FROM questions q JOIN questions_transection qt ON qt.questionId = q.id WHERE delegationType = 'peerResponseVideo' AND q.id IN (" . $questionIds . ");";
            $queryResult = mysqli_query($databaseConnection, $query);
            $queryValue = mysqli_fetch_all($queryResult, MYSQLI_ASSOC);
            $to_encode = array(
                "status" => -2,
                "msg" => 'interview "' . $name . '" already exists',
                "interviewId" => $checkSqlValue[0]['id'],
                "data" => $queryValue,
            );
        } else {
            $to_encode = array(
                'result' => "error",
                'errorCode' => "Interview Creation failed.",
                'status' => 0,
                'query' => $sql,
            );
        }
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['saveWhiteboardByExpert'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['candidateId'];
        $interviewId = $json['interviewId'];
        $questionId = $json['questionId'];
        $questionVideoId = $json['questionVideoId'];
        $candidateResponseId = $json['candidateResponseId'];
        $information = $json['information'];
        $streamId = $json['streamId'];
        $cropTime = $json['cropTime'];
        $publishStartTime = $json['publishStartTime'];
        $whiteboardStartTime = $json['whiteboardStartTime']; // by rp
        $interviewSessionId = $json['interviewSessionId'];
        $videoLength = $json['videoLength'];
        $totalTime = $json['totalTime'];
        $saidWords = $json['saidwords'];
        $checkQuery = "SELECT * FROM mergedVideos mv WHERE mv.interviewId = '$interviewId' AND mv.questionId = '$questionId' AND mv.candidateId = '$candidateId';";
        $checkQueryResult = mysqli_query($databaseConnection, $checkQuery);
        if (mysqli_num_rows($checkQueryResult) > 0) {
            $updateQuery = "UPDATE `mergedVideos` SET `outputVideoURL`='$streamId',`youtubeId`='$candidateResponseId',`vidLength`='$videoLength',`totalTime`='$totalTime' WHERE interviewId = '$interviewId' AND questionId = '$questionId' AND candidateId = '$candidateId'";
            $updateResult = mysqli_query($databaseConnection, $updateQuery);

            $to_encode = array(
                'result' => "Data Update Successfully",
                'status' => 4,
                'query' => $updateQuery,
            );
        } else {
            $query = "INSERT INTO `whiteboard` (`candidateId`, `interviewId`, `questionId`,`questionVideoId`,`streamId`,`cropTime`, `publishStartTime`, `interviewSessionId`, `whiteboardStartTime`) VALUES ('$candidateId', '$interviewId', '$questionId','$questionVideoId','$streamId','$cropTime','$publishStartTime','$interviewSessionId', '$whiteboardStartTime');";
            $whiteBoardQuery = mysqli_query($databaseConnection, $query);
            if ($whiteBoardQuery) {
                $whiteBoardId = mysqli_insert_id($databaseConnection);

                end($information[0]);
                $key = key($information[0]);
                $val = str_replace("'", "''", $information[0][$key]);
                $val = $information[0][$key];
                $whiteboardDetailsQuery = "INSERT INTO whiteboard_details (`whiteBoardId`, `time`, `text`) VALUES ('$whiteBoardId','$key','" . addslashes($val) . "');";
                mysqli_query($databaseConnection, $whiteboardDetailsQuery);

                flush();
                sleep(1);
                error_log("StreamId Before API Calling : " . $streamId, 0);

                $answerSubmitQuery = "INSERT INTO `mergedVideos` (`mergeId`, `created`, `mergeStatus`, `outputVideoURL`,`candidateId`, `interviewId`, `questionId`, `questionVideoId`,`uploadStatus`,`youtubeId`,`interviewSessionId`, `vidLength`, `totalTime`) VALUES (NULL, NOW(), NULL, '$streamId','$candidateId', '$interviewId', '$questionId', '$questionVideoId','SUCCESS','$candidateResponseId','$interviewSessionId', '$videoLength', '$totalTime');";
                mysqli_query($databaseConnection, $answerSubmitQuery);
                $mergeId = mysqli_insert_id($databaseConnection);

                $fileUploadqry = "INSERT INTO `file_upload_status`(`key`, `status`, `modified_date`) VALUES (" . $mergeId . ",'SUCCESS',now())";
                mysqli_query($databaseConnection, $fileUploadqry);

                $vidWatchQry = mysqli_query($databaseConnection, "INSERT INTO `video_watched_details`(`mergeId`, `saidWords`) VALUES ('$mergeId', NULLIF('" . addslashes(trim($saidWords)) . "', ''))");

                $to_encode = array(
                    'result' => "Success",
                    'message' => "Whiteboard Saved.",
                    'status' => 1,
                    'mergeId' => $mergeId,
                    'query' => $query,
                    'query1' => $answerSubmitQuery,
                    'query2' => $fileUploadqry,
                );
            } else {
                $to_encode = array(
                    'result' => "error",
                    'errorCode' => "Whiteboard save failed.",
                    'status' => 0,
                    'query' => $query,
                );
            }
        }

    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Panel Creation failed.",
            'status' => -1
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['requestInterviewFeedbackByExpert'])) {
    // This function is used for interview feedback
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $interviewId = $json['interviewId'];
        $candidateId = $json['candidateId'];
        $interviewSessionId = $json['interviewSessionId'];
        $userId = $json['userId'];
        $createdAt = $json['createdAt'];
        $contactDetails = array();
        $contact = array();

        $feedbackQuery = "SELECT * FROM `feedback_request` WHERE candidateId = '" . $candidateId . "' AND interviewSessionId = '" . $interviewSessionId . "' AND interviewId = '" . $interviewId . "'";
        $feedbackQueryResult = mysqli_query($databaseConnection, $feedbackQuery);

        if (mysqli_num_rows($feedbackQueryResult) > 0) {
            $query2 = "UPDATE feedback_request SET `review_status` = '-2' WHERE `interviewSessionId` = " . $interviewSessionId . " AND `candidateId` = " . $candidateId . " AND `interviewId` = " . $interviewId;
            $query2Result = mysqli_query($databaseConnection, $query2);
            if ($query2Result) {
                $to_encode = array(
                    'result' => "Success",
                    'message' => "Information Update  Successfully",
                    'status' => 1
                );
            } else {
                $to_encode = array(
                    'result' => "request feedback not success",
                    'message' => "Unable to request feedback",
                    'status' => -1
                );
            }
        } else {
            $query2 = "INSERT INTO `feedback_request`
                (`candidateId`,`interviewId`,`interviewSessionId`,`requestDate`,`review_status`,`createdBy`) VALUES('$candidateId','$interviewId','$interviewSessionId',NOW(),-2,'$userId');";
            $query2Result = mysqli_query($databaseConnection, $query2);
            if ($query2Result) {
                $to_encode = array(
                    'result' => "Success",
                    'message' => "Information Saved  Successfully",
                    'status' => 1
                );
            } else {
                $to_encode = array(
                    'result' => "request feedback not success",
                    'message' => "Unable to request feedback",
                    'status' => -1
                );
            }
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Request failed.",
            'status' => 0
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['createQuestion'])) {
    //$data = @file_get_contents("php://input");
    //$json = json_decode($data, true);
    //if (isset($json)) {
    $topic_id = $_POST['topic_id'];
    $youtubeId = $_POST['youtubeId'] == '' ? '314664775' : $_POST['youtubeId'];
    $thumbnail = $_POST['thumbnail'];
    $concept_id = $_POST['concept_id'];
    $subject_id = $_POST['subject_id'];
    //$domainId = explode(',', $_POST['domainId']);
    $isFollowUp = 'N';
    $expertApproval = $_POST['expertApproval'];
    $priorityStatus = $_POST['highPriority'];
    $thinkingTime = $_POST['thinkingTime'];

    if ($_POST['otherTopic'] != "") {
        $topicQuery = mysqli_query($databaseConnection, "insert into topic(name) values ('" . addslashes($_POST['otherTopic']) . "');");
        $topic_id = mysqli_insert_id($databaseConnection);
    }

    if ($_POST['otherSubject'] != "") {
        $subjectQuery = mysqli_query($databaseConnection, "insert into favourite_subject(favourite_subject, isActiveForMentorship) values ('" . addslashes($_POST['otherSubject']) . "', 'N');");
        $subject_id = mysqli_insert_id($databaseConnection);
    }

    if ($_POST['otherConcept'] != "") {
        $conceptQuery = mysqli_query($databaseConnection, "insert into concepts(name, subject_id) values ('" . addslashes($_POST['otherConcept']) . "', '" . $subject_id . "');");
        $concept_id = mysqli_insert_id($databaseConnection);
    }

    /*if ($_POST['otherIndustry'] != "") {
            array_pop($domainId);
            $_POST['otherIndustry'] = explode(",",$_POST['otherIndustry']);
            for($i=0; $i<count($_POST['otherIndustry']); $i++) {
                if(trim($_POST['otherIndustry'][$i]) != '') {
                    $domainQuery = mysqli_query($databaseConnection, "insert into favourite_domain(name) values ('".addslashes($_POST['otherIndustry'][$i])."');");
                    $domain_id = mysqli_insert_id($databaseConnection);
                    array_push($domainId, $domain_id);
                }
            }
        }*/

    $sql = "INSERT INTO `questions`(`youtubeId`,`thumbnail`,`thinkingTime`,`priorityStatus`, `questionText`, `key_skill_id`, `questionType`,`topic_id`, `answerDuration`, `isActive`, `isFollowUp`, `shortExpectedAns`, `questionLevel`, `isWbRequired`, `instruction`, `eligibleStreamId`, `subjectId`, `conceptId`, `tutorialLink`, `remarks`,`expertApproval`,`questionCreator`, `questionReviewer`, `noOfImages`, `noOfVideos`,`updatedAt`,`clusterLevel`) VALUES ('" . $youtubeId . "','" . $thumbnail . "','" . $thinkingTime . "','" . $priorityStatus . "','" . addslashes($_POST['questionText']) . "', '" . $_POST['keySkillId'] . "', '" . $_POST['questionType'] . "', NULLIF('" . $topic_id . "', 'null'), '" . $_POST['answerDuration'] . "', 'Y', '$isFollowUp', '" . addslashes($_POST['shortExpectedAns']) . "', '" . $_POST['questionLevel'] . "', '" . $_POST['isWbRequired'] . "', NULLIF('" . addslashes($_POST['instruction']) . "', ''), '" . $_POST['target_audience'] . "', '" . $subject_id . "', '" . $concept_id . "', '" . addslashes($_POST['tutorialLink']) . "', '" . addslashes($_POST['remarks']) . "','" . $expertApproval . "','" . $_POST['questionCreator'] . "','" . $_POST['questionReviewer'] . "','" . $_POST['noOfImages'] . "','" . $_POST['noOfVideos'] . "',NOW(),'" . $_POST['questionLevel'] . "');";
    $quesQuery = mysqli_query($databaseConnection, $sql);
    if ($quesQuery) {
        $quesId = mysqli_insert_id($databaseConnection);

        /*$timeQuery = mysqli_query($databaseConnection, "SELECT SUM(answerDuration) as totalTime FROM `questions` WHERE interviewId = '".$interviewId."'");
            $timeResult = mysqli_fetch_assoc($timeQuery);

            $updateDuration = mysqli_query($databaseConnection,"update interview set duration='".roundMultipleOf10($timeResult['totalTime'])."' where id='".$interviewId."'");*/

        $updateInterviewStatus = mysqli_query($databaseConnection, "update interview set isActive='N' where id IN (select interviewId from interview_questions_transection where questionId='" . $quesId . "'");

        if ($_FILES['quesDiagram']['name'] != "") {
            $filename = $quesId; //question id
            $extension = pathinfo($_FILES["quesDiagram"]["name"], PATHINFO_EXTENSION); //png
            $basename = $filename . '.' . $extension;
            $file_tmp = $_FILES['quesDiagram']['tmp_name'];
            move_uploaded_file($file_tmp, "../pracschool_app/public/interviewDiagram/" . $basename);
            $updateQuesDiagram = mysqli_query($databaseConnection, "update questions set quesDiagram='" . $basename . "' where id='" . $quesId . "'");
            $to_encode = array(
                'result' => "Success",
                'message' => "Question Created.",
                'status' => 1,
                'diagram' => $updateQuesDiagram
            );
        } else {
            $to_encode = array(
                'result' => "Success",
                'message' => "Question Created.",
                'status' => 1
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Question Creation failed.",
            'status' => -1,
            'query' => $sql
        );
    }
    /*} else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Question Creation failed.",
            'status' => - 1,
            'query' => $sql
        );
    }*/
    echo json_encode($to_encode);
} elseif (isset($_GET['saveExpertReview'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $interviewId = $json['interviewId'];
        // $youtubeId = $json['youtubeId'];
        $questionId = $json['questionId'];
        $candidateId = $json['candidateId'];
        $questionVideoId = $json['questionVideoId'];
        //$reviewParamValueId = $json['reviewParamValueId'];
        $streamId = $json['streamId'];
        $finalValueArr = $json['finalValuesArray'];
        $expert_review_suggestion = addslashes($json['expert_review_suggestion']);
        $insertedCount = 0;
        $expertReviewParamQry = "";
        $feedbackVideoURL = $json['feedbackVideoURL'];
        $isFeedbackVideoURLChanged = $json['isFeedbackVideoURLChanged'];
        $videoLength = $json['videoLength'];
        $currentFeedbackRequestId = $json['currentFeedbackRequestId'];
        $panelId = $json['panelId'];
        $expertReviewId = $json['expert_review_id'];
        $uploadStatus = $json['videoFeedbackSelection'] == true ? 'open' : 'SUCCESS';
        $currentPanelUserId = $json['currentPanelUserId'];
        $overallRating = $json['overallRating'];
        $isGvAvailable = $json['isGvAvailable'];
        $selectExpertReviewValues = array();

        $delegation_status = mysqli_query($databaseConnection, "select * from `feedback_request` where id='" . $currentFeedbackRequestId . "'");
        $delegation_status_result = mysqli_fetch_assoc($delegation_status);
        if ($delegation_status_result['review_status'] != '1') {
            $feedback_request_status_query = mysqli_query($databaseConnection, "UPDATE `feedback_request` SET `review_status` = '1' WHERE id=" . $currentFeedbackRequestId);
        }

        //in some condition, expertReviewId is 0 (frontend bug) even if expertReviewId is exist in the database
        $selectExperReviewResult = mysqli_query($databaseConnection, "select * from expert_review where feedback_request_id = '" . $currentFeedbackRequestId . "' and questionId = '" . $questionId . "'");
        if (mysqli_num_rows($selectExperReviewResult) > 0) {
            $selectExpertReviewValues = mysqli_fetch_array($selectExperReviewResult, MYSQLI_ASSOC);
            $expertReviewId = $selectExpertReviewValues['id'];
        } else {
            $selectExpertReviewValues['feedbackGivenBy'] = 0;
        }

        if ($expertReviewId == 0) {
            if ($isFeedbackVideoURLChanged) {
                $expertSql = "INSERT INTO `expert_review`(`interviewId`, `candidateId`, `feedbackGivenBy`, `questionId`, `questionVideoId`, `streamId`, feedback_request_id, expert_review_suggestion, feedbackVideoURL, vidLength, uploadStatus, overallRating,isGvAvailable) VALUES('$interviewId', '$candidateId', '$panelId', '$questionId', '$questionVideoId', '$streamId', $currentFeedbackRequestId, NULLIF('$expert_review_suggestion', ''), NULLIF('$feedbackVideoURL', ''), '$videoLength', 'open', '$overallRating','$isGvAvailable')";
            } else {
                $expertSql = "INSERT INTO `expert_review`(`interviewId`, `candidateId`, `feedbackGivenBy`, `questionId`, `questionVideoId`, `streamId`, feedback_request_id, expert_review_suggestion, overallRating) VALUES('$interviewId', '$candidateId', '$panelId', '$questionId', '$questionVideoId', '$streamId', $currentFeedbackRequestId, NULLIF('$expert_review_suggestion', ''), '$overallRating')";
            }
            $experReviewQuery = mysqli_query($databaseConnection, $expertSql);
            $expertReviewId = mysqli_insert_id($databaseConnection);
            $selectExpertReviewValues['feedbackGivenBy'] = $panelId;

            $feedbackStatusQuestionQuery = mysqli_query($databaseConnection, "update feedback_status_question set expertId = '$panelId' where feedbackRequestId = '$currentFeedbackRequestId' and expertId is null and review_status!=9 and questionId in (SELECT id FROM questions WHERE find_in_set(subjectId, (select areaOfExpertiseId from panel where id = '" . $panelId . "')))");

            $feedbackStatusQuestionQuery2 = mysqli_query($databaseConnection, "update feedback_status_question set review_status = 1 where feedbackRequestId = '$currentFeedbackRequestId' and questionId = '" . $questionId . "'");
        } else {
            if ($selectExpertReviewValues['feedbackGivenBy'] == $panelId || $delegation_status_result['delegationId'] == $panelId) {
                $experReviewQuery = mysqli_query($databaseConnection, 'DELETE FROM `expert_review_observation_details` where expertReviewId=' . $expertReviewId);

                if ($isFeedbackVideoURLChanged) {
                    $expert_review_suggestion_query = mysqli_query($databaseConnection, "update expert_review set expert_review_suggestion = NULLIF('$expert_review_suggestion', ''), feedbackGivenBy='$panelId', questionVideoId='$questionVideoId', feedbackVideoURL=NULLIF('$feedbackVideoURL', ''), vidLength='$videoLength', uploadStatus='open',isGvAvailable='$isGvAvailable', overallRating = '$overallRating' where id=" . $expertReviewId);
                } else {
                    $expert_review_suggestion_query = mysqli_query($databaseConnection, "update expert_review set expert_review_suggestion = NULLIF('$expert_review_suggestion', ''), feedbackGivenBy='$panelId', questionVideoId='$questionVideoId', overallRating = '$overallRating' where id=" . $expertReviewId);
                }

                $feedbackStatusQuestionQuery2 = mysqli_query($databaseConnection, "update feedback_status_question set review_status = 1 where feedbackRequestId = '$currentFeedbackRequestId' and questionId = '" . $questionId . "'");
            }
        }

        if ($isFeedbackVideoURLChanged) {
            $answerSubmitQuery = "INSERT INTO `mergedVideos` (`mergeId`, `candidateId`, `created`, `interviewId`, `outputVideoURL`, `questionId`, `uploadStatus`, `youtubeId`) VALUES (NULL, '$currentPanelUserId', NOW(), '$interviewId', '$feedbackVideoURL', '$questionId', '$uploadStatus', NULL);";
            $answerSubmitResult = mysqli_query($databaseConnection, $answerSubmitQuery);
        }


        if ($expertReviewId != 0 && ($delegation_status_result['delegationId'] == $panelId || $selectExpertReviewValues['feedbackGivenBy'] == $panelId)) {
            for ($i = 0; $i < sizeof($finalValueArr); $i++) {
                $value = $finalValueArr[$i];

                $expertReviewParamQry = "INSERT INTO expert_review_observation_details(expertReviewId, observationAreaId, observationValueId, message) VALUES ('" . $expertReviewId . "', NULLIF('" . $value['observationAreaId'] . "', ''), NULLIF('" . $value['observationValueId'] . "', ''), NULLIF('" . $value['message'] . "', ''))";
                $expertReviewParamQryResult = mysqli_query($databaseConnection, $expertReviewParamQry);
                $expertReviewParamDetailId = mysqli_insert_id($databaseConnection);
                if ($expertReviewParamDetailId > 0) {
                    $insertedCount = $insertedCount + 1;
                }
                $param_id = mysqli_insert_id($databaseConnection);
                $expertReviewParamQryResult = mysqli_query($databaseConnection, "update `expert_review` set review_param_valueId=" . $param_id . " where id=" . $expertReviewId);

                $updateObservationAreaIdQryResult = mysqli_query($databaseConnection, "UPDATE expert_review_observation_details erod INNER JOIN observation_values ov ON ov.id = erod.observationValueId SET erod.observationAreaId = ov.observation_id where erod.observationAreaId IS NULL AND erod.expertReviewId=" . $expertReviewId);

            }

            if ($overallRating == 'videoIssue') {
                $videoIssueExpertRated = mysqli_query($databaseConnection, "DELETE FROM `expert_review_observation_details` where feedback_request_id = '$currentFeedbackRequestId' and questionId = '" . $questionId . "'");
            } else {
                $videoIssueRobotRated = mysqli_query($databaseConnection, "UPDATE expert_review_observation_details set expertReviewId = '" . $expertReviewId . "' where feedback_request_id = '$currentFeedbackRequestId' and questionId = '" . $questionId . "'");
            }

            if ($insertedCount == sizeof($finalValueArr)) {
                $to_encode = array(
                    'result' => "Success",
                    'message' => "Expert Review Saved.",
                    'status' => 1,
                    'expertReviewId' => $expertReviewId,
                    'data' => $expertReviewId
                );
            } else {
                $to_encode = array(
                    'result' => "error",
                    'errorCode' => "Some review parameters may not be saved!.",
                    'status' => -1,
                    'submittedReviewParameters' => sizeof($finalValueArr),
                    'savedReviewParameters' => $insertedCount,
                    'query' => $expertReviewParamQry
                );
            }
        } else {
            $to_encode = array(
                'result' => "error",
                'errorCode' => "Feedback already saved by some other expert",
                'status' => 0
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Expert Review Creation failed.",
            'status' => -1
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['saveExpertVideoFeedback'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $interviewId = $json['interviewId'];
        $questionId = $json['questionId'];
        $candidateId = $json['candidateId'];
        $questionVideoId = $json['questionVideoId'];
        $feedbackVideoURL = $json['feedbackVideoURL'];
        $videoLength = $json['videoLength'];
        $isFeedbackVideoURLChanged = $json['isFeedbackVideoURLChanged'];
        $currentFeedbackRequestId = $json['currentFeedbackRequestId'];
        $panelId = $json['panelId'];
        $expertReviewId = $json['expert_review_id'];
        $uploadStatus = $json['videoFeedbackSelection'] == true ? 'open' : 'SUCCESS';
        $currentPanelUserId = $json['currentPanelUserId'];
        $isGvAvailable = $json['isGvAvailable'];
        $selectExpertReviewValues = array();

        $delegation_status = mysqli_query($databaseConnection, "select * from `feedback_request` where id='" . $currentFeedbackRequestId . "'");
        $delegation_status_result = mysqli_fetch_assoc($delegation_status);
        if ($delegation_status_result['review_status'] != '1') {
            $feedback_request_status_query = mysqli_query($databaseConnection, "UPDATE `feedback_request` SET `review_status` = '1' WHERE id=" . $currentFeedbackRequestId);
        }

        //in some condition, expertReviewId is 0 (frontend bug) even if expertReviewId is exist in the database
        $selectExperReviewResult = mysqli_query($databaseConnection, "select * from expert_review where feedback_request_id = '" . $currentFeedbackRequestId . "' and questionId = '" . $questionId . "'");
        if (mysqli_num_rows($selectExperReviewResult) > 0) {
            $selectExpertReviewValues = mysqli_fetch_array($selectExperReviewResult, MYSQLI_ASSOC);
            $expertReviewId = $selectExpertReviewValues['id'];
        } else {
            $selectExpertReviewValues['feedbackGivenBy'] = 0;
        }

        if ($expertReviewId == 0) {
            $expertSql = "INSERT INTO `expert_review`(`interviewId`, `candidateId`, `feedbackGivenBy`, `questionId`, `questionVideoId`, feedback_request_id, feedbackVideoURL, vidLength, uploadStatus,isGvAvailable) VALUES('$interviewId', '$candidateId', '$panelId', '$questionId', '$questionVideoId', $currentFeedbackRequestId, NULLIF('$feedbackVideoURL', ''), '$videoLength', 'open','$isGvAvailable')";
            $experReviewQuery = mysqli_query($databaseConnection, $expertSql);
            $expertReviewId = mysqli_insert_id($databaseConnection);
            $selectExpertReviewValues['feedbackGivenBy'] = $panelId;

            $feedbackStatusQuestionQuery = mysqli_query($databaseConnection, "update feedback_status_question set expertId = '$panelId' where feedbackRequestId = '$currentFeedbackRequestId' and expertId is null and questionId in (SELECT id FROM questions WHERE find_in_set(subjectId, (select areaOfExpertiseId from panel where id = '" . $panelId . "')))");

            $feedbackStatusQuestionQuery2 = mysqli_query($databaseConnection, "update feedback_status_question set review_status = 1 where feedbackRequestId = '$currentFeedbackRequestId' and questionId = '" . $questionId . "'");
        } else {
            if ($selectExpertReviewValues['feedbackGivenBy'] == $panelId) {
                $expert_review_suggestion_query = mysqli_query($databaseConnection, "update expert_review set feedbackGivenBy='$panelId', questionVideoId='$questionVideoId', feedbackVideoURL=NULLIF('$feedbackVideoURL', ''), vidLength='$videoLength', uploadStatus='open' ,isGvAvailable='$isGvAvailable' where id=" . $expertReviewId);

                $feedbackStatusQuestionQuery2 = mysqli_query($databaseConnection, "update feedback_status_question set review_status = 1 where feedbackRequestId = '$currentFeedbackRequestId' and questionId = '" . $questionId . "'");
            }
        }

        $answerSubmitQuery = "INSERT INTO `mergedVideos` (`mergeId`, `candidateId`, `created`, `interviewId`, `outputVideoURL`, `questionId`, `uploadStatus`, `youtubeId`) VALUES (NULL, '$currentPanelUserId', NOW(), '$interviewId', '$feedbackVideoURL', '$questionId', '$uploadStatus', NULL);";
        $answerSubmitResult = mysqli_query($databaseConnection, $answerSubmitQuery);

        if (($expertReviewId == 0) || ($expertReviewId != 0 && $selectExpertReviewValues['feedbackGivenBy'] == $panelId)) {
            if ($answerSubmitResult) {
                $to_encode = array(
                    'result' => "Success",
                    'message' => "Expert video feedback Saved.",
                    'status' => 1,
                    'expertReviewId' => $expertReviewId,
                    'feedbackVideoURL' => $feedbackVideoURL
                );
            } else {
                $to_encode = array(
                    'result' => "error",
                    'errorCode' => "Expert video feedback did not save.",
                    'status' => 0
                );
            }
        } else {
            $to_encode = array(
                'result' => "error",
                'errorCode' => "Feedback already saved by some other expert",
                'status' => 2
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Expert Video Feedback Creation failed.",
            'status' => -1
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['getFeedbackRequestList'])) {
    //This endpoint will be used to get the feedback request list
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $limit = 50;
        $start = 0;
        $panelId = $json['panelId'];
        $filter_query = ' ';
        $filter_queryQry = ' ';
        $filter_query_status = ' ';
        $filter_query_duration = ' ';
        $limit = $json['limit'];
        $start = ($json['page'] - 1) * $limit;
        $order_query = "";
        $limit_query = $limit == 0 ? "" : " limit " . $start . "," . $limit;

        if ($json['feedbackStatus'] != "") {
            $filter_query_status .= " and (questionStatusmax ='" . $json['feedbackStatus'] . "') ";
            // if ($json['feedbackStatus'] == "0" || $json['feedbackStatus'] == "1") {
            //     $filter_query_status .= " and (questionStatus ='" . $json['feedbackStatus'] . "') ";
            // } else {
            //     $filter_query_status .= " and fbr_status ='" . $json['feedbackStatus'] . "' ";
            // }
        }
        if ($json['feedbackStatus'] != "") {
            // $filter_query_duration .= " and fr.review_status ='" . $json['feedbackStatus'] . "' ";
            $filter_query_duration .= " and fsq.review_status ='" . $json['feedbackStatus'] . "' ";
        }
        if ($json['from_date'] != "" && $json['to_date'] == "") {
            $filter_query .= " and fr.updatedAt >= '" . $json['from_date'] . " 00:00:00' ";
            $filter_queryQry .= " and er.createdAt >= '" . $json['from_date'] . " 00:00:00' ";
        }
        if ($json['from_date'] == "" && $json['to_date'] != "") {
            $filter_query .= " and fr.updatedAt <= '" . $json['to_date'] . " 23:59:59' ";
            $filter_queryQry .= " and er.createdAt <= '" . $json['to_date'] . " 23:59:59' ";
        }
        if ($json['from_date'] != "" && $json['to_date'] != "") {
            $filter_query .= " and fr.updatedAt >= '" . $json['from_date'] . " 00:00:00' and fr.updatedAt <= '" . $json['to_date'] . " 23:59:59' ";
            $filter_queryQry .= " and er.createdAt >= '" . $json['from_date'] . " 00:00:00' and er.createdAt <= '" . $json['to_date'] . " 23:59:59' ";
        }
        if ($json['interviewPriority'] != "") {
            $filter_query .= " and fr.priority = '" . $json['interviewPriority'] . "' ";
            $filter_queryQry .= " and fr.priority = '" . $json['interviewPriority'] . "' ";
        }
        if ($json['studentName'] != "") {
            $filter_query .= " and u.firstName like '%" . $json['studentName'] . "%' ";
            $filter_queryQry .= " and u.firstName like '%" . $json['studentName'] . "%' ";
        }

        $totalCandidateVideoWatchResult = mysqli_query($databaseConnection, "select SEC_TO_TIME( SUM( TIME_TO_SEC( vwd.vidWatchedDuration ) ) ) AS vidLength from mergedVideos m inner join video_watched_details vwd on vwd.mergeId = m.mergeId inner join feedback_request fr on fr.interviewSessionId = m.interviewSessionId inner join expert_review er on er.feedback_request_id = fr.id and er.questionId = m.questionId INNER JOIN `feedback_status_question` fsq ON fsq.feedbackRequestId=fr.id AND fsq.questionId = er.questionId  inner join users u on u.id = fr.candidateId WHERE er.overallRating !='VideoIssue'  and er.review_type='question' and  er.feedbackGivenBy = '" . $panelId . "' " . $filter_queryQry . $filter_query_duration);
        $totalCandidateVideoWatchValues = mysqli_fetch_assoc($totalCandidateVideoWatchResult);

        $totalCandidateVideoResult = mysqli_query($databaseConnection, "select SEC_TO_TIME( SUM( TIME_TO_SEC( m.vidLength ) ) ) AS vidLength from mergedVideos m inner join feedback_request fr on fr.interviewSessionId = m.interviewSessionId inner join expert_review er on er.feedback_request_id = fr.id and er.questionId = m.questionId INNER JOIN `feedback_status_question` fsq ON fsq.feedbackRequestId=fr.id AND fsq.questionId=er.questionId inner join users u on u.id = fr.candidateId WHERE  er.overallRating !='VideoIssue'  and er.review_type='question' and er.feedbackGivenBy = '" . $panelId . "' " . $filter_queryQry . $filter_query_duration);
        $totalCandidateVideoValues = mysqli_fetch_assoc($totalCandidateVideoResult);

        $totalGivenFeedbackQuery = "select count(*) as totalGivenFeedback from (select er.id, er.feedbackGivenBy from expert_review_observation_details erod inner join observation_values ov on erod.observationValueId = ov.id inner join observation_area oa on ov.observation_id = oa.id inner join expert_review er on erod.expertReviewId = er.id inner join feedback_request fr on fr.id = er.feedback_request_id INNER JOIN `feedback_status_question` fsq ON er.feedback_request_id = fsq.feedbackRequestId AND er.questionId = fsq.questionId inner join users u on u.id = fr.candidateId where oa.key_skill != '0' and oa.is_final_parameters = 'N' and oa.id != '25' and er.feedbackGivenBy = '" . $panelId . "' " . $filter_queryQry . $filter_query_duration . " group by er.id) as temp";
        $totalGivenFeedbackResult = mysqli_query($databaseConnection, $totalGivenFeedbackQuery);
        $totalGivenFeedbackValues = mysqli_fetch_assoc($totalGivenFeedbackResult);

        $totalVideoFeedbackResult = mysqli_query($databaseConnection, "SELECT SEC_TO_TIME( SUM( TIME_TO_SEC( er.vidLength ) ) )  AS vidLength FROM expert_review er, feedback_request fr INNER JOIN `feedback_status_question` fsq ON fr.id = fsq.feedbackRequestId inner join users u on u.id = fr.candidateId WHERE fr.id = er.feedback_request_id AND fsq.questionId = er.questionId  and er.isGvAvailable='N'  and er.overallRating !='VideoIssue'  and er.review_type='question'  AND er.feedbackGivenBy = '" . $panelId . "' " . $filter_queryQry . $filter_query_duration);
        $totalVideoFeedbackValues = mysqli_fetch_assoc($totalVideoFeedbackResult);

        $totalIsGuidanceFeedbackResult = mysqli_query($databaseConnection, "SELECT  SEC_TO_TIME( SUM( TIME_TO_SEC( er.vidLength ) ) )  AS vidLength FROM expert_review er, feedback_request fr INNER JOIN `feedback_status_question` fsq ON fr.id = fsq.feedbackRequestId AND fsq.expertid = " . $panelId . " inner join users u on u.id = fr.candidateId WHERE fr.id = er.feedback_request_id and er.isGvAVailable='Y' and er.feedbackGivenBy = '" . $panelId . "' " . $filter_queryQry . $filter_query_duration);
        $totalIsGuidanceValues = mysqli_fetch_assoc($totalIsGuidanceFeedbackResult);

        $inProgress = mysqli_query($databaseConnection, "SELECT count(distinct(fsq.feedbackRequestId)) as count_review_status FROM `feedback_status_question` fsq inner join feedback_request fr on fr.id = fsq.feedbackRequestId LEFT JOIN expert_review er ON er.feedback_request_id = fsq.feedbackRequestId AND er.questionId = fsq.questionId where fsq.review_status in(0) and  fsq.expertId='" . $panelId . "' and fr.delegationId is null group by fsq.expertId");

        if (mysqli_num_rows($inProgress) > 0) {
            $reviwe_status = mysqli_fetch_assoc($inProgress);
            if ($reviwe_status != null) {
                $inProgressInterviewCount = $reviwe_status['count_review_status'];
            } else {
                $inProgressInterviewCount = 0;
            }
        } else {
            $inProgressInterviewCount = 0;
        }

        // added by keerthi for expert assessment more than 5 21 jun 2023
        $assessmentInProgress = mysqli_query($databaseConnection, "SELECT count(distinct(fsq.feedbackRequestId)) as count_review_status FROM feedback_status_question fsq inner join feedback_request fr on fr.id = fsq.feedbackRequestId LEFT JOIN expert_review er ON er.feedback_request_id = fsq.feedbackRequestId AND er.questionId = fsq.questionId where fsq.review_status in(1) and  fsq.expertId='" . $panelId . "'");

        if (mysqli_num_rows($assessmentInProgress) > 0) {
            $reviwe_status = mysqli_fetch_assoc($assessmentInProgress);
            if ($reviwe_status != null) {
                $inProgressAssessmentCount = $reviwe_status['count_review_status'];
            } else {
                $inProgressAssessmentCount = 0;
            }
        } else {
            $inProgressAssessmentCount = 0;
        }

        // added by keerthi for expert assessment more than 5

        /* $totalPayableFeedbackResult = mysqli_query($databaseConnection, "SELECT  SEC_TO_TIME( SUM( TIME_TO_SEC( er.vidLength ) ) )   AS vidLength FROM expert_review er, feedback_request fr WHERE fr.id = er.feedback_request_id and er.isGvAVailable='N' and er.feedbackGivenBy = '".$panelId."' ".$filter_query.$filter_query_duration);
        $totalPayableValues = mysqli_fetch_assoc($totalPayableFeedbackResult);*/

        $query = "select * from panel where id = '" . $panelId . "' and deleted_at is null";
        $result = mysqli_query($databaseConnection, $query);
        if (mysqli_num_rows($result) > 0) {
            $values = mysqli_fetch_assoc($result);
            $values['areaOfExpertiseId'] = $values['areaOfExpertiseId'] == '' ? 0 : $values['areaOfExpertiseId'];
            $isAssessmentApproved = $values['isAssessmentApproved'] == 'Y' ? ' OR (fsq.expertId is null and fsq.review_status!=2) ' : '';

            // $feedbackRequestQuery = "SELECT * FROM (SELECT fr.id AS feedbackRequestId, fr.delegationId, fr.interviewId, fr.candidateId, fr.interviewSessionId, fr.priority, CONCAT(u.firstName, ' ', IFNULL(u.lastName, '')) AS candidateName, fr.requestDate AS feedbackRequestDate, fr.review_status AS fbr_status, fr.updatedAt as feedbackDeliveryDate1,max(er.createdAt) as feedbackDeliveryDate, i.name AS interviewName, i.description AS interviewDescription, count(distinct case when fsq.expertId = '" . $panelId . "' then fsq.questionId when fsq.expertId is null then fsq.questionId else null end) as availableQuestion, max(fsq.review_status) as questionStatus,min(fsq.review_status) as questionStatusmin,max(fsq.review_status) as questionStatusmax FROM feedback_request fr inner join interview i on i.id = fr.interviewId inner join users u on u.id = fr.candidateId inner join feedback_status_question fsq on fsq.feedbackRequestId = fr.id inner join questions q on q.id = fsq.questionId LEFT JOIN expert_review er ON er.feedback_request_id = fsq.feedbackRequestId AND er.questionId = fsq.questionId where fr.review_status != -2 AND fr.review_status != -4 and fsq.review_status!=9 " . $filter_queryQry . " AND ((q.subjectId in (" . $values['areaOfExpertiseId'] . ") and fr.delegationId is null and (fsq.expertId = '" . $panelId . "' ".$isAssessmentApproved.")) or fr.delegationId = '" . $panelId . "' or fsq.expertId = '" . $panelId . "') group by fr.id order by fr.priority desc, fsq.review_status = 1 desc, fsq.review_status asc, fr.review_status = -3 desc, fr.id asc) AS temp where 1 " . $filter_query_status;

            // $feedbackRequestQuery = "SELECT * FROM (SELECT fr.id AS feedbackRequestId, fr.delegationId, fr.interviewId, fr.candidateId, fr.interviewSessionId, fr.priority, CONCAT(u.firstName, ' ', IFNULL(u.lastName, '')) AS candidateName, fr.requestDate AS feedbackRequestDate, fr.review_status AS fbr_status, fr.updatedAt as feedbackDeliveryDate1,max(er.createdAt) as feedbackDeliveryDate, i.name AS interviewName, i.description AS interviewDescription, count(distinct case when fsq.expertId = '" . $panelId . "' then fsq.questionId when fsq.expertId is null then fsq.questionId else null end) as availableQuestion, max(fsq.review_status) as questionStatus,min(fsq.review_status) as questionStatusmin,max(fsq.review_status) as questionStatusmax FROM feedback_request fr inner join interview i on i.id = fr.interviewId inner join users u on u.id = fr.candidateId inner join feedback_status_question fsq on fsq.feedbackRequestId = fr.id inner join questions q on q.id = fsq.questionId LEFT JOIN expert_review er ON er.feedback_request_id = fsq.feedbackRequestId AND er.questionId = fsq.questionId where fr.review_status != -2 and fsq.review_status!=9 and fsq.review_status !=10 " . $filter_queryQry . " AND ((q.subjectId in (" . $values['areaOfExpertiseId'] . ") and fr.delegationId is null and (fsq.expertId = '" . $panelId . "' ".$isAssessmentApproved.")) or fr.delegationId = '" . $panelId . "' or fsq.expertId = '" . $panelId . "') group by fr.id order by fr.priority desc, fsq.review_status = 1 desc, fsq.review_status asc, fr.review_status = -3 desc, fr.id asc) AS temp where 1 " . $filter_query_status . "UNION SELECT * FROM (SELECT fr.id AS feedbackRequestId, fr.delegationId, fr.interviewId, fr.candidateId, fr.interviewSessionId, fr.priority, CONCAT(u.firstName, ' ', IFNULL(u.lastName, '')) AS candidateName, fr.requestDate AS feedbackRequestDate, fr.review_status AS fbr_status, fr.updatedAt as feedbackDeliveryDate1,max(er.createdAt) as feedbackDeliveryDate, i.name AS interviewName, i.description AS interviewDescription, count(distinct case when fsq.expertId = '" . $panelId . "' then fsq.questionId when fsq.expertId is null then fsq.questionId else null end) as availableQuestion, max(fsq.review_status) as questionStatus,min(2) as questionStatusmin,max(2) as questionStatusmax FROM feedback_request fr inner join interview i on i.id = fr.interviewId inner join users u on u.id = fr.candidateId inner join feedback_status_question fsq on fsq.feedbackRequestId = fr.id inner join questions q on q.id = fsq.questionId LEFT JOIN expert_review er ON er.feedback_request_id = fsq.feedbackRequestId AND er.questionId = fsq.questionId where fr.review_status != -2 and fsq.review_status!=9 and fsq.review_status=10 " . $filter_queryQry . " AND ((q.subjectId in (" . $values['areaOfExpertiseId'] . ") and fr.delegationId is null and (fsq.expertId = '" . $panelId . "' ".$isAssessmentApproved.")) or fr.delegationId = '" . $panelId . "' or fsq.expertId = '" . $panelId . "') group by fr.id order by fr.priority desc, fsq.review_status = 1 desc, fsq.review_status asc, fr.review_status = -3 desc, fr.id asc) AS temp where 1 " . $filter_query_status;

            // Query is modified by vijay on 24 May 2023 based on tat time

            $feedbackRequestQuery = "SELECT * FROM (SELECT case when fr.review_status = 2 then TIMESTAMPDIFF(HOUR, fsq.createdAt, max(er.createdAt)) else TIMESTAMPDIFF(HOUR, fr.requestDate, NOW()) end AS hours_since_request,fr.id AS feedbackRequestId, fr.delegationId, fr.interviewId, fr.candidateId, fr.interviewSessionId, fr.priority, CONCAT(u.firstName, ' ', IFNULL(u.lastName, '')) AS candidateName, fr.requestDate AS feedbackRequestDate, fr.review_status AS fbr_status, fr.updatedAt as feedbackDeliveryDate1,max(er.createdAt) as feedbackDeliveryDate, i.name AS interviewName, i.description AS interviewDescription, count(distinct case when fsq.expertId = '" . $panelId . "' then fsq.questionId when fsq.expertId is null then fsq.questionId else null end) as availableQuestion, max(fsq.review_status) as questionStatus,min(fsq.review_status) as questionStatusmin,max(fsq.review_status) as questionStatusmax FROM feedback_request fr inner join interview i on i.id = fr.interviewId inner join users u on u.id = fr.candidateId inner join feedback_status_question fsq on fsq.feedbackRequestId = fr.id inner join questions q on q.id = fsq.questionId LEFT JOIN expert_review er ON er.feedback_request_id = fsq.feedbackRequestId AND er.questionId = fsq.questionId where fr.review_status != -2 and fsq.review_status!=9 and fsq.review_status !=10 " . $filter_queryQry . " AND ((q.subjectId in (" . $values['areaOfExpertiseId'] . ") and fr.delegationId is null and (fsq.expertId = '" . $panelId . "' " . $isAssessmentApproved . ")) or fr.delegationId = '" . $panelId . "' or fsq.expertId = '" . $panelId . "') group by fr.id order by fr.priority desc, fsq.review_status = 1 desc, fsq.review_status asc, fr.review_status = -3 desc, fr.id asc) AS temp where 1 " . $filter_query_status . "UNION SELECT * FROM (SELECT null as col1, fr.id AS feedbackRequestId, fr.delegationId, fr.interviewId, fr.candidateId, fr.interviewSessionId, fr.priority, CONCAT(u.firstName, ' ', IFNULL(u.lastName, '')) AS candidateName, fr.requestDate AS feedbackRequestDate, fr.review_status AS fbr_status, fr.updatedAt as feedbackDeliveryDate1,max(er.createdAt) as feedbackDeliveryDate, i.name AS interviewName, i.description AS interviewDescription, count(distinct case when fsq.expertId = '" . $panelId . "' then fsq.questionId when fsq.expertId is null then fsq.questionId else null end) as availableQuestion, max(fsq.review_status) as questionStatus,min(2) as questionStatusmin,max(2) as questionStatusmax FROM feedback_request fr inner join interview i on i.id = fr.interviewId inner join users u on u.id = fr.candidateId inner join feedback_status_question fsq on fsq.feedbackRequestId = fr.id inner join questions q on q.id = fsq.questionId LEFT JOIN expert_review er ON er.feedback_request_id = fsq.feedbackRequestId AND er.questionId = fsq.questionId where fr.review_status != -2 and fsq.review_status!=9 and fsq.review_status=10 " . $filter_queryQry . " AND ((q.subjectId in (" . $values['areaOfExpertiseId'] . ") and fr.delegationId is null and (fsq.expertId = '" . $panelId . "' " . $isAssessmentApproved . ")) or fr.delegationId = '" . $panelId . "' or fsq.expertId = '" . $panelId . "') group by fr.id order by fr.priority desc, fsq.review_status = 1 desc, fsq.review_status asc, fr.review_status = -3 desc, fr.id asc) AS temp where 1 " . $filter_query_status;

            $feedbackRequestQryResult = mysqli_query($databaseConnection, $feedbackRequestQuery . $limit_query);
            $feedbackReqArray = array();
            if (mysqli_num_rows($feedbackRequestQryResult) > 0) {
                $count_query = mysqli_query($databaseConnection, $feedbackRequestQuery);
                $count_result = mysqli_num_rows($count_query);

                while ($row = mysqli_fetch_array($feedbackRequestQryResult, MYSQLI_ASSOC)) {
                    $questions_query = mysqli_query($databaseConnection, "select interviewId, questionVideoId, interviewSessionId from mergedVideos where candidateId='" . $row['candidateId'] . "' and interviewId=" . $row['interviewId'] . " and interviewSessionId='" . $row['interviewSessionId'] . "'");
                    $row['attendedQuestions'] = mysqli_num_rows($questions_query);

                    $candidateVideoWatchResult = mysqli_query($databaseConnection, "select SEC_TO_TIME( SUM( TIME_TO_SEC( vwd.vidWatchedDuration ) ) ) AS vidLength from mergedVideos m inner join video_watched_details vwd on vwd.mergeId = m.mergeId inner join feedback_request fr on fr.interviewSessionId = m.interviewSessionId inner join expert_review er on er.feedback_request_id = fr.id and er.questionId = m.questionId WHERE er.overallRating !='VideoIssue'  and er.review_type='question' and er.feedbackGivenBy = '" . $panelId . "' and fr.id = '" . $row['feedbackRequestId'] . "'");
                    $candidateVideoResultWatchValues = mysqli_fetch_assoc($candidateVideoWatchResult);
                    $row['candidateVideoWatch'] = $candidateVideoResultWatchValues['vidLength'];

                    $candidateVideoResult = mysqli_query($databaseConnection, "select SEC_TO_TIME( SUM( TIME_TO_SEC( m.vidLength ) ) ) AS vidLength from mergedVideos m inner join feedback_request fr on fr.interviewSessionId = m.interviewSessionId inner join expert_review er on er.feedback_request_id = fr.id and er.questionId = m.questionId WHERE er.overallRating !='VideoIssue'  and er.review_type='question' and er.feedbackGivenBy = '" . $panelId . "' and fr.id = '" . $row['feedbackRequestId'] . "'");
                    $candidateVideoResultValues = mysqli_fetch_assoc($candidateVideoResult);
                    $row['candidateVideo'] = $candidateVideoResultValues['vidLength'];

                    $videoFeedbackResult = mysqli_query($databaseConnection, "SELECT SEC_TO_TIME( SUM( TIME_TO_SEC( er.vidLength ) ) ) AS vidLength FROM expert_review er, feedback_request fr WHERE fr.id = er.feedback_request_id and er.feedbackGivenBy = '" . $panelId . "' and er.isGvAvailable='N'  and er.overallRating !='VideoIssue' AND fr.id = '" . $row['feedbackRequestId'] . "'");
                    $videoFeedbackValues = mysqli_fetch_assoc($videoFeedbackResult);
                    $row['videoFeedback'] = $videoFeedbackValues['vidLength'];

                    $isGvideoFeedbackResult = mysqli_query($databaseConnection, "SELECT  SEC_TO_TIME( SUM( TIME_TO_SEC( er.vidLength ) ) ) AS vidLength FROM expert_review er, feedback_request fr WHERE fr.id = er.feedback_request_id and er.isGvAvailable = 'Y' and  er.feedbackGivenBy = '" . $panelId . "' and fr.id = '" . $row['feedbackRequestId'] . "'");
                    $isGvideoFeedbackValues = mysqli_fetch_assoc($isGvideoFeedbackResult);
                    $row['isGvideoFeedback'] = $isGvideoFeedbackValues['vidLength'];

                    /* $payableVideoFeedbackResult = mysqli_query($databaseConnection, "SELECT SEC_TO_TIME( SUM( TIME_TO_SEC( er.vidLength ) ) ) AS vidLength FROM expert_review er, feedback_request fr WHERE fr.id = er.feedback_request_id and  er.isGvAvailable = 'N' and er.feedbackGivenBy = '".$panelId."' and fr.id = '".$row['feedbackRequestId']."'");
                    $payableVideoFeedbackValues = mysqli_fetch_assoc($payableVideoFeedbackResult);
                    $row['payableVideoFeedback'] = is_null($payableVideoFeedbackValues['vidLength']) ? '00:00:00':$payableVideoFeedbackValues['vidLength'];*/

                    $givenFeedbackQuery = "select count(*) as totalGivenFeedback from (select er.id, er.feedbackGivenBy from expert_review_observation_details erod inner join observation_values ov on erod.observationValueId = ov.id inner join observation_area oa on ov.observation_id = oa.id inner join expert_review er on erod.expertReviewId = er.id inner join feedback_request fr on fr.id = er.feedback_request_id where oa.key_skill != '0' and oa.is_final_parameters = 'N' and oa.id != '25' and er.feedbackGivenBy = '" . $panelId . "' and er.feedback_request_id = '" . $row['feedbackRequestId'] . "' group by er.id) as temp";
                    $givenFeedbackResult = mysqli_query($databaseConnection, $givenFeedbackQuery);
                    $givenFeedbackValues = mysqli_fetch_assoc($givenFeedbackResult);
                    $row['givenFeedback'] = $givenFeedbackValues['totalGivenFeedback'];

                    array_push($feedbackReqArray, $row);
                }
                $to_encode = array(
                    'feedbackRequestArray' => $feedbackReqArray,
                    'totalGivenFeedback' => $totalGivenFeedbackValues['totalGivenFeedback'],
                    'totalVideoFeedback' => $totalVideoFeedbackValues['vidLength'],
                    'isGvAvailableFeedback' => $totalIsGuidanceValues['vidLength'],
                    //'totalPayableFeedback' =>$totalPayableValues['vidLength'],
                    'totalCandidateVideo' => $totalCandidateVideoValues['vidLength'],
                    'totalCandidateVideoWatch' => $totalCandidateVideoWatchValues['vidLength'],
                    'totalInprogressInterviewCount' => $inProgressInterviewCount,
                    'ratePerQuestion' => $values['feedbackRatePerQuestion'],
                    'expertName' => $values['name'],
                    'status' => 1,
                    'count' => $count_result,
                    'QRY' => $feedbackRequestQuery,
                    'totalInprogressAssessmentCount' => $inProgressAssessmentCount
                );
            } else {
                $to_encode = array(
                    'feedbackRequestArray' => $feedbackReqArray,
                    'totalGivenFeedback' => 0,
                    'totalVideoFeedback' => null,
                    'totalCandidateVideoWatch' => null,
                    'ratePerQuestion' => $values['feedbackRatePerQuestion'],
                    'expertName' => $values['name'],
                    'status' => 0,
                    'count' => 0,
                    'QRY' => $feedbackRequestQuery,
                    'totalInprogressAssessmentCount' => $inProgressAssessmentCount
                );
            }
        } else {
            $to_encode = array(
                'feedbackRequestArray' => [],
                'totalGivenFeedback' => 0,
                'totalVideoFeedback' => null,
                'ratePerQuestion' => 0,
                'expertName' => '',
                'status' => 0,
                'count' => 0
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Request for getting feedback request Failed.",
            'status' => -1
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['getExpertAccountList'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        //$limit = 50;
        $start = 0;
        $userId = $json['userId'];
        $expert_filter_query = ' ';
        $filter_query = ' ';
        $filter_type = ' ';
        $limit = $json['limit'];
        $start = ($json['page'] - 1) * $limit;
        $order_query = "";
        $limit_query = $limit == 0 ? "" : " limit " . $start . "," . $limit;
        $values = array();

        if ($json['expertName'] != "")
            $expert_filter_query .= " and p.name LIKE '%" . $json['expertName'] . "%' ";

        if ($json['from_date'] != "" && $json['to_date'] == "")
            $filter_query .= " and fr.updatedAt >= '" . $json['from_date'] . " 00:00:00' ";
        if ($json['from_date'] == "" && $json['to_date'] != "")
            $filter_query .= " and fr.updatedAt <= '" . $json['to_date'] . " 23:59:59' ";
        if ($json['from_date'] != "" && $json['to_date'] != "")
            $filter_query .= " and fr.updatedAt >= '" . $json['from_date'] . " 00:00:00' and fr.updatedAt <= '" . $json['to_date'] . " 23:59:59' ";

        $query = "select p.*,u.id as candidateId from panel p inner join users u on p.id = u.panelId  where p.deleted_at is NULL " . $expert_filter_query . " order by p.name ";
        $result = mysqli_query($databaseConnection, $query . $limit_query);
        //$values = mysqli_fetch_assoc($result);

        if (mysqli_num_rows($result) > 0) {
            $count_query = mysqli_query($databaseConnection, $query);
            $count_result = mysqli_num_rows($count_query);

            while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
                $totalGivenFeedbackQuery = "select count(*) as totalGivenFeedback from (select er.id, er.feedbackGivenBy from expert_review_observation_details erod inner join observation_values ov on erod.observationValueId = ov.id inner join observation_area oa on ov.observation_id = oa.id inner join expert_review er on erod.expertReviewId = er.id inner join feedback_request fr on fr.id = er.feedback_request_id where oa.key_skill != '0' and oa.is_final_parameters = 'N' and oa.id != '25' and fr.review_status = '2' and er.feedbackGivenBy = '" . $row['id'] . "' " . $filter_query . " group by er.id) as temp";
                $totalGivenFeedbackResult = mysqli_query($databaseConnection, $totalGivenFeedbackQuery);
                $totalGivenFeedbackValues = mysqli_fetch_assoc($totalGivenFeedbackResult);
                if ($json['workDone'] == "" || $json['workDone'] == "personalizedFeedback") {
                    $row['totalGivenFeedback'] = $totalGivenFeedbackValues['totalGivenFeedback'];
                } else {
                    $row['totalGivenFeedback'] = '0';
                }

                $totalVideoFeedbackResult = mysqli_query($databaseConnection, "SELECT  SEC_TO_TIME( SUM( TIME_TO_SEC( er.vidLength ) ) ) AS vidLength FROM expert_review er, feedback_request fr WHERE fr.id = er.feedback_request_id AND er.isGvAvailable='N' AND fr.review_status = '2' AND er.feedbackGivenBy = '" . $row['id'] . "' " . $filter_query);
                $totalVideoFeedbackValues = mysqli_fetch_assoc($totalVideoFeedbackResult);
                if ($json['workDone'] == "" || $json['workDone'] == "personalizedFeedback") {
                    //$row['totalVideoFeedback'] = is_null($totalVideoFeedbackValues['vidLength'])?'00:00:00':$totalVideoFeedbackValues['vidLength'];
                    $row['totalVideoFeedback'] = $totalVideoFeedbackValues['vidLength'];
                } else {
                    $row['totalVideoFeedback'] = '00:00:00';
                }

                $totalGvAvailableResult = mysqli_query($databaseConnection, "SELECT SEC_TO_TIME( SUM( TIME_TO_SEC( er.vidLength ) ) ) AS vidLength FROM expert_review er, feedback_request fr WHERE fr.id = er.feedback_request_id AND  er.isGvAvailable='Y' AND fr.review_status = '2' AND er.feedbackGivenBy = '" . $row['id'] . "' " . $filter_query);
                $totalGvAvailableValues = mysqli_fetch_assoc($totalGvAvailableResult);
                if ($json['workDone'] == "" || $json['workDone'] == "personalizedFeedback") {
                    //$row['totalGvAvailableFeedback'] =  is_null($totalGvAvailableValues['vidLength'])?'00:00:00':$totalGvAvailableValues['vidLength'];
                    $row['totalGvAvailableFeedback'] = $totalGvAvailableValues['vidLength'];
                } else {
                    $row['totalGvAvailableFeedback'] = '00:00:00';
                }

                /*if($row['totalVideoFeedback'] == '00:00:00') {
                    $row['totalPayableVideoFeedback'] = '00:00:00';
                } else if( $row['totalGvAvailableFeedback'] == '00:00:00') {
                    $row['totalPayableVideoFeedback'] = $row['totalVideoFeedback'];
                } else {
                    $totalPayableFeedbackResult = mysqli_query($databaseConnection, "SELECT  SEC_TO_TIME( SUM( TIME_TO_SEC( er.vidLength ) ) )   AS vidLength FROM expert_review er, feedback_request fr WHERE fr.id = er.feedback_request_id and er.isGvAVailable='N' and fr.review_status = '2' and er.feedbackGivenBy = '".$row['id']."' ".$filter_query);
                    $totalPayableValues = mysqli_fetch_assoc($totalPayableFeedbackResult);
                    $row['totalPayableVideoFeedback'] = $totalPayableValues['vidLength'];
                }*/

                $totalCandidateVideoWatchResult = mysqli_query($databaseConnection, "select SEC_TO_TIME( SUM( TIME_TO_SEC( vwd.vidWatchedDuration ) ) ) AS vidLength from mergedVideos m inner join video_watched_details vwd on vwd.mergeId = m.mergeId inner join feedback_request fr on fr.interviewSessionId = m.interviewSessionId inner join expert_review er on er.feedback_request_id = fr.id and er.questionId = m.questionId WHERE fr.review_status = '2' and er.feedbackGivenBy = '" . $row['id'] . "' " . $filter_query);
                $totalCandidateVideoWatchValues = mysqli_fetch_assoc($totalCandidateVideoWatchResult);
                if ($json['workDone'] == "" || $json['workDone'] == "personalizedFeedback") {
                    $row['totalCandidateVideoWatch'] = $totalCandidateVideoWatchValues['vidLength'];
                } else {
                    $row['totalCandidateVideoWatch'] = '00:00:00';
                }
                $totalCandidateVideoResult = mysqli_query($databaseConnection, "select SEC_TO_TIME( SUM( TIME_TO_SEC( m.vidLength ) ) ) AS vidLength from mergedVideos m inner join feedback_request fr on fr.interviewSessionId = m.interviewSessionId inner join expert_review er on er.feedback_request_id = fr.id and er.questionId = m.questionId WHERE fr.review_status = '2' and er.feedbackGivenBy = '" . $row['id'] . "' " . $filter_query);
                $totalCandidateVideoValues = mysqli_fetch_assoc($totalCandidateVideoResult);
                if ($json['workDone'] == "" || $json['workDone'] == "personalizedFeedback") {
                    $row['totalCandidateVideo'] = $totalCandidateVideoValues['vidLength'];
                } else {
                    $row['totalCandidateVideo'] = '00:00:00';
                }

                $questionVideoResult = mysqli_query($databaseConnection, "SELECT count(fr.vidLength) as totalQuestion, SEC_TO_TIME( SUM( TIME_TO_SEC( fr.vidLength ) ) ) AS vidLength FROM questions_transection fr where fr.delegationType = 'questionVideo' and fr.uploadStatus = 2 and fr.expertId = '" . $row['id'] . "' " . $filter_query);
                $questionVideoValues = mysqli_fetch_assoc($questionVideoResult);
                if ($json['workDone'] == "" || $json['workDone'] == "questionVideo") {
                    $row['totalQuestionVideoLength'] = $questionVideoValues['vidLength'];
                    $row['totalQuestionVideo'] = $questionVideoValues['totalQuestion'];
                } else {
                    $row['totalQuestionVideoLength'] = '00:00:00';
                    $row['totalQuestionVideo'] = '0';
                }

                $guidanceVideoResult = mysqli_query($databaseConnection, "SELECT count(fr.vidLength) as totalQuestion, SEC_TO_TIME( SUM( TIME_TO_SEC( fr.vidLength ) ) ) AS vidLength FROM questions_transection fr where fr.delegationType = 'guidanceVideo' and fr.uploadStatus = 2 and fr.expertId = '" . $row['id'] . "' " . $filter_query);
                $guidanceVideoValues = mysqli_fetch_assoc($guidanceVideoResult);
                if ($json['workDone'] == "" || $json['workDone'] == "guidanceVideo") {
                    $row['totalGuidanceVideoLength'] = $guidanceVideoValues['vidLength'];
                    $row['totalGuidanceVideo'] = $guidanceVideoValues['totalQuestion'];
                } else {
                    $row['totalGuidanceVideoLength'] = '00:00:00';
                    $row['totalGuidanceVideo'] = '0';
                }

                $peerResponseVideoResult = mysqli_query($databaseConnection, "SELECT count(fr.vidLength) as totalQuestion, SEC_TO_TIME( SUM( TIME_TO_SEC( fr.vidLength ) ) ) AS vidLength FROM questions_transection fr where fr.delegationType = 'peerResponseVideo' and fr.uploadStatus = 2 and fr.expertId = '" . $row['id'] . "' " . $filter_query);
                $peerVideoValues = mysqli_fetch_assoc($peerResponseVideoResult);
                if ($json['workDone'] == "" || $json['workDone'] == "peerResponseVideo") {
                    $row['totalPeerResponseVideoLength'] = $peerVideoValues['vidLength'];
                    $row['totalPeerResponseVideo'] = $peerVideoValues['totalQuestion'];
                } else {
                    $row['totalPeerResponseVideoLength'] = '00:00:00';
                    $row['totalPeerResponseVideo'] = '0';
                }

                $totalTaggingQuery = mysqli_query($databaseConnection, "SELECT count(fr.id) as totalTaggingQuestion FROM questions_transection fr where fr.delegationType = 'tagging' and fr.uploadStatus = 2 and fr.expertId = '" . $row['id'] . "' " . $filter_query);
                $totalTaggingValue = mysqli_fetch_assoc($totalTaggingQuery);
                if ($json['workDone'] == "" || $json['workDone'] == "tagging") {
                    $row['totalTaggingQuestion'] = $totalTaggingValue['totalTaggingQuestion'];
                } else {
                    $row['totalTaggingQuestion'] = '0';
                }
                $totalGuidanceFeature = mysqli_query($databaseConnection, "SELECT sum(fr.noOfImages) as totalImages, sum(fr.noOfVideos) as totalVideos FROM questions_transection fr where fr.delegationType = 'guidanceVideo' and fr.uploadStatus = 2 and fr.expertId = '" . $row['id'] . "' " . $filter_query);
                $totalGuidanceFeatureValue = mysqli_fetch_assoc($totalGuidanceFeature);
                if ($totalGuidanceFeatureValue['totalImages'] == null && $totalGuidanceFeatureValue['totalVideos'] == null) {
                    $row['totalImages'] = 0;
                    $row['totalVideos'] = 0;
                } else {
                    $row['totalImages'] = $totalGuidanceFeatureValue['totalImages'];
                    $row['totalVideos'] = $totalGuidanceFeatureValue['totalVideos'];
                }


                array_push($values, $row);
            }
            $to_encode = array(
                'expertAccountList' => $values,
                'count' => $count_result,
                'status' => 1
            );
        } else {
            $to_encode = array(
                'expertAccountList' => $values,
                'status' => 0,
                'count' => 0
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Request for getting feedback request Failed.",
            'status' => -1
        );
    }

    echo json_encode($to_encode);
} else if (isset($_GET['getExpertAccountLists'])) {
    /* 28-oct-2021 ratecard added by anuj Verma for calculating expert total payable amount */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        //$limit = 50;
        $start = 0;
        $userId = $json['userId'];
        $expert_filter_query = ' ';
        $filter_query = ' ';
        $filter_query_fsq = ' ';
        $filter_type = ' ';
        $limit = $json['limit'];
        $start = ($json['page'] - 1) * $limit;
        $order_query = "";
        $limit_query = $limit == 0 ? "" : " limit " . $start . "," . $limit;
        $values = array();
        $ratefilter_query = ' ';

        if ($json['expertName'] != "")
            $expert_filter_query .= " and p.name LIKE '%" . $json['expertName'] . "%' ";

        if ($json['from_date'] != "" && $json['to_date'] == "") {
            $filter_query .= " and fr.updatedAt >= '" . $json['from_date'] . " 00:00:00' ";
            $filter_query_fsq .= " and er.createdAt >= '" . $json['from_date'] . " 00:00:00' ";

            $ratefilter_query .= "  AND ( ('" . $json['from_date'] . " 00:00:00' BETWEEN rateCardStartDate AND rateCardEndDate)  OR (rateCardStartDate >='" . $json['from_date'] . " 00:00:00') or (rateCardStartDate  <> '" . $json['from_date'] . " 00:00:00' and rateCardEndDate is null ))";
        }
        if ($json['from_date'] == "" && $json['to_date'] != "") {
            $filter_query .= " and fr.updatedAt <= '" . $json['to_date'] . " 23:59:59' ";
            $filter_query_fsq .= " and er.createdAt <= '" . $json['to_date'] . " 23:59:59' ";

            $ratefilter_query .= " AND (('" . $json['to_date'] . " 23:59:59' BETWEEN rateCardStartDate AND rateCardEndDate) OR (rateCardEndDate<='" . $json['to_date'] . " 23:59:59')  or (rateCardStartDate  <='" . $json['to_date'] . " 00:00:00' and rateCardEndDate is null ) )";
        }
        if ($json['from_date'] != "" && $json['to_date'] != "") {
            $filter_query .= " and fr.updatedAt >= '" . $json['from_date'] . " 00:00:00' and fr.updatedAt <= '" . $json['to_date'] . " 23:59:59' ";
            $filter_query_fsq .= " and er.createdAt >= '" . $json['from_date'] . " 00:00:00' and er.createdAt <= '" . $json['to_date'] . " 23:59:59' ";

            $ratefilter_query .= " AND (('" . $json['from_date'] . " 00:00:00' BETWEEN rateCardStartDate  AND rateCardEndDate) OR ('" . $json['to_date'] . " 23:59:59' BETWEEN rateCardStartDate  AND rateCardEndDate) OR ( rateCardStartDate >='" . $json['from_date'] . " 00:00:00' AND  rateCardEndDate<='" . $json['to_date'] . " 23:59:59') or (rateCardStartDate  <='" . $json['to_date'] . " 00:00:00' and rateCardEndDate is null ))";

        }

        if ($json['workDone'] != "") {
            if ($json['workDone'] == "personalizedFeedback") {
                $query = "SELECT p.name,p.id as id,p.emailId,p.phonenumber,u.id as candidateId FROM panel p  inner join users u on p.id = u.panelId inner  join expert_review er on er.feedbackGivenBy = p.id inner join feedback_request fr on fr.id = er.feedback_request_id INNER JOIN feedback_status_question fsq ON fsq.feedbackRequestId = er.feedback_request_id AND fsq.questionId = er.questionId where p.deleted_at is null AND fr.review_status = 2 " . $expert_filter_query . $filter_query_fsq . " group by p.id ";
            } elseif ($json['workDone'] == "qnsCreate") {
                $query = "SELECT p.name,p.id as id,p.emailId,p.phonenumber,u.id as candidateId FROM panel p  inner join users u on p.id = u.panelId inner join questions fr on (fr.questionCreator = p.id OR fr.questionReviewer = p.id ) where p.deleted_at is null  " . $expert_filter_query . $filter_query . " group by p.id ";
            } else {
                $query = "SELECT p.name,p.id as id,p.emailId,p.phonenumber,u.id as candidateId FROM panel p  inner join users u on p.id = u.panelId inner join questions_transection fr on fr.expertId= p.id where p.deleted_at is null and fr.uploadStatus = 2 " . $expert_filter_query . " " . $filter_query . " and fr.delegationType='" . $json['workDone'] . "' group by p.id";
            }

        } else {
            $query = "SELECT p.name,p.id as id,p.emailId,p.phonenumber,u.id as candidateId FROM panel p inner join users u on p.id = u.panelId inner join expert_review er on er.feedbackGivenBy = p.id inner join feedback_request fr on fr.id = er.feedback_request_id INNER JOIN feedback_status_question fsq ON fsq.feedbackRequestId = er.feedback_request_id AND fsq.questionId = er.questionId where p.deleted_at is null AND fsq.review_status = 2 " . $expert_filter_query . $filter_query_fsq . " group by p.id   UNION SELECT p.name,p.id as id,p.emailId,p.phonenumber,u.id as candidateId  FROM panel p inner join users u on p.id = u.panelId inner join questions_transection fr on fr.expertId= p.id where p.deleted_at is null and fr.uploadStatus = 2 " . $expert_filter_query . " " . $filter_query . " group by p.id UNION SELECT p.name,p.id as id,p.emailId,p.phonenumber,u.id as candidateId FROM panel p  inner join users u on p.id = u.panelId inner join questions fr on (fr.questionCreator = p.id OR fr.questionReviewer = p.id ) where p.deleted_at is null  " . $expert_filter_query . $filter_query . " group by p.id ";
        }

        $result = mysqli_query($databaseConnection, $query . $limit_query);
        if (mysqli_num_rows($result) > 0) {
            $count_query = mysqli_query($databaseConnection, $query);
            $count_result = mysqli_num_rows($count_query);

            while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
                $rateQuery = mysqli_query($databaseConnection, "SELECT * FROM `expert_rate_card` WHERE expertId ='" . $row['id'] . "' " . $ratefilter_query . "  ORDER BY rateCardStartDate  ASC");

                $totalGivenAssessment = 0;
                $totalVideoFeedback = 0;
                $totalCandidateVideoWatch = 0;
                $totalCandidateVideo = 0;

                $totalQuestionVideo = 0;
                $totalGuidanceVideo = 0;
                $totalPeerResponseVideo = 0;
                $totalTaggingQuestion = 0;
                $totalGuidanceVideoLength = 0;
                $totalQuestionVideoLength = 0;
                $totalPeerResponseVideoLength = 0;
                $totalquestionCreated = 0;
                $totalQuestionReviewed = 0;
                $totalImagesUsedInQnsCreation = 0;
                $totalVideosUsedInQnsCreation = 0;

                $totalImagesUsedInGV = 0;
                $totalVideosUsedInGV = 0;



                $totalGivenAssessmentAmount = 0;
                $totalVideoFeedbackAmount = 0;
                $totalCandidateVideoWatchAmount = 0;

                $totalQuestionVideoAmount = 0;
                $totalGuidanceVideoAmount = 0;
                $totalGuidanceVideoDurationAmount = 0;
                $totalQuestionVideoDurationAmount = 0;
                $totalPeerResponseVideoAmount = 0;
                $totalPeerResponseVideoDurationAmount = 0;
                $totalTaggingQuestionAmount = 0;


                $totalImagesUsedInGVAmount = 0;
                $totalVideosUsedInGVAmount = 0;

                $totalquestionCreationAmount = 0;
                $totalQuestionReviewedAmount = 0;
                $totalImagesUsedInQnsCreationAmount = 0;
                $totalVideosUsedInQnsCreationAmount = 0;
                $internet_Allowance_Per_Month = 0;

                while ($rate_card = mysqli_fetch_array($rateQuery, MYSQLI_ASSOC)) {
                    $rcFilterQuery = " ";
                    $rcFilterQueryFsq = " ";
                    if ($json['from_date'] >= $rate_card['rateCardStartDate'] && $json['from_date'] != "") {
                        $rcFilterQuery .= " AND fr.updatedAt >= '" . $json['from_date'] . " 00:00:00'";
                        $rcFilterQueryFsq .= " AND er.createdAt >= '" . $json['from_date'] . " 00:00:00'";
                    } else if ($json['from_date'] == "") {
                        $rcFilterQuery .= " AND fr.updatedAt >='" . $rate_card['rateCardStartDate'] . "'";
                        $rcFilterQueryFsq .= " AND er.createdAt >='" . $rate_card['rateCardStartDate'] . "'";
                    } else {
                        $rcFilterQuery .= " AND fr.updatedAt>='" . $rate_card['rateCardStartDate'] . "'";
                        $rcFilterQueryFsq .= " AND er.createdAt>='" . $rate_card['rateCardStartDate'] . "'";
                    }


                    if ($json['to_date'] >= $rate_card['rateCardEndDate'] && $rate_card['rateCardEndDate'] != NULL) {
                        $rcFilterQuery .= " AND fr.updatedAt <= '" . $rate_card['rateCardEndDate'] . "'";
                        $rcFilterQueryFsq .= " AND er.createdAt <= '" . $rate_card['rateCardEndDate'] . "'";

                    } else if ($json['to_date'] == "" && $rate_card['rateCardEndDate'] != NULL) {
                        $rcFilterQuery .= " AND fr.updatedAt  <= '" . $rate_card['rateCardEndDate'] . "'";
                        $rcFilterQueryFsq .= " AND er.createdAt  <= '" . $rate_card['rateCardEndDate'] . "'";
                    } else if ($json['to_date'] != "") {
                        $rcFilterQuery .= " AND fr.updatedAt <= '" . $json['to_date'] . " 23:59:59'";
                        $rcFilterQueryFsq .= " AND er.createdAt <= '" . $json['to_date'] . " 23:59:59'";
                    }


                    $totalGivenFeedbackQuery = "select count(distinct er.id) as totalAssessmentQuestion,SUM( TIME_TO_SEC( vwd.vidWatchedDuration ) )  AS candidateVideoWatchLength,(SUM( TIME_TO_SEC( vwd.vidWatchedDuration ) )/3600) as watchHrs,SUM( TIME_TO_SEC( m.vidLength) )  AS candidateVideoLength  ,  SUM( CASE WHEN er.isGvAvailable='N' THEN   TIME_TO_SEC( er.vidLength ) ELSE 0 END )  AS personalizedVideoLength,(SUM( CASE WHEN er.isGvAvailable='N' THEN   TIME_TO_SEC( er.vidLength ) ELSE 0 END )/3600) as perHrs from mergedVideos m inner join video_watched_details vwd on vwd.mergeId = m.mergeId inner join feedback_request fr on fr.interviewSessionId = m.interviewSessionId inner join expert_review er on er.feedback_request_id = fr.id and er.questionId = m.questionId and er.candidateId = m.candidateId and er.interviewId= m.interviewId INNER JOIN feedback_status_question fsq ON fsq.feedbackRequestId = er.feedback_request_id AND fsq.questionId = er.questionId WHERE er.overallRating !='VideoIssue' and er.review_type='question' and fsq.review_status = '2' and er.feedbackGivenBy = '" . $row['id'] . "' " . $rcFilterQueryFsq . " group by er.feedbackGivenBy;";


                    $totalGivenFeedbackResult = mysqli_query($databaseConnection, $totalGivenFeedbackQuery);
                    if (mysqli_num_rows($totalGivenFeedbackResult) > 0) {
                        $totalGivenFeedbackValues = mysqli_fetch_assoc($totalGivenFeedbackResult);

                        $totalGivenAssessment += intval($totalGivenFeedbackValues['totalAssessmentQuestion']);

                        $totalGivenAssessmentAmount += intval($totalGivenFeedbackValues['totalAssessmentQuestion']) * intval($rate_card['assessmentRate_Per_Qns']);

                        if ($totalGivenFeedbackValues['personalizedVideoLength'] != NULL) {
                            $sumper = round($totalGivenFeedbackValues['perHrs'] * intval($rate_card['personalizedVideoDurationRate_Per_hr']), 2);
                            $totalVideoFeedback += intval($totalGivenFeedbackValues['personalizedVideoLength']);
                        } else {
                            $sumper = 0;
                            $totalVideoFeedback += 0;
                        }

                        $totalVideoFeedbackAmount += $sumper;
                        if ($totalGivenFeedbackValues['candidateVideoLength'] != null) {
                            $totalCandidateVideo += intval($totalGivenFeedbackValues['candidateVideoLength']);
                        }

                        if ($totalGivenFeedbackValues['candidateVideoWatchLength'] != NULL) {

                            $sumcanwv = round($totalGivenFeedbackValues['watchHrs'] * intval($rate_card['candidateVideoWatchDurationRate_Per_hr']), 2);
                            $totalCandidateVideoWatch += intval($totalGivenFeedbackValues['candidateVideoWatchLength']);
                        } else {
                            $sumcanwv = 0;
                            $totalCandidateVideoWatch += 0;
                        }

                        $totalCandidateVideoWatchAmount += $sumcanwv;

                    }
                    $totalQnsCreationQuery = "select  count(fr.id) as questionCreated , SUM(fr.noOfImages) as NumberOfImages, SUM(fr.noOfVideos) as NumberOfVideos from questions fr WHERE  fr.questionCreator = '" . $row['id'] . "'  " . $rcFilterQuery . " group by fr.questionCreator ";

                    $totalQnsReviewQuery = "select  count(fr.id) as questionReviewed from questions fr WHERE  fr.questionReviewer  = '" . $row['id'] . "'  " . $rcFilterQuery . " group by fr.questionReviewer ";

                    $totalQnsCreationResult = mysqli_query($databaseConnection, $totalQnsCreationQuery);
                    if (mysqli_num_rows($totalQnsCreationResult) > 0) {
                        $totalQnsCreationValues = mysqli_fetch_assoc($totalQnsCreationResult);


                        $totalquestionCreated += intval($totalQnsCreationValues['questionCreated']);
                        $totalImagesUsedInQnsCreation += intval($totalQnsCreationValues['NumberOfImages']);
                        $totalVideosUsedInQnsCreation += intval($totalQnsCreationValues['NumberOfVideos']);

                        $totalquestionCreationAmount += intval($totalQnsCreationValues['questionCreated']) * intval($rate_card['createQuesRate_Per_Qns']);

                        $totalImagesUsedInQnsCreationAmount += intval($totalQnsCreationValues['NumberOfImages']) * intval($rate_card['imageusedinCreateQnsRate_Per_Image']);
                        $totalVideosUsedInQnsCreationAmount += intval($totalQnsCreationValues['NumberOfVideos']) * intval($rate_card['videousedinCreateQnsRate_Per_Video']);


                    }
                    $totalQnsReviewResult = mysqli_query($databaseConnection, $totalQnsReviewQuery);
                    if (mysqli_num_rows($totalQnsReviewResult) > 0) {
                        $totalQnsReviewValues = mysqli_fetch_assoc($totalQnsReviewResult);
                        $totalQuestionReviewed += intval($totalQnsReviewValues['questionReviewed']);

                        $totalQuestionReviewedAmount += intval($totalQnsReviewValues['questionReviewed']) * intval($rate_card['reviewQuesRate_Per_Qns']);
                    }

                    $contentWorkResult = mysqli_query($databaseConnection, "SELECT COUNT(CASE WHEN fr.delegationType = 'questionVideo' AND fr.uploadStatus = 2  THEN fr.vidLength ELSE NULL END) as totalQuestionVideo,  SUM( CASE WHEN fr.delegationType = 'questionVideo' AND fr.uploadStatus = 2  THEN TIME_TO_SEC( fr.vidLength ) ELSE 0 END )  AS totalQuestionVidLength, (SUM( CASE WHEN fr.delegationType = 'questionVideo' AND fr.uploadStatus = 2  THEN TIME_TO_SEC( fr.vidLength ) ELSE 0 END )/3600) as quesHrs,  COUNT(CASE WHEN fr.delegationType = 'guidanceVideo' AND fr.uploadStatus = 2  THEN fr.vidLength ELSE NULL END) as totalGuidanceVideo,  SUM( CASE WHEN fr.delegationType = 'guidanceVideo' AND fr.uploadStatus = 2  THEN TIME_TO_SEC( fr.vidLength ) ELSE 0 END  ) AS guidanceVidLength,( SUM( CASE WHEN fr.delegationType = 'guidanceVideo' AND fr.uploadStatus = 2  THEN TIME_TO_SEC( fr.vidLength ) ELSE 0 END )/3600) as guidHrs,SUM(CASE WHEN fr.delegationType = 'guidanceVideo' AND fr.uploadStatus = 2 THEN fr.noOfImages ELSE 0 END) as totalImages, sum(CASE WHEN fr.delegationType = 'guidanceVideo' AND fr.uploadStatus = 2 THEN fr.noOfVideos ELSE 0 END) as totalVideos ,COUNT(CASE WHEN fr.delegationType = 'tagging' AND fr.uploadStatus = 2  THEN  fr.expertId ELSE NULL END) as totalTaggingQuestion, COUNT(CASE WHEN fr.delegationType = 'peerResponseVideo' AND fr.uploadStatus = 2  THEN fr.vidLength ELSE NULL END) as totalPeerResponseVideo, SUM( CASE WHEN fr.delegationType = 'peerResponseVideo' AND fr.uploadStatus = 2  THEN TIME_TO_SEC( fr.vidLength ) ELSE 0 END  ) AS peerVidLength FROM questions_transection fr where fr.uploadStatus = 2 and fr.expertId ='" . $row['id'] . "' " . $rcFilterQuery . " ");

                    $contentWorkValues = mysqli_fetch_assoc($contentWorkResult);

                    $totalQuestionVideo += intval($contentWorkValues['totalQuestionVideo']);
                    $totalGuidanceVideo += intval($contentWorkValues['totalGuidanceVideo']);
                    $totalPeerResponseVideo += intval($contentWorkValues['totalPeerResponseVideo']);
                    $totalTaggingQuestion += intval($contentWorkValues['totalTaggingQuestion']);

                    $totalImagesUsedInGV += $contentWorkValues['totalImages'] == NULL ? 0 : intval($contentWorkValues['totalImages']);
                    $totalVideosUsedInGV += $contentWorkValues['totalVideos'] == NULL ? 0 : intval($contentWorkValues['totalVideos']);

                    $totalTaggingQuestionAmount += intval($contentWorkValues['totalTaggingQuestion']) * floatval($rate_card['taggingRate_Per_Qns']);

                    $totalQuestionVideoAmount += intval($contentWorkValues['totalQuestionVideo']) * floatval($rate_card['qnsVideoRate_Per_Qns']);

                    $totalGuidanceVideoAmount += intval($contentWorkValues['totalGuidanceVideo']) * floatval($rate_card['guidanceVideoRate_Per_Qns']);


                    $totalImagesUsedInGVAmount += ($contentWorkValues['totalImages'] == NULL ? 0 : intval($contentWorkValues['totalImages'])) * intval($rate_card['imageusedinGVRate_Per_Image']);

                    $totalVideosUsedInGVAmount += ($contentWorkValues['totalVideos'] == NULL ? 0 : intval($contentWorkValues['totalVideos'])) * intval($rate_card['videousedinGVRate_Per_Video']);

                    $totalPeerResponseVideoAmount += intval($contentWorkValues['totalPeerResponseVideo']) * intval($rate_card['peerResponseRate_Per_Qns']);

                    if ($contentWorkValues['guidanceVidLength'] != NULL) {
                        $guidance = round($contentWorkValues['guidHrs'] * intval($rate_card['guidanceVideoDurationRate_Per_hr']), 2);
                        $totalGuidanceVideoLength += intval($contentWorkValues['guidanceVidLength']);
                    } else {
                        $guidance = 0;
                        $totalGuidanceVideoLength += 0;
                    }
                    $totalGuidanceVideoDurationAmount += $guidance;

                    /* this is for calculating Question video rate hourly type  */
                    if ($contentWorkValues['totalQuestionVidLength'] != NULL) {
                        $question = round($contentWorkValues['quesHrs'] * intval($rate_card['qnsVideoDurationRate_Per_hr']), 2);
                        $totalQuestionVideoLength += intval($contentWorkValues['totalQuestionVidLength']);
                    } else {
                        $question = 0;
                        $totalQuestionVideoLength += 0;
                    }
                    $totalQuestionVideoDurationAmount += $question;

                    if ($contentWorkValues['peerVidLength'] != NULL) {

                        $totalPeerResponseVideoLength += intval($contentWorkValues['peerVidLength']);
                    } else {
                        $totalPeerResponseVideoLength += 0;
                    }



                    $internet_Allowance_Per_Month = intval($rate_card['internet_Allowance_Per_Month']);


                }

                $row['totalGivenAssessment'] = $totalGivenAssessment;
                $row['totalGivenAssessmentAmount'] = $totalGivenAssessmentAmount;
                $row['totalCandidateVideoWatch'] = sec2hms($totalCandidateVideoWatch);
                $row['totalCandidateVideoWatchAmount'] = $totalCandidateVideoWatchAmount;

                $row['totalPersonalizedVideoFeedback'] = sec2hms($totalVideoFeedback);
                $row['totalPersonalizedVideoFeedbackAmount'] = $totalVideoFeedbackAmount;
                $row['totalCandidateVideo'] = sec2hms($totalCandidateVideo);

                $row['totalQuestionVideo'] = $totalQuestionVideo;
                $row['totalQuestionVideoAmount'] = $totalQuestionVideoAmount;
                $row['totalQuestionVideoLength'] = sec2hms($totalQuestionVideoLength);
                $row['totalQuestionVideoDurationAmount'] = $totalQuestionVideoDurationAmount;
                $row['totalGuidanceVideo'] = $totalGuidanceVideo;
                $row['totalGuidanceVideoAmount'] = $totalGuidanceVideoAmount;
                $row['totalGuidanceVideoLength'] = sec2hms($totalGuidanceVideoLength);
                $row['totalGuidanceVideoDurationAmount'] = $totalGuidanceVideoDurationAmount;
                $row['totalPeerResponseVideo'] = $totalPeerResponseVideo;
                $row['totalPeerResponseVideoLength'] = sec2hms($totalPeerResponseVideoLength);
                $row['totalPeerResponseVideoAmount'] = $totalPeerResponseVideoAmount;
                $row['totalTaggingQuestion'] = $totalTaggingQuestion;
                $row['totalTaggingQuestionAmount'] = $totalTaggingQuestionAmount;

                $row['totalImagesUsedInGv'] = $totalImagesUsedInGV;
                $row['totalImagesUsedInGvAmount'] = $totalImagesUsedInGVAmount;
                $row['totalVideosUsedInGv'] = $totalVideosUsedInGV;
                $row['totalVideosInGvAmount'] = $totalVideosUsedInGVAmount;
                $row['internet_Allowance_Per_Month'] = $internet_Allowance_Per_Month;

                $row['totalImagesUsedInQnsCreation'] = $totalImagesUsedInQnsCreation;
                $row['totalImagesUsedInQnsCreationAmount'] = $totalImagesUsedInQnsCreationAmount;
                $row['totalVideosUsedInQnsCreation'] = $totalVideosUsedInQnsCreation;
                $row['totalVideosUsedInQnsCreationAmount'] = $totalVideosUsedInQnsCreationAmount;
                $row['totalQuestionReviewedAmount'] = $totalQuestionReviewedAmount;
                $row['totalQuestionReviewed'] = $totalQuestionReviewed;
                $row['totalquestionCreation'] = $totalquestionCreated;
                $row['totalquestionCreationAmount'] = $totalquestionCreationAmount;

                array_push($values, $row);
            }
            $to_encode = array(
                'expertAccountList' => $values,
                'count' => $count_result,
                'status' => 1
            );
        } else {
            $to_encode = array(
                'expertAccountList' => $values,
                'status' => 0,
                'count' => 0
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Request for getting feedback request Failed.",
            'status' => -1
        );
    }

    echo json_encode($to_encode);
} else if (isset($_GET['getExpertAccountListswithBankDetails'])) {
    /* 10-Nov-2021 ratecard added by Naraayn  for calculating expert total payable amount with bank data */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        //$limit = 50;
        $start = 0;
        $userId = $json['userId'];
        $expert_filter_query = ' ';
        $filter_query = ' ';
        $filter_query_fsq = ' ';
        $filter_type = ' ';
        $limit = $json['limit'];
        $start = ($json['page'] - 1) * $limit;
        $order_query = "";
        $limit_query = $limit == 0 ? "" : " limit " . $start . "," . $limit;
        $values = array();
        $ratefilter_query = ' ';

        if ($json['expertName'] != "")
            $expert_filter_query .= " and p.name LIKE '%" . $json['expertName'] . "%' ";

        if ($json['from_date'] != "" && $json['to_date'] == "") {
            $filter_query .= " and fr.updatedAt >= '" . $json['from_date'] . " 00:00:00' ";
            $filter_query_fsq .= " and er.createdAt >= '" . $json['from_date'] . " 00:00:00' ";

            $ratefilter_query .= "  AND ( ('" . $json['from_date'] . " 00:00:00' BETWEEN rateCardStartDate AND rateCardEndDate)  OR (rateCardStartDate >='" . $json['from_date'] . " 00:00:00') or (rateCardStartDate  <> '" . $json['from_date'] . " 00:00:00' and rateCardEndDate is null ))";
        }
        if ($json['from_date'] == "" && $json['to_date'] != "") {
            $filter_query .= " and fr.updatedAt <= '" . $json['to_date'] . " 23:59:59' ";
            $filter_query_fsq .= " and er.createdAt <= '" . $json['to_date'] . " 23:59:59' ";

            $ratefilter_query .= " AND (('" . $json['to_date'] . " 23:59:59' BETWEEN rateCardStartDate AND rateCardEndDate) OR (rateCardEndDate<='" . $json['to_date'] . " 23:59:59')  or (rateCardStartDate  <='" . $json['to_date'] . " 00:00:00' and rateCardEndDate is null ) )";
        }
        if ($json['from_date'] != "" && $json['to_date'] != "") {
            $filter_query .= " and fr.updatedAt >= '" . $json['from_date'] . " 00:00:00' and fr.updatedAt <= '" . $json['to_date'] . " 23:59:59' ";
            $filter_query_fsq .= " and er.createdAt >= '" . $json['from_date'] . " 00:00:00' and er.createdAt <= '" . $json['to_date'] . " 23:59:59' ";

            $ratefilter_query .= " AND (('" . $json['from_date'] . " 00:00:00' BETWEEN rateCardStartDate  AND rateCardEndDate) OR ('" . $json['to_date'] . " 23:59:59' BETWEEN rateCardStartDate  AND rateCardEndDate) OR ( rateCardStartDate >='" . $json['from_date'] . " 00:00:00' AND  rateCardEndDate<='" . $json['to_date'] . " 23:59:59') or (rateCardStartDate  <='" . $json['to_date'] . " 00:00:00' and rateCardEndDate is null ))";

        }

        if ($json['workDone'] != "") {
            if ($json['workDone'] == "personalizedFeedback") {
                $query = "SELECT epd.beneficiaryAccNo,epd.beneficiaryName,epd.IFSC_code,epd.beneficiary_Bank_Name,epd.walletNumber_UPIId , epd.walletType, p.name,p.id as id,p.emailId,p.phonenumber,u.id as candidateId FROM panel p LEFT join expert_bank_details epd on epd.expertId =p.id  inner join users u on p.id = u.panelId inner  join expert_review er on er.feedbackGivenBy = p.id inner join feedback_request fr on fr.id = er.feedback_request_id INNER JOIN feedback_status_question fsq ON fsq.feedbackRequestId = er.feedback_request_id AND fsq.questionId = er.questionId where p.deleted_at is null AND fr.review_status = 2 " . $expert_filter_query . $filter_query_fsq . " group by p.id ";
            } elseif ($json['workDone'] == "qnsCreate") {
                $query = "SELECT epd.beneficiaryAccNo,epd.beneficiaryName,epd.IFSC_code,epd.beneficiary_Bank_Name,epd.walletNumber_UPIId , epd.walletType ,p.name,p.id as id,p.emailId,p.phonenumber,u.id as candidateId FROM panel p  LEFT join expert_bank_details epd on epd.expertId =p.id inner join users u on p.id = u.panelId inner join questions fr on (fr.questionCreator = p.id OR fr.questionReviewer = p.id ) where p.deleted_at is null  " . $expert_filter_query . $filter_query . " group by p.id ";
            } else {
                $query = "SELECT epd.beneficiaryAccNo,epd.beneficiaryName,epd.IFSC_code,epd.beneficiary_Bank_Name,epd.walletNumber_UPIId , epd.walletType ,p.name,p.id as id,p.emailId,p.phonenumber,u.id as candidateId FROM panel p LEFT join expert_bank_details epd on epd.expertId =p.id inner join users u on p.id = u.panelId inner join questions_transection fr on fr.expertId= p.id where p.deleted_at is null and fr.uploadStatus = 2 " . $expert_filter_query . " " . $filter_query . " and fr.delegationType='" . $json['workDone'] . "' group by p.id ";
            }

        } else {
            $query = "SELECT epd.beneficiaryAccNo,epd.beneficiaryName,epd.IFSC_code,epd.beneficiary_Bank_Name,epd.walletNumber_UPIId , epd.walletType, p.name,p.id as id,p.emailId,p.phonenumber,u.id as candidateId FROM panel p LEFT join expert_bank_details epd on epd.expertId = p.id inner join users u on p.id = u.panelId inner join expert_review er on er.feedbackGivenBy = p.id inner join feedback_request fr on fr.id = er.feedback_request_id INNER JOIN feedback_status_question fsq ON fsq.feedbackRequestId = er.feedback_request_id AND fsq.questionId = er.questionId where p.deleted_at is null AND fsq.review_status = 2 " . $expert_filter_query . $filter_query_fsq . " group by p.id   UNION SELECT epd.beneficiaryAccNo,epd.beneficiaryName,epd.IFSC_code,epd.beneficiary_Bank_Name,epd.walletNumber_UPIId , epd.walletType,p.name,p.id as id,p.emailId,p.phonenumber,u.id as candidateId  FROM panel p LEFT join expert_bank_details epd on epd.expertId = p.id inner join users u on p.id = u.panelId inner join questions_transection fr on fr.expertId= p.id where p.deleted_at is null and fr.uploadStatus = 2 " . $expert_filter_query . " " . $filter_query . " group by p.id UNION SELECT epd.beneficiaryAccNo,epd.beneficiaryName,epd.IFSC_code,epd.beneficiary_Bank_Name,epd.walletNumber_UPIId , epd.walletType,p.name,p.id as id,p.emailId,p.phonenumber,u.id as candidateId FROM panel p LEFT join expert_bank_details epd on epd.expertId = p.id inner join users u on p.id = u.panelId inner join questions fr on (fr.questionCreator = p.id OR fr.questionReviewer = p.id ) where p.deleted_at is null  " . $expert_filter_query . $filter_query . " group by p.id ";
        }
        $result = mysqli_query($databaseConnection, $query . $limit_query);
        if (mysqli_num_rows($result) > 0) {
            $count_query = mysqli_query($databaseConnection, $query);
            $count_result = mysqli_num_rows($count_query);

            while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
                $rateQuery = mysqli_query($databaseConnection, "SELECT * FROM `expert_rate_card` WHERE expertId ='" . $row['id'] . "' " . $ratefilter_query . "  ORDER BY rateCardStartDate  ASC");

                $totalGivenAssessment = 0;
                $totalVideoFeedback = 0;
                $totalCandidateVideoWatch = 0;
                $totalCandidateVideo = 0;

                $totalQuestionVideo = 0;
                $totalGuidanceVideo = 0;
                $totalPeerResponseVideo = 0;
                $totalTaggingQuestion = 0;
                $totalGuidanceVideoLength = 0;
                $totalQuestionVideoLength = 0;
                $totalPeerResponseVideoLength = 0;

                $totalquestionCreated = 0;
                $totalQuestionReviewed = 0;
                $totalImagesUsedInQnsCreation = 0;
                $totalVideosUsedInQnsCreation = 0;

                $totalImagesUsedInGV = 0;
                $totalVideosUsedInGV = 0;

                $totalGivenAssessmentAmount = 0;
                $totalVideoFeedbackAmount = 0;
                $totalCandidateVideoWatchAmount = 0;

                $totalQuestionVideoAmount = 0;
                $totalGuidanceVideoAmount = 0;
                $totalGuidanceVideoDurationAmount = 0;
                $totalQuestionVideoDurationAmount = 0;
                $totalPeerResponseVideoAmount = 0;
                $totalPeerResponseVideoDurationAmount = 0;
                $totalTaggingQuestionAmount = 0;


                $totalImagesUsedInGVAmount = 0;
                $totalVideosUsedInGVAmount = 0;

                $totalquestionCreationAmount = 0;
                $totalQuestionReviewedAmount = 0;
                $totalImagesUsedInQnsCreationAmount = 0;
                $totalVideosUsedInQnsCreationAmount = 0;
                $internet_Allowance_Per_Month = 0;

                while ($rate_card = mysqli_fetch_array($rateQuery, MYSQLI_ASSOC)) {
                    $rcFilterQuery = " ";
                    $rcFilterQueryFsq = " ";
                    if ($json['from_date'] >= $rate_card['rateCardStartDate'] && $json['from_date'] != "") {
                        $rcFilterQuery .= " AND fr.updatedAt >= '" . $json['from_date'] . " 00:00:00'";
                        $rcFilterQueryFsq .= " AND er.createdAt >= '" . $json['from_date'] . " 00:00:00'";
                    } else if ($json['from_date'] == "") {
                        $rcFilterQuery .= " AND fr.updatedAt >='" . $rate_card['rateCardStartDate'] . "'";
                        $rcFilterQueryFsq .= " AND er.createdAt >='" . $rate_card['rateCardStartDate'] . "'";
                    } else {
                        $rcFilterQuery .= " AND fr.updatedAt>='" . $rate_card['rateCardStartDate'] . "'";
                        $rcFilterQueryFsq .= " AND er.createdAt>='" . $rate_card['rateCardStartDate'] . "'";
                    }


                    if ($json['to_date'] >= $rate_card['rateCardEndDate'] && $rate_card['rateCardEndDate'] != NULL) {
                        $rcFilterQuery .= " AND fr.updatedAt <= '" . $rate_card['rateCardEndDate'] . "'";
                        $rcFilterQueryFsq .= " AND er.createdAt <= '" . $rate_card['rateCardEndDate'] . "'";

                    } else if ($json['to_date'] == "" && $rate_card['rateCardEndDate'] != NULL) {
                        $rcFilterQuery .= " AND fr.updatedAt  <= '" . $rate_card['rateCardEndDate'] . "'";
                        $rcFilterQueryFsq .= " AND er.createdAt  <= '" . $rate_card['rateCardEndDate'] . "'";
                    } else if ($json['to_date'] != "") {
                        $rcFilterQuery .= " AND fr.updatedAt <= '" . $json['to_date'] . " 23:59:59'";
                        $rcFilterQueryFsq .= " AND er.createdAt <= '" . $json['to_date'] . " 23:59:59'";
                    }


                    $totalGivenFeedbackQuery = "select count(distinct er.id) as totalAssessmentQuestion,SUM( TIME_TO_SEC( vwd.vidWatchedDuration ) )  AS candidateVideoWatchLength,(SUM( TIME_TO_SEC( vwd.vidWatchedDuration ) )/3600) as watchHrs,SUM( TIME_TO_SEC( m.vidLength) )  AS candidateVideoLength  ,  SUM( CASE WHEN er.isGvAvailable='N' THEN   TIME_TO_SEC( er.vidLength ) ELSE 0 END )  AS personalizedVideoLength,(SUM( CASE WHEN er.isGvAvailable='N' THEN   TIME_TO_SEC( er.vidLength ) ELSE 0 END )/3600) as perHrs from mergedVideos m inner join video_watched_details vwd on vwd.mergeId = m.mergeId inner join feedback_request fr on fr.interviewSessionId = m.interviewSessionId inner join expert_review er on er.feedback_request_id = fr.id and er.questionId = m.questionId and er.candidateId = m.candidateId and er.interviewId= m.interviewId INNER JOIN feedback_status_question fsq ON fsq.feedbackRequestId = er.feedback_request_id AND fsq.questionId = er.questionId WHERE er.overallRating !='VideoIssue' and er.review_type='question' and fsq.review_status = '2' and er.feedbackGivenBy = '" . $row['id'] . "' " . $rcFilterQueryFsq . " group by er.feedbackGivenBy;";


                    $totalGivenFeedbackResult = mysqli_query($databaseConnection, $totalGivenFeedbackQuery);
                    if (mysqli_num_rows($totalGivenFeedbackResult) > 0) {
                        $totalGivenFeedbackValues = mysqli_fetch_assoc($totalGivenFeedbackResult);

                        $totalGivenAssessment += intval($totalGivenFeedbackValues['totalAssessmentQuestion']);

                        $totalGivenAssessmentAmount += intval($totalGivenFeedbackValues['totalAssessmentQuestion']) * intval($rate_card['assessmentRate_Per_Qns']);

                        if ($totalGivenFeedbackValues['personalizedVideoLength'] != NULL) {
                            $sumper = round($totalGivenFeedbackValues['perHrs'] * intval($rate_card['personalizedVideoDurationRate_Per_hr']), 2);
                            $totalVideoFeedback += intval($totalGivenFeedbackValues['personalizedVideoLength']);
                        } else {
                            $sumper = 0;
                            $totalVideoFeedback += 0;
                        }

                        $totalVideoFeedbackAmount += $sumper;
                        if ($totalGivenFeedbackValues['candidateVideoLength'] != null) {
                            $totalCandidateVideo += intval($totalGivenFeedbackValues['candidateVideoLength']);
                        }

                        if ($totalGivenFeedbackValues['candidateVideoWatchLength'] != NULL) {

                            $sumcanwv = round($totalGivenFeedbackValues['watchHrs'] * intval($rate_card['candidateVideoWatchDurationRate_Per_hr']), 2);
                            $totalCandidateVideoWatch += intval($totalGivenFeedbackValues['candidateVideoWatchLength']);
                        } else {
                            $sumcanwv = 0;
                            $totalCandidateVideoWatch += 0;
                        }

                        $totalCandidateVideoWatchAmount += $sumcanwv;

                    }



                    $totalQnsCreationQuery = "select  count(fr.id) as questionCreated , SUM(fr.noOfImages) as NumberOfImages, SUM(fr.noOfVideos) as NumberOfVideos from questions fr WHERE  fr.questionCreator = '" . $row['id'] . "'  " . $rcFilterQuery . " group by fr.questionCreator ";

                    $totalQnsReviewQuery = "select  count(fr.id) as questionReviewed from questions fr WHERE  fr.questionReviewer  = '" . $row['id'] . "'  " . $rcFilterQuery . " group by fr.questionReviewer ";

                    $totalQnsCreationResult = mysqli_query($databaseConnection, $totalQnsCreationQuery);
                    if (mysqli_num_rows($totalQnsCreationResult) > 0) {
                        $totalQnsCreationValues = mysqli_fetch_assoc($totalQnsCreationResult);


                        $totalquestionCreated += intval($totalQnsCreationValues['questionCreated']);
                        $totalImagesUsedInQnsCreation += intval($totalQnsCreationValues['NumberOfImages']);
                        $totalVideosUsedInQnsCreation += intval($totalQnsCreationValues['NumberOfVideos']);

                        $totalquestionCreationAmount += intval($totalQnsCreationValues['questionCreated']) * intval($rate_card['createQuesRate_Per_Qns']);

                        $totalImagesUsedInQnsCreationAmount += intval($totalQnsCreationValues['NumberOfImages']) * intval($rate_card['imageusedinCreateQnsRate_Per_Image']);
                        $totalVideosUsedInQnsCreationAmount += intval($totalQnsCreationValues['NumberOfVideos']) * intval($rate_card['videousedinCreateQnsRate_Per_Video']);


                    }
                    $totalQnsReviewResult = mysqli_query($databaseConnection, $totalQnsReviewQuery);
                    if (mysqli_num_rows($totalQnsReviewResult) > 0) {
                        $totalQnsReviewValues = mysqli_fetch_assoc($totalQnsReviewResult);
                        $totalQuestionReviewed += intval($totalQnsReviewValues['questionReviewed']);

                        $totalQuestionReviewedAmount += intval($totalQnsReviewValues['questionReviewed']) * intval($rate_card['reviewQuesRate_Per_Qns']);
                    }



                    $contentWorkResult = mysqli_query($databaseConnection, "SELECT COUNT(CASE WHEN fr.delegationType = 'questionVideo' AND fr.uploadStatus = 2  THEN fr.vidLength ELSE NULL END) as totalQuestionVideo,  SUM( CASE WHEN fr.delegationType = 'questionVideo' AND fr.uploadStatus = 2  THEN TIME_TO_SEC( fr.vidLength ) ELSE 0 END )  AS totalQuestionVidLength, (SUM( CASE WHEN fr.delegationType = 'questionVideo' AND fr.uploadStatus = 2  THEN TIME_TO_SEC( fr.vidLength ) ELSE 0 END )/3600) as quesHrs,  COUNT(CASE WHEN fr.delegationType = 'guidanceVideo' AND fr.uploadStatus = 2  THEN fr.vidLength ELSE NULL END) as totalGuidanceVideo,  SUM( CASE WHEN fr.delegationType = 'guidanceVideo' AND fr.uploadStatus = 2  THEN TIME_TO_SEC( fr.vidLength ) ELSE 0 END  ) AS guidanceVidLength,( SUM( CASE WHEN fr.delegationType = 'guidanceVideo' AND fr.uploadStatus = 2  THEN TIME_TO_SEC( fr.vidLength ) ELSE 0 END )/3600) as guidHrs,SUM(CASE WHEN fr.delegationType = 'guidanceVideo' AND fr.uploadStatus = 2 THEN fr.noOfImages ELSE 0 END) as totalImages, sum(CASE WHEN fr.delegationType = 'guidanceVideo' AND fr.uploadStatus = 2 THEN fr.noOfVideos ELSE 0 END) as totalVideos ,COUNT(CASE WHEN fr.delegationType = 'tagging' AND fr.uploadStatus = 2  THEN  fr.expertId ELSE NULL END) as totalTaggingQuestion, COUNT(CASE WHEN fr.delegationType = 'peerResponseVideo' AND fr.uploadStatus = 2  THEN fr.vidLength ELSE NULL END) as totalPeerResponseVideo, SUM( CASE WHEN fr.delegationType = 'peerResponseVideo' AND fr.uploadStatus = 2  THEN TIME_TO_SEC( fr.vidLength ) ELSE 0 END  ) AS peerVidLength FROM questions_transection fr where fr.uploadStatus = 2 and fr.expertId ='" . $row['id'] . "' " . $rcFilterQuery . " ");

                    $contentWorkValues = mysqli_fetch_assoc($contentWorkResult);

                    $totalQuestionVideo += intval($contentWorkValues['totalQuestionVideo']);
                    $totalGuidanceVideo += intval($contentWorkValues['totalGuidanceVideo']);
                    $totalPeerResponseVideo += intval($contentWorkValues['totalPeerResponseVideo']);
                    $totalTaggingQuestion += intval($contentWorkValues['totalTaggingQuestion']);

                    $totalImagesUsedInGV += $contentWorkValues['totalImages'] == NULL ? 0 : intval($contentWorkValues['totalImages']);
                    $totalVideosUsedInGV += $contentWorkValues['totalVideos'] == NULL ? 0 : intval($contentWorkValues['totalVideos']);

                    $totalTaggingQuestionAmount += intval($contentWorkValues['totalTaggingQuestion']) * floatval($rate_card['taggingRate_Per_Qns']);

                    $totalQuestionVideoAmount += intval($contentWorkValues['totalQuestionVideo']) * floatval($rate_card['qnsVideoRate_Per_Qns']);

                    $totalGuidanceVideoAmount += intval($contentWorkValues['totalGuidanceVideo']) * floatval($rate_card['guidanceVideoRate_Per_Qns']);


                    $totalImagesUsedInGVAmount += ($contentWorkValues['totalImages'] == NULL ? 0 : intval($contentWorkValues['totalImages'])) * intval($rate_card['imageusedinGVRate_Per_Image']);

                    $totalVideosUsedInGVAmount += ($contentWorkValues['totalVideos'] == NULL ? 0 : intval($contentWorkValues['totalVideos'])) * intval($rate_card['videousedinGVRate_Per_Video']);

                    $totalPeerResponseVideoAmount += intval($contentWorkValues['totalPeerResponseVideo']) * intval($rate_card['peerResponseRate_Per_Qns']);

                    if ($contentWorkValues['guidanceVidLength'] != NULL) {
                        $guidance = round($contentWorkValues['guidHrs'] * intval($rate_card['guidanceVideoDurationRate_Per_hr']), 2);
                        $totalGuidanceVideoLength += intval($contentWorkValues['guidanceVidLength']);
                    } else {
                        $guidance = 0;
                        $totalGuidanceVideoLength += 0;
                    }
                    $totalGuidanceVideoDurationAmount += $guidance;

                    /* this is for calculating Question video rate hourly type  */
                    if ($contentWorkValues['totalQuestionVidLength'] != NULL) {
                        $question = round($contentWorkValues['quesHrs'] * intval($rate_card['qnsVideoDurationRate_Per_hr']), 2);
                        $totalQuestionVideoLength += intval($contentWorkValues['totalQuestionVidLength']);
                    } else {
                        $question = 0;
                        $totalQuestionVideoLength += 0;
                    }
                    $totalQuestionVideoDurationAmount += $question;

                    if ($contentWorkValues['peerVidLength'] != NULL) {

                        $totalPeerResponseVideoLength += intval($contentWorkValues['peerVidLength']);
                    } else {
                        $totalPeerResponseVideoLength += 0;
                    }



                    $internet_Allowance_Per_Month = intval($rate_card['internet_Allowance_Per_Month']);


                }

                $row['totalGivenAssessment'] = $totalGivenAssessment;
                $row['totalGivenAssessmentAmount'] = $totalGivenAssessmentAmount;
                $row['totalCandidateVideoWatch'] = sec2hms($totalCandidateVideoWatch);
                $row['totalCandidateVideoWatchAmount'] = $totalCandidateVideoWatchAmount;

                $row['totalPersonalizedVideoFeedback'] = sec2hms($totalVideoFeedback);
                $row['totalPersonalizedVideoFeedbackAmount'] = $totalVideoFeedbackAmount;
                $row['totalCandidateVideo'] = sec2hms($totalCandidateVideo);

                $row['totalQuestionVideo'] = $totalQuestionVideo;
                $row['totalQuestionVideoAmount'] = $totalQuestionVideoAmount;
                $row['totalQuestionVideoLength'] = sec2hms($totalQuestionVideoLength);
                $row['totalQuestionVideoDurationAmount'] = $totalQuestionVideoDurationAmount;
                $row['totalGuidanceVideo'] = $totalGuidanceVideo;
                $row['totalGuidanceVideoAmount'] = $totalGuidanceVideoAmount;
                $row['totalGuidanceVideoLength'] = sec2hms($totalGuidanceVideoLength);
                $row['totalGuidanceVideoDurationAmount'] = $totalGuidanceVideoDurationAmount;
                $row['totalPeerResponseVideo'] = $totalPeerResponseVideo;
                $row['totalPeerResponseVideoLength'] = sec2hms($totalPeerResponseVideoLength);
                $row['totalPeerResponseVideoAmount'] = $totalPeerResponseVideoAmount;
                $row['totalTaggingQuestion'] = $totalTaggingQuestion;
                $row['totalTaggingQuestionAmount'] = $totalTaggingQuestionAmount;

                $row['totalImagesUsedInGv'] = $totalImagesUsedInGV;
                $row['totalImagesUsedInGvAmount'] = $totalImagesUsedInGVAmount;
                $row['totalVideosUsedInGv'] = $totalVideosUsedInGV;
                $row['totalVideosInGvAmount'] = $totalVideosUsedInGVAmount;
                $row['internet_Allowance_Per_Month'] = $internet_Allowance_Per_Month;

                $row['totalImagesUsedInQnsCreation'] = $totalImagesUsedInQnsCreation;
                $row['totalImagesUsedInQnsCreationAmount'] = $totalImagesUsedInQnsCreationAmount;
                $row['totalVideosUsedInQnsCreation'] = $totalVideosUsedInQnsCreation;
                $row['totalVideosUsedInQnsCreationAmount'] = $totalVideosUsedInQnsCreationAmount;
                $row['totalQuestionReviewedAmount'] = $totalQuestionReviewedAmount;
                $row['totalQuestionReviewed'] = $totalQuestionReviewed;
                $row['totalquestionCreation'] = $totalquestionCreated;
                $row['totalquestionCreationAmount'] = $totalquestionCreationAmount;

                array_push($values, $row);
            }
            $to_encode = array(
                'expertAccountList' => $values,
                'count' => $count_result,
                'status' => 1
            );
        } else {
            $to_encode = array(
                'expertAccountList' => $values,
                'status' => 0,
                'count' => 0
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Request for getting feedback request Failed.",
            'status' => -1
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['submitVideoResume'])) {
    /* This function is used for submiting video resume by ANuj 3-Nov */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    if (isset($json)) {
        $interviewId = $json['interviewId'];
        $candidateId = $json['candidateId'];
        $interviewSessionId = $json['interviewSessionId'];
        $userId = $json['userId'];
        $createdAt = $json['createdAt'];
        $isAccepted = $json['isAccepted'];
        $userType = $json['currentUserType'];
        $fbr_status = -6;
        $query4 = "INSERT INTO `feedback_request`(`candidateId`,`interviewId`,`interviewSessionId`,`requestDate`,`review_status`,`createdBy`) VALUES('$candidateId','$interviewId','$interviewSessionId',NOW(),-6,'$candidateId');";

        $requestReviewInsertQryResult1 = mysqli_query($databaseConnection, $query4);
        $to_encode = array(
            'result' => "Success",
            'message' => "Information Saved  Successfully",
            'status' => 1,
            'fbr_status' => $fbr_status
        );
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Request failed.",
            'status' => 0
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['openInterviewQuestions'])) {
    /* This function is used for open the locked questions from experts inbox by arun on 2 Aug 2023 */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    if (isset($json)) {


        $query1 = mysqli_query($databaseConnection, "DELETE FROM expert_review_observation_details WHERE expertReviewId IN (SELECT id FROM expert_review WHERE feedback_request_id='" . $json['feedbackRequestId'] . "' AND feedbackGivenBy='" . $json['expertId'] . "')");

        if ($query1) {


            $query2 = mysqli_query($databaseConnection, "DELETE FROM expert_review WHERE feedback_request_id='" . $json['feedbackRequestId'] . "' AND feedbackGivenBy='" . $json['expertId'] . "'");

            if ($query2) {

                $query3 = mysqli_query($databaseConnection, "UPDATE feedback_status_question SET review_status=0,expertId=NULL WHERE feedbackRequestId='" . $json['feedbackRequestId'] . "' AND expertId='" . $json['expertId'] . "'");

                if ($query3) {

                    $to_encode = array(
                        'result' => "Success",
                        'message' => "Information Saved  Successfully",
                        'status' => 1
                    );

                } else {
                    $to_encode = array(
                        'result' => "error",
                        'errorCode' => "Error while updating fsq",
                        'status' => 0
                    );
                }


            } else {
                $to_encode = array(
                    'result' => "error",
                    'errorCode' => "Error while deleting expert review",
                    'status' => 0
                );
            }


        } else {
            $to_encode = array(
                'result' => "error",
                'errorCode' => "Error while deleting erod",
                'status' => 0
            );
        }


    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Request failed.",
            'status' => 0
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['updateResumeVideo'])) {
    /* This function is used for Approving/reject video resume by ANuj 3-Nov */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    if (isset($json)) {
        $interviewId = $json['interviewId'];
        $candidateId = $json['candidateId'];
        $interviewSessionId = $json['interviewSessionId'];
        $userId = $json['userId'];
        $createdAt = $json['createdAt'];
        $isAccepted = $json['isAccepted'];
        $userType = $json['currentUserType'];
        $candidateQuery = mysqli_query($databaseConnection, "select u.emailId as candidateEmail,u.firstName as candidateName,concat('https://goprac.com/interviewDetails?id=',m.interviewId) as interviewLink from mergedVideos m inner join  users u on u.id = m.candidateId  where m.candidateId = '" . $json['candidateId'] . "' and m.interviewSessionId = '" . $json['interviewSessionId'] . "' group by m.interviewSessionId ;");
        if (mysqli_num_rows($candidateQuery) > 0) {
            $candidateDetails = mysqli_fetch_all($candidateQuery, MYSQLI_ASSOC);
        }

        if ($userType == 'admin') {
            $query3 = "SELECT * from feedback_request  WHERE `interviewSessionId` = " . $interviewSessionId . " AND `candidateId` = " . $candidateId . " AND `interviewId` = " . $interviewId;
            $requestReviewSelectQryResult = mysqli_query($databaseConnection, $query3);

            if (mysqli_num_rows($requestReviewSelectQryResult) >= 1) {
                if ($isAccepted == 'Y') {
                    $fbr_status = 3;
                    $query2 = "UPDATE feedback_request SET `review_status` = '3' WHERE `interviewSessionId` = " . $interviewSessionId . " AND `candidateId` = " . $candidateId . " AND `interviewId` = " . $interviewId;
                    $requestReviewUpdateQryResult = mysqli_query($databaseConnection, $query2);
                } else {

                    $fbr_status = -7;
                    $query2 = "UPDATE feedback_request SET `review_status` = '-7', `rejectedBy`=" . $userId . " WHERE `interviewSessionId` = " . $interviewSessionId . " AND `candidateId` = " . $candidateId . " AND `interviewId` = " . $interviewId;
                    $requestReviewUpdateQryResult = mysqli_query($databaseConnection, $query2);
                }

                if ($fbr_status == -7) {
                    $message = "<p>Dear " . $candidateDetails[0]['candidateName'] . ",</p>
                                        
                    <p>Your video resume is not approved. We request you to re-take the video resume interview till you are confident & satisfied. Link: " . $candidateDetails[0]['interviewLink'] . "</p>
                    <p>In case you have any doubt , please call us +91-9731107508.</p>
                    <p> Thanks & Regards,<br>GoPrac Team,<br>Bangalore</p>
                    ";
                    sendEmailToUser($candidateDetails[0]['candidateEmail'], null, 'Video resume NOT approved', $message);

                }
                $to_encode = array(
                    'result' => "Success",
                    'message' => "Information Saved  Successfully",
                    'status' => 1,
                    'fbr_status' => $fbr_status
                );
            } else {
                $fbr_status = -7;
                $query = "INSERT INTO `feedback_request`(`candidateId`,`interviewId`,`interviewSessionId`,rejectedBy,`requestDate`,`review_status`,`createdBy`) VALUES('$candidateId','$interviewId','$interviewSessionId','$userId',NOW(),-7,'$userId');";
                $requestReviewInsertQryResult = mysqli_query($databaseConnection, $query);
                $feedback_request_id = mysqli_insert_id($databaseConnection);

                $countApproved = mysqli_query($databaseConnection, "select  count(fr.id) as totalRequested from feedback_request fr inner join interview i on i.id = fr.interviewId where i.name='Video Resume' and fr.candidateId='" . $candidateId . "'");
                if (mysqli_num_rows > 0) {
                    $countResult = mysqli_fetch_all($candidateQuery, MYSQLI_ASSOC);

                    if ($countResult[0]['totalRequested'] == '0') {
                        $message = "<p>Dear " . $candidateDetails[0]['candidateName'] . ",</p>
                                        
                        <p>Your video resume is not approved. We request you to re-take the video resume interview till you are confident & satisfied. Link: " . $candidateDetails[0]['interviewLink'] . "</p>
                        <p>In case you have any doubt , please call us +91-9731107508.</p>
                        <p> Thanks & Regards,<br>GoPrac Team,<br>Bangalore</p>
                        ";
                        sendEmailToUser($candidateDetails[0]['candidateEmail'], null, 'Video resume NOT approved', $message);

                    }

                } else {
                    $message = "<p>Dear " . $candidateDetails[0]['candidateName'] . ",</p>
                                        
                    <p>Your video resume is not approved. We request you to re-take the video resume interview till you are confident & satisfied. Link: " . $candidateDetails[0]['interviewLink'] . "</p>
                    <p>In case you have any doubt , please call us +91-9731107508.</p>
                    <p> Thanks & Regards,<br>GoPrac Team,<br>Bangalore</p>
                    ";
                    sendEmailToUser($candidateDetails[0]['candidateEmail'], null, 'Video resume NOT approved', $message);
                }


                $to_encode = array(
                    'result' => "Success",
                    'message' => "Information Saved  Successfully",
                    'status' => 1,
                    'fbr_status' => $fbr_status
                );
            }
        } else {
            $to_encode = array(
                'result' => "Error",
                'message' => "You are Not Admin",
                'status' => -1

            );

        }

    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Request failed.",
            'status' => 0
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['shareFinalScoreExpertReview'])) {
    /* This function is used to store the finalscore parameters BY Narayan 22 jan 2022 */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $interviewId = $json['interviewId'];
        $candidateId = $json['candidateId'];
        $currentFeedbackRequestId = $json['currentFeedbackRequestId'];
        $interviewSessionId = $json['interviewSessionId'];
        $expertId = $json['expertId'];
        $createdAt = $json['createdAt'];
        $checkReasonOfRejection = '';
        $increment = 1;
        $followUpPresent = false;

        $assessmentType = mysqli_query($databaseConnection, "SELECT i.assessmenttype FROM interview i INNER JOIN feedback_request fr ON fr.interviewId = i.id WHERE fr.id IN ('" . $currentFeedbackRequestId . "' ) ");
        $assessmentTypeData = mysqli_fetch_all($assessmentType, MYSQLI_ASSOC)[0];

        $feedback_status_query = mysqli_query($databaseConnection, "UPDATE `feedback_status_question` SET `review_status` = '2' WHERE expertId = '" . $expertId . "' and feedbackRequestId = " . $currentFeedbackRequestId);

        // final submit subject tagging
        $StatusQuery = mysqli_query($databaseConnection, "select review_status from feedback_status_question where feedbackRequestId = '" . $currentFeedbackRequestId . "' group by review_status order by review_status");

        if (mysqli_num_rows($StatusQuery) == 1) {
            $values = mysqli_fetch_all($StatusQuery, MYSQLI_ASSOC);
            if ($values[0]['review_status'] == '2') {

                $feedbackStatusQuestionsQuery = mysqli_query($databaseConnection, "select m.questionId,fs.id as subjectId,q.isFollowUp,null as questionTag from feedback_request fr inner join mergedVideos m on m.interviewSessionId = fr.interviewSessionId INNER JOIN questions q ON q.id = m.questionId INNER JOIN favourite_subject fs ON fs.id = q.subjectId where fr.id = '" . $currentFeedbackRequestId . "' and m.questionId not in ( select questionId from expert_review where feedback_request_id='" . $currentFeedbackRequestId . "' and questionId is not null)");

                if (mysqli_num_rows($feedbackStatusQuestionsQuery) > 0) {
                    while ($row = mysqli_fetch_assoc($feedbackStatusQuestionsQuery)) {
                        $fsqQuestions[] = $row;
                    }
                }

                $expertReviewQuestionsQuery = mysqli_query($databaseConnection, "SELECT er.questionId,fs.id as subjectId,q.isFollowUp,er.questionTag from expert_review er inner join questions q on q.id=er.questionid inner join favourite_subject fs on fs.id=q.subjectId where er.feedback_request_id='" . $currentFeedbackRequestId . "'");

                if (mysqli_num_rows($expertReviewQuestionsQuery) > 0) {
                    while ($row = mysqli_fetch_assoc($expertReviewQuestionsQuery)) {
                        $fsqQuestions[] = $row;
                    }
                }

                $assignClusterId = parentChildClusterId($fsqQuestions);
                $questionsWithClusterId = $assignClusterId[0];
                $totalParentQuestions = $assignClusterId[1];
                $followUpPresent = $assignClusterId[2];

                // here we are checking whether every followup questions and parent questions has clusterId 
                if ($followUpPresent == true) {
                    foreach ($questionsWithClusterId as $key_a => $val_a) {
                        if (array_key_exists("clusterID", $questionsWithClusterId[$key_a])) {
                            $updatingSubjectTagQuery = mysqli_query($databaseConnection, "UPDATE expert_review er set er.clusterId=" . $questionsWithClusterId[$key_a]['clusterID'] . " where er.questionid=" . $questionsWithClusterId[$key_a]['questionId'] . " and er.feedback_request_id = " . $currentFeedbackRequestId . "");
                        }
                    }


                    for ($i = 0; $i < $totalParentQuestions; $i++) {
                        $questionsCluster = array();
                        $val = $i;
                        $QuestionsQuery = mysqli_query($databaseConnection, "SELECT er.questionId,fs.id as subjectId,q.isFollowUp,er.questionTag from expert_review er inner join questions q on q.id=er.questionid inner join favourite_subject fs on fs.id=q.subjectId where er.clusterId=" . $val . " and er.feedback_request_id='" . $currentFeedbackRequestId . "'");

                        if (mysqli_num_rows($QuestionsQuery) > 0) {
                            while ($row = mysqli_fetch_assoc($QuestionsQuery)) {
                                $questionsCluster[] = $row;
                            }

                            checkClusterGoodBad($databaseConnection, $questionsCluster, $currentFeedbackRequestId, $techIssueTolerance);
                            unset($questionsCluster);
                        }
                    }
                }
            }
        }
        // 

        if ($assessmentTypeData['assessmenttype'] == 'stepper') {

            // Added for checking the score greater than or not for stepper assessment Sibin 16 august 2022 hold status is 9

            $checkAverage = mysqli_query($databaseConnection, "SELECT review_status from feedback_status_question fsq inner join questions q on q.id = fsq.questionId inner join favourite_subject fs on fs.id = q.subjectId where fsq.feedbackRequestId = '" . $currentFeedbackRequestId . "' and fs.id=178 group by fsq.review_status");

            if (mysqli_num_rows($checkAverage) == 1) {
                $values = mysqli_fetch_all($checkAverage, MYSQLI_ASSOC);
                if ($values[0]['review_status'] == '2') {
                    // $behaviouralSubQuery = mysqli_query($databaseConnection, "SELECT AVG(overallRating) as behavioral from expert_review er inner join questions q on q.id=er.questionId inner join favourite_subject fs on q.subjectId = fs.id where er.feedback_request_id = '" . $currentFeedbackRequestId . "' and fs.id=178 and er.overAllRating !='videoIssue' and er.overallRating is not null");
                    // $behaviouralSubQueryResult = mysqli_fetch_assoc($behaviouralSubQuery);
                    // $behaviouralSubScore = $behaviouralSubQueryResult['behavioral'];
                    $subjectClusterAverage = clusterScore($databaseConnection, $currentFeedbackRequestId, '178');
                    $behaviouralSubScore = $subjectClusterAverage / 2;

                    if ($behaviouralSubScore >= 4) {
                        $fbrQuery = "INSERT INTO feedback_status_question(feedbackRequestId, questionId, review_status) select fr.id as feedbackRequestId, m.questionId, 0 as review_status from feedback_request fr inner join mergedVideos m on m.interviewSessionId = fr.interviewSessionId where fr.id = '" . $currentFeedbackRequestId . "' and m.questionId not in ( select questionId from feedback_status_question where feedbackRequestId='" . $currentFeedbackRequestId . "' )";
                        $setQuestionStatus = mysqli_query($databaseConnection, $fbrQuery);

                    } else {
                        if ($followUpPresent == true) {
                            $getFeedbackStatusReview = mysqli_query($databaseConnection, "UPDATE `feedback_request` SET `review_status` = '2' WHERE id = " . $currentFeedbackRequestId);
                        }

                        $stepperRejectedQuery = mysqli_query($databaseConnection, "INSERT INTO expert_review (interviewId,candidateId,questionId,subjectTag,review_type,feedback_request_id,overallRating) select fr.interviewId,fr.candidateId,m.questionId,'notAssessed','question',fr.id as feedbackRequestId,0 from feedback_request fr inner join mergedVideos m on m.interviewSessionId = fr.interviewSessionId where fr.id = " . $currentFeedbackRequestId . " and m.questionId not in ( select questionId from feedback_status_question where feedbackRequestId=" . $currentFeedbackRequestId . " )");

                        $fbrQuery = "INSERT INTO feedback_status_question(feedbackRequestId, expertId, questionId, review_status) select fr.id as feedbackRequestId, 62 as expertId, m.questionId, 2 as review_status from feedback_request fr inner join mergedVideos m on m.interviewSessionId = fr.interviewSessionId where fr.id = '" . $currentFeedbackRequestId . "' and m.questionId not in ( select questionId from feedback_status_question where feedbackRequestId='" . $currentFeedbackRequestId . "' )";
                        $setQuestionStatus = mysqli_query($databaseConnection, $fbrQuery);

                        $checkReasonOfRejection = 'Behavioural subject needs improvment';
                        $interviewQuery = "SELECT i.id AS interviewId, i.name AS interviewname, i.description AS interviewDescription, " . " p.id AS panelId, p.name AS panelName, p.emailid AS panelEmail, p.phonenumber AS panelPhoneNumber " . " FROM interview AS i, panel AS p " . " WHERE p.id = i.panelId AND i.id = " . $interviewId;
                        $interviewQueryResult = mysqli_query($databaseConnection, $interviewQuery);
                        $interviewDetails = $interviewQueryResult->fetch_assoc();

                        $userQuery = "SELECT CONCAT(firstName, ' ', IFNULL(lastName, '')) AS candidateName, emailId AS candidateEmail, mobileNumber AS candidateMobileNumber FROM users WHERE id = " . $candidateId;
                        $userQueryResult = mysqli_query($databaseConnection, $userQuery);
                        $candidateDetails = $userQueryResult->fetch_assoc();

                        $NewFeedbackReport = updateNewFeedbackReport($databaseConnection, $interviewSessionId);

                        if ($checkReasonOfRejection == 'Behavioural subject needs improvment') {
                            $message = "<p>Dear " . $candidateDetails['candidateName'] . ",</p>

                                                 <p>Thanks for practicing interviews on GoPrac.com. Your interview response to the interview named " . $interviewDetails['interviewname'] . " can't be reviewed by the expert. This is because, we feel that you have not taken this interview seriously.</p>
                                                 <p><b>Advice :</b>. In case you have any doubt , please call us +91-9731107508.</p>
                                                 <p> Thanks & Regards</p>
                                                 <p>GoPrac Team.</p>
                                                ";
                            sendEmailToUser($candidateDetails['candidateEmail'], null, 'Feedback Request Rejected', $message);

                            $emailSentQuery = mysqli_query($databaseConnection, "UPDATE feedback_request set isEmailSent = 'Y' WHere interviewSessionId = '" . $interviewSessionId . "'");
                        }

                    }
                }
            }

        }
        $getFeedbackStatusQuery = mysqli_query($databaseConnection, "select review_status from feedback_status_question where feedbackRequestId = '" . $currentFeedbackRequestId . "' group by review_status order by review_status");

        if (mysqli_num_rows($getFeedbackStatusQuery) == 1) {
            $values = mysqli_fetch_all($getFeedbackStatusQuery, MYSQLI_ASSOC);
            if ($values[0]['review_status'] == '2') {
                $overallRatingQuery = mysqli_query($databaseConnection, "SELECT round(AVG(overallRating),1) as aptitudeScore  FROM `expert_review` WHERE overallRating !='videoIssue' and overallRating is not null and  `feedback_request_id` = '" . $currentFeedbackRequestId . "'");

                $overallRatingResult = mysqli_fetch_assoc($overallRatingQuery);

                $overAllScore = $overallRatingResult['aptitudeScore'];

                $getFinalScore = mysqli_query($databaseConnection, "select er.*, erod.observationAreaId, erod.observationValueId from expert_review er inner join expert_review_observation_details erod on erod.expertReviewId = er.id where review_type = 'Final Score' and er.feedback_request_id = '" . $currentFeedbackRequestId . "' ");
                $expertReviewParamQry = '';
                if (mysqli_num_rows($getFinalScore) == 1) {
                    $result = mysqli_fetch_assoc($getFinalScore);
                    $expertReviewId = $result['id'];

                    if ($overAllScore >= 7) {
                        $expertReviewParamQry = "UPDATE expert_review_observation_details SET observationValueId = '90' WHERE expertReviewId = '" . $expertReviewId . "' AND observationAreaId = '24'";
                    } elseif ($overAllScore < 7 && $overAllScore > 4) {
                        $expertReviewParamQry = "UPDATE expert_review_observation_details SET observationValueId = '89' WHERE expertReviewId = '" . $expertReviewId . "' AND observationAreaId = '24'";
                    } elseif ($overAllScore <= 4) {
                        $expertReviewParamQry = "UPDATE expert_review_observation_details SET observationValueId = '88' WHERE expertReviewId = '" . $expertReviewId . "' AND observationAreaId = '24'";
                    }
                    $expertReviewParamQryResult = mysqli_query($databaseConnection, $expertReviewParamQry);
                } else {
                    $expertSql = "INSERT INTO `expert_review`(`interviewId`, `candidateId`, `review_type`, feedback_request_id) VALUES('$interviewId', '$candidateId', 'Final Score', $currentFeedbackRequestId)";
                    $experReviewQuery = mysqli_query($databaseConnection, $expertSql);
                    $expertReviewId = mysqli_insert_id($databaseConnection);

                    if ($overAllScore >= 7) {
                        $expertReviewParamQry = "INSERT INTO expert_review_observation_details(expertReviewId, observationAreaId, observationValueId) VALUES($expertReviewId, '24', '90')";
                    } elseif ($overAllScore < 7 && $overAllScore > 4) {
                        $expertReviewParamQry = "INSERT INTO expert_review_observation_details(expertReviewId, observationAreaId, observationValueId) VALUES($expertReviewId, '24', '89')";
                    } elseif ($overAllScore <= 4) {
                        $expertReviewParamQry = "INSERT INTO expert_review_observation_details(expertReviewId, observationAreaId, observationValueId) VALUES($expertReviewId, '24', '88')";
                    }
                    $expertReviewParamQryResult = mysqli_query($databaseConnection, $expertReviewParamQry);
                    $expertReviewParamDetailId = mysqli_insert_id($databaseConnection);

                    $expertReviewParamQryResult = mysqli_query($databaseConnection, "update `expert_review` set review_param_valueId=" . $expertReviewParamDetailId . " where id=" . $expertReviewId);
                }

                if ($checkReasonOfRejection == '' && $followUpPresent == true) {
                    $feedback_request_status_query = mysqli_query($databaseConnection, "UPDATE `feedback_request` SET `review_status` = '2' , `priority` = 0  WHERE id=" . $currentFeedbackRequestId);
                } else {
                    $feedback_request_status_query = 0;
                }

                /* this peice of code is added by narayan for sending completion email */
                if ($feedback_request_status_query) {
                    $query3 = "SELECT fr.* from feedback_request fr  WHERE id='" . $currentFeedbackRequestId . "' ";

                    $requestReviewSelectQryResult = mysqli_query($databaseConnection, $query3);

                    if (mysqli_num_rows($requestReviewSelectQryResult) >= 1) {

                        $feedbackData = mysqli_fetch_assoc($requestReviewSelectQryResult);
                        if ($feedbackData['review_status'] == 2) {
                            $NewFeedbackReport = updateNewFeedbackReport($databaseConnection, $interviewSessionId);
                            if ($feedbackData['isEmailSent'] == 'N') {

                                $sql2 = "select u.firstName AS candidateDetails,u.emailId AS contactEmail,i.name AS interviewDetails,p.name AS panelDetails,u.mobileNumber from users u, interview i, panel p, ratings r where r.candidateId = u.id and r.interviewId = i.id and i.panelId = p.id and interviewSessionId =" . $interviewSessionId;


                                $sql2Query = mysqli_query($databaseConnection, $sql2);
                                $values = mysqli_fetch_assoc($sql2Query);

                                $companyQuery = "select ac.name from feedback_request fr inner join interview i on i.id=fr.interviewId inner join aspiration_company ac on ac.id=i.companyId where fr.id ='" . $currentFeedbackRequestId . "'";
                                $companyQueryResult = mysqli_query($databaseConnection, $companyQuery);
                                $companyValues = mysqli_fetch_assoc($companyQueryResult);

                                $iReviewlink = $emailApiHost . "/review?i=" . $interviewId . "&c=" . $candidateId . "&s=" . $interviewSessionId;

                                expertCompleteReviewEmail($databaseConnection, $values, $interviewSessionId, $createdAt, $iReviewlink, $companyValues);


                                $emailSentQuery = mysqli_query($databaseConnection, "UPDATE feedback_request set isEmailSent = 'Y' WHere interviewSessionId = '" . $interviewSessionId . "'");

                            }

                            // TO INSERT THE SKILL % IN SKILLMATCH TABLE
                            $skillScores = getskillMatch($databaseConnection, "fbr.id  in (" . $currentFeedbackRequestId . ") and ");

                            $deleteQuerySkillMatch = mysqli_query($databaseConnection, "DELETE FROM skillMatch where feedbackRequestId=" . $currentFeedbackRequestId . "");
                            if (!empty($skillScores)) {
                                for ($i = 0; $i < count($skillScores); $i++) {
                                    for ($j = 0; $j < count($skillScores[$i]); $j++) {
                                        $insertQuerySkillMatch = "INSERT INTO `skillMatch`(`feedbackRequestId`, `candidateId`, `subjectType`,`skillPercent`) VALUES ('" . $skillScores[$i][$j]['feedbackRequestId'] . "','" . $skillScores[$i][$j]['candidateId'] . "', NULLIF('" . $skillScores[$i][$j]['subjectType'] . "', ''), NULLIF('" . $skillScores[$i][$j]['skillPercent'] . "', ''))";
                                        mysqli_query($databaseConnection, $insertQuerySkillMatch);
                                    }
                                }
                            }
                            // TO INSERT THE SKILL % IN SKILLMATCH TABLE END

                        }
                    }

                }


                if ($checkReasonOfRejection == 'Behavioural subject needs improvment') {
                    $updatingSubjectTagQuery = mysqli_query($databaseConnection, "UPDATE expert_review er inner join questions q on q.id=er.questionId inner join favourite_subject fs on fs.id=q.subjectId set er.subjectTag='notAssessed' where fs.id!=178 and er.feedback_request_id = " . $currentFeedbackRequestId . "");
                }




                $to_encode = array(
                    'result' => "Success",
                    'message' => "Final Expert Review Saved.",
                    'status' => 1,


                );

            } else {
                $to_encode = array(
                    'result' => "Success",
                    'message' => "Final Expert Review Shared.",
                    'status' => 1
                );
            }
        } else {
            $to_encode = array(
                'result' => "Success",
                'message' => "Final Expert Review Shared.",
                'status' => 1
            );
        }

    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "ExperReview shared failed.",
            'status' => -1
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['oldShareFinalScoreExpertReview'])) {
    // This function was  used  till 1st week of Feb 2022 to store the finalscore parameters
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $interviewId = $json['interviewId'];
        $candidateId = $json['candidateId'];
        $currentFeedbackRequestId = $json['currentFeedbackRequestId'];
        $interviewSessionId = $json['interviewSessionId'];
        $expertId = $json['expertId'];
        $createdAt = $json['createdAt'];

        $feedback_status_query = mysqli_query($databaseConnection, "UPDATE `feedback_status_question` SET `review_status` = '2' WHERE expertId = '" . $expertId . "' and feedbackRequestId = " . $currentFeedbackRequestId);

        $getFeedbackStatusQuery = mysqli_query($databaseConnection, "select review_status from feedback_status_question where feedbackRequestId = '" . $currentFeedbackRequestId . "' group by review_status order by review_status");
        if (mysqli_num_rows($getFeedbackStatusQuery) == 1) {
            $values = mysqli_fetch_all($getFeedbackStatusQuery, MYSQLI_ASSOC);
            if ($values[0]['review_status'] == '2') {
                $overallRatingQuery = mysqli_query($databaseConnection, "SELECT SUM(CASE WHEN `overallRating` = 'good' THEN 1 ELSE 0 END) AS Good, SUM(CASE WHEN `overallRating` = 'acceptable' THEN 1 ELSE 0 END) AS Acceptable, SUM(CASE WHEN `overallRating` = 'needsImprovement' THEN 1 ELSE 0 END) AS Improvement FROM `expert_review` WHERE `feedback_request_id` = '" . $currentFeedbackRequestId . "'");
                $overallRatingResult = mysqli_fetch_assoc($overallRatingQuery);
                $score = (($overallRatingResult['Good']) * 15) + (($overallRatingResult['Acceptable']) * 10) + (($overallRatingResult['Improvement']) * 0);
                $totalscore = (($overallRatingResult['Good']) + ($overallRatingResult['Acceptable']) + ($overallRatingResult['Improvement'])) * 15;
                if ($score == 0) {
                    $overAllScore = 0;
                } else {
                    $overAllScore = ($score * 100) / $totalscore;
                }

                $getFinalScore = mysqli_query($databaseConnection, "select er.*, erod.observationAreaId, erod.observationValueId from expert_review er inner join expert_review_observation_details erod on erod.expertReviewId = er.id where review_type = 'Final Score' and er.feedback_request_id = '" . $currentFeedbackRequestId . "' ");
                $expertReviewParamQry = '';
                if (mysqli_num_rows($getFinalScore) == 1) {
                    $result = mysqli_fetch_assoc($getFinalScore);
                    $expertReviewId = $result['id'];

                    if ($overAllScore > 83.33) {
                        $expertReviewParamQry = "UPDATE expert_review_observation_details SET observationValueId = '90' WHERE expertReviewId = '" . $expertReviewId . "' AND observationAreaId = '24'";
                    } elseif ($overAllScore <= 83.33 && $overAllScore >= 66.66) {
                        $expertReviewParamQry = "UPDATE expert_review_observation_details SET observationValueId = '89' WHERE expertReviewId = '" . $expertReviewId . "' AND observationAreaId = '24'";
                    } elseif ($overAllScore < 66.66) {
                        $expertReviewParamQry = "UPDATE expert_review_observation_details SET observationValueId = '88' WHERE expertReviewId = '" . $expertReviewId . "' AND observationAreaId = '24'";
                    }
                } else {
                    $expertSql = "INSERT INTO `expert_review`(`interviewId`, `candidateId`, `review_type`, feedback_request_id) VALUES('$interviewId', '$candidateId', 'Final Score', $currentFeedbackRequestId)";
                    $experReviewQuery = mysqli_query($databaseConnection, $expertSql);
                    $expertReviewId = mysqli_insert_id($databaseConnection);

                    if ($overAllScore > 83.33) {
                        $expertReviewParamQry = "INSERT INTO expert_review_observation_details(expertReviewId, observationAreaId, observationValueId) VALUES($expertReviewId, '24', '90')";
                    } elseif ($overAllScore <= 83.33 && $overAllScore >= 66.66) {
                        $expertReviewParamQry = "INSERT INTO expert_review_observation_details(expertReviewId, observationAreaId, observationValueId) VALUES($expertReviewId, '24', '89')";
                    } elseif ($overAllScore < 66.66) {
                        $expertReviewParamQry = "INSERT INTO expert_review_observation_details(expertReviewId, observationAreaId, observationValueId) VALUES($expertReviewId, '24', '88')";
                    }
                }
                $expertReviewParamQryResult = mysqli_query($databaseConnection, $expertReviewParamQry);
                $expertReviewParamDetailId = mysqli_insert_id($databaseConnection);

                $expertReviewParamQryResult = mysqli_query($databaseConnection, "update `expert_review` set review_param_valueId=" . $expertReviewParamDetailId . " where id=" . $expertReviewId);

                $feedback_request_status_query = mysqli_query($databaseConnection, "UPDATE `feedback_request` SET `review_status` = '-3' WHERE id=" . $currentFeedbackRequestId);

                $to_encode = array(
                    'result' => "Success",
                    'message' => "Final Expert Review Saved.",
                    'status' => 1
                );
            } else {
                $to_encode = array(
                    'result' => "Success",
                    'message' => "Final Expert Review Shared.",
                    'status' => 1
                );
            }
        } else {
            $to_encode = array(
                'result' => "Success",
                'message' => "Final Expert Review Shared.",
                'status' => 1
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "ExperReview shared failed.",
            'status' => -1
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['saveFinalScoreExpertReview'])) {
    // This function is used to store the finalscore parameters
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $interviewId = $json['interviewId'];
        $candidateId = $json['candidateId'];
        $streamId = $json['streamId'];
        $currentFeedbackRequestId = $json['currentFeedbackRequestId'];
        $finalValueArr = $json['finalValuesArray'];
        $insertedCount = 0;
        $review_type = $json['questionType'];
        /*changes by anil 18-10-2018*/
        $expert_review_suggestion = addslashes($json['expert_review_suggestion']);
        $expertReviewId = $json['expert_review_id'];
        $interviewSessionId = $json['interviewSessionId'];
        $createdAt = $json['createdAt'];
        if ($expertReviewId == 0) {
            $expertSql = "INSERT INTO `expert_review`(`interviewId`,`candidateId`,`streamId`,`review_type`,feedback_request_id,expert_review_suggestion) VALUES('$interviewId', '$candidateId','$streamId','$review_type',$currentFeedbackRequestId, NULLIF('$expert_review_suggestion', ''))";
            $experReviewQuery = mysqli_query($databaseConnection, $expertSql);
            $expertReviewId = mysqli_insert_id($databaseConnection);
        } else {
            $expertReviewId = $json['expert_review_id'];
            $experReviewQuery = mysqli_query($databaseConnection, 'DELETE FROM `expert_review_observation_details` where expertReviewId=' . $expertReviewId);
            $expert_review_suggestion_query = mysqli_query($databaseConnection, "update expert_review set expert_review_suggestion = NULLIF('$expert_review_suggestion', '') where id=" . $expertReviewId);
        }

        /*changes by anil 18-10-2018*/
        for ($i = 0; $i < sizeof($finalValueArr); $i++) {
            if ($expertReviewId != 0) {
                $value = $finalValueArr[$i];
                $expertReviewParamQry = "INSERT INTO expert_review_observation_details(expertReviewId, observationValueId)" .
                    " VALUES($expertReviewId, $value)";
                $expertReviewParamQryResult = mysqli_query($databaseConnection, $expertReviewParamQry);
                $expertReviewParamDetailId = mysqli_insert_id($databaseConnection);

                $updateObservationAreaIdQryResult = mysqli_query($databaseConnection, "UPDATE expert_review_observation_details erod INNER JOIN observation_values ov ON ov.id = erod.observationValueId SET erod.observationAreaId = ov.observation_id where erod.observationAreaId IS NULL AND erod.expertReviewId=" . $expertReviewId);

                $updateRequestFeedbackStatus = "UPDATE feedback_request SET review_status =1 WHERE id = '" . $expertReviewParamDetailId . "' ";
                $updateRequestFeedbackStatusResult = mysqli_query($databaseConnection, $updateRequestFeedbackStatus);
                if ($expertReviewParamDetailId > 0) {
                    $insertedCount = $insertedCount + 1;
                }
                /*changes by anil 18-10-2018*/
                $expertReviewParamQryResult = mysqli_query($databaseConnection, "update `expert_review` set review_param_valueId=" . $expertReviewParamDetailId . " where id=" . $expertReviewId);
            }

            /*changes by anil 18-10-2018*/
        }
        if ($insertedCount == sizeof($finalValueArr)) {
            $to_encode = array(
                'result' => "Success",
                'message' => "Final Expert Review Saved.",
                'status' => 1,
                'finalReviewId' => $expertReviewId
            );
        } else {
            $to_encode = array(
                'result' => "error",
                'errorCode' => "Some review parameters may not be saved!.",
                'status' => -1,
                'submittedReviewParameters' => sizeof($finalValueArr),
                'savedReviewParameters' => $insertedCount,
                'query' => $expertSql
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "ExperReview Creation failed.",
            'status' => -1
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['acceptReviewInterview'])) {
    // This function is used to accept the Review Interview
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $feedbackRequestId = $json['feedbackRequestId'];
        $panelId = $json['panelId'];

        $feedback_request_status_query = mysqli_query($databaseConnection, "UPDATE `feedback_request` SET  delegationId = '" . $panelId . "' WHERE   id=" . $feedbackRequestId);
        if ($feedback_request_status_query) {
            $to_encode = array(
                'result' => "Success",
                'message' => "ExpertReview accepted.",
                'status' => 1
            );
        } else {
            $to_encode = array(
                'result' => "Success",
                'message' => "ExpertReview not accept.",
                'status' => 0
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "ExpertReview not accepted.",
            'status' => -1
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['submitRating'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $interviewSessionId = $json['interviewSessionId'];
        $interviewId = $json['interviewId'];
        $candidateId = $json['candidateId'];
        $createdAt = $json['createdAt'];
        $isSubmit = $json['isSubmit'];
        $feedbackReason = $json['feedbackReason'] ?? '';
        $userInterface = $json['userInterface'];
        $userInterface1 = $json['userInterface1'];
        $isRetake = $json['isRetake'];
        //$interviewQuality = $json['interviewQuality'];
        //$relevantQues = $json['relevantQues'];
        //$recommendInt = $json['recommendInt'];
        /* if ($json['complexBtn'] != '') {
            $complexBtn = implode(',', $json['complexBtn']);
        } else {
            $complexBtn = $json['complexBtn'];
        } */

        if ($json['relevance'] != '') {
            $relevance = implode(',', $json['relevance']);
        } else {
            $relevance = $json['relevance'];
        }


        $bandwidth = $json['bandwidth'];
        $expert = $json['expert'];
        // $relevance = $json['relevance'];
        $otherWork = $json['otherWork'];
        $siteIssue = $json['siteIssue'];
        $queryCheck = "SELECT * FROM `ratings` WHERE interviewSessionId ='" . $interviewSessionId . "'";
        $queryCheckResult = mysqli_query($databaseConnection, $queryCheck);
        if (mysqli_num_rows($queryCheckResult) > 0) {
            $sql = "UPDATE `ratings` SET `isSubmit`='" . $isSubmit . "', `feedbackReason` = '$feedbackReason', `userInterface` = '$userInterface', `questionQuality` = '$userInterface1', `bandwidth` = '$bandwidth', `expert` = '$expert',`relevance` = '$relevance',`otherWork`='" . $otherWork . "',`siteIssue`='" . $siteIssue . "' WHERE interviewSessionId ='" . $interviewSessionId . "'";
        } else {
            $sql = "INSERT INTO `ratings` 
            (`interviewSessionId`,`interviewId`, `candidateId`, `isSubmit`, `feedbackReason`, `userInterface`, `questionQuality`, `bandwidth`, `expert`,`relevance`,`otherWork`, `siteIssue`) VALUES 
            ('$interviewSessionId','$interviewId', '$candidateId', '$isSubmit', '$feedbackReason', '$userInterface', '$userInterface1', '$bandwidth','$expert','$relevance', '$otherWork', '$siteIssue');";
        }
        $usersQuery = mysqli_query($databaseConnection, $sql);
        if ($usersQuery) {
            if ($isSubmit == 'Y' && $isRetake == 'N') {
                $sql2 = "select u.firstName AS candidateDetails,u.emailId AS contactEmail,i.name AS interviewDetails,p.name AS panelDetails from users u, interview i, panel p, ratings r where r.candidateId = u.id and r.interviewId = i.id and i.panelId = p.id and interviewSessionId =" . $interviewSessionId;
                $sql2Query = mysqli_query($databaseConnection, $sql2);
                $values = mysqli_fetch_assoc($sql2Query);
                $feedbackRequestLink = $emailApiHost . "/review?i=" . $interviewId . "&c=" . $candidateId . "&s=" . $interviewSessionId;
                // if($values['interviewDetails'] !='Video Resume'){
                //     studentCompleteInterviewEmail($values['contactEmail'], $values['candidateDetails'], $values['interviewDetails'], $values['panelDetails'], $createdAt, $feedbackRequestLink);

                // }
            }
            $userId = mysqli_insert_id($databaseConnection);
            $to_encode = array(
                'result' => "Success",
                'message' => "review submitted",
                'status' => 1
            );
        } else {
            $to_encode = array(
                'result' => "error",
                'errorCode' => "review submission failed.",
                'status' => 0,
                'query' => $sql
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "review submission failed.",
            'status' => -1,
            'query' => $sql
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['submitpaidFeedback'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['candidateId'];
        $interested = $json['isInterested'];
        $url = $json['url'];

        $checking = mysqli_query($databaseConnection, "select * from detail_feedback_request where candidateId=" . $candidateId . " and url='" . $url . "'");

        if (mysqli_num_rows($checking) >= 1) {
            $rowid = mysqli_fetch_assoc($checking)['id'];
            if ($interested == 'Yes') {
                $sql = "update detail_feedback_request set requestedDate=now(),interested='" . $interested . "' where candidateId=" . $candidateId . " and id=" . $rowid . "";
            } else {
                $sql = "update detail_feedback_request set requestedDate=now(),interested='" . $interested . "' where candidateId=" . $candidateId . " and id=" . $rowid . "";
            }
            $sqlQuery = mysqli_query($databaseConnection, $sql);

        } else {
            $sql = "insert into detail_feedback_request(`candidateId`,`url`,`requestedDate`,`interested`) values($candidateId,'$url',now(),'$interested')";
            $sqlQuery = mysqli_query($databaseConnection, $sql);
        }

        if ($sqlQuery) {
            $to_encode = array(
                'result' => "Success",
                'message' => "interest submitted",
                'status' => 1
            );
        } else {
            $to_encode = array(
                'result' => "error",
                'errorCode' => "interest submission failed.",
                'status' => 0,
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "interest submission failed.",
            'status' => -1,

        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['inserting_usersView'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['candidateId'];
        $url = $json['url'];

        $checking = mysqli_query($databaseConnection, "select * from usersView where candidateId=" . $candidateId . " and url='" . $url . "'");

        if (mysqli_num_rows($checking) >= 1) {
            $rowId = mysqli_fetch_assoc($checking)['id'];
            $sql = "update usersView set detailedView=1,learningView=1,paidStatus='Y' where candidateId=" . $candidateId . " and id=" . $rowId . "";
            $sqlQuery = mysqli_query($databaseConnection, $sql);
        } else {
            $sql = "insert into usersView(`candidateId`,`url`,`detailedView`,`learningView`,`paidStatus`) values($candidateId,'$url',1,1,'Y')";
            $sqlQuery = mysqli_query($databaseConnection, $sql);

            $userDetails = mysqli_query($databaseConnection, "select emailId as candidateEmail,firstName as candidateName from users where id=" . $candidateId . "");
            $candidateDetails = mysqli_fetch_assoc($userDetails);

            //sending details view confirmation mail

            if (mysqli_num_rows($userDetails) >= 1) {
                $message = "<p>Dear " . $candidateDetails['candidateName'] . ",</p>
                                <p>Greetings from GoPrac.com ! </p>
                                 <p>Thank you for showing interest for detailed feedback. Your detailed feedback report is ready.  <a href='" . $url . "'>Click Here </a> to access it.</p>
                                 <p> Thanks & Regards</p>
                                 <p>GoPrac.com</p>
                                 <p>Bangalore</p>
                                ";
                sendEmailToUser($candidateDetails['candidateEmail'], null, 'Approved Detailed Feedback', $message);
            }
        }
        if ($sqlQuery) {
            $to_encode = array(
                'result' => "Success",
                'message' => "interest submitted",
                'status' => 1
            );
        } else {
            $to_encode = array(
                'result' => "error",
                'errorCode' => "interest submission failed.",
                'status' => 0,
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "interest submission failed.",
            'status' => -1,

        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['hiding_usersView'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['candidateId'];
        $url = $json['url'];

        $checking = mysqli_query($databaseConnection, "select * from usersView where candidateId=" . $candidateId . " and url='" . $url . "'");

        if (mysqli_num_rows($checking) >= 1) {
            $rowId = mysqli_fetch_assoc($checking)['id'];
            $sql = "update usersView set detailedView=0,learningView=0,paidStatus='N' where candidateId=" . $candidateId . " and id=" . $rowId . "";

            $sqlQuery = mysqli_query($databaseConnection, $sql);
        } else {
            $sqlQuery = 0;
        }
        if ($sqlQuery) {
            $to_encode = array(
                'result' => "Success",
                'message' => "interest submitted",
                'status' => 1
            );
        } else {
            $to_encode = array(
                'result' => "error",
                'errorCode' => "interest submission failed.",
                'status' => 0,
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "interest submission failed.",
            'status' => -1,

        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['assessmentReport_visit'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $candidateId = $json['candidateId'];
        $userType = $json['userType'];
        $url = $json['url'];
        $interviewId = $json['interviewId'];
        $interviewSessionId = $json['interviewSessionId'];
        $viewedStatus = $json['viewedStatus'];
        $status = false;

        if ($userId == $candidateId) {
            $checking = mysqli_query($databaseConnection, "select * from detail_feedback_request where candidateId=" . $candidateId . " and interviewSessionId='" . $interviewSessionId . "'");

            if (mysqli_num_rows($checking) >= 1) {
                $result = mysqli_fetch_assoc($checking);

                if (($result && $result['viewedStatus'] == 'download' && $viewedStatus == 'download') || ($result && $result['viewedStatus'] == 'Viewed' && $viewedStatus == 'download') || ($result && $result['viewedStatus'] == 'download' && $viewedStatus == 'pay')) {
                    $rowId = $result['id'];
                    $sql = "update detail_feedback_request set url='" . $url . "',interviewId=" . $interviewId . ",interviewSessionId=" . $interviewSessionId . ",viewedStatus='" . $viewedStatus . "',viewedDate=now() where candidateId=" . $candidateId . " and interviewSessionId=" . $interviewSessionId . "";
                    $sqlQuery = mysqli_query($databaseConnection, $sql);
                    $status = true;
                } else {
                    $status = true;
                }
            } else {
                $sql = "insert into detail_feedback_request(`candidateId`,`url`,`viewedStatus`,`interviewId`,`interviewSessionId`,`viewedDate`) values($candidateId,'$url','$viewedStatus',$interviewId,$interviewSessionId,now())";
                $sqlQuery = mysqli_query($databaseConnection, $sql);
                $status = true;
            }

            if ($status) {
                $to_encode = array(
                    'result' => "Success",
                    'message' => "submitted",
                    'status' => 1
                );
            } else {
                $to_encode = array(
                    'result' => "error",
                    'errorCode' => "submission failed.",
                    'status' => 0,
                );
            }

        } else {
            if ($userType == 'admin') {

                $to_encode = array(
                    'result' => "Success",
                    'message' => "status not updated for admin action",
                    'status' => 1
                );
            } else {
                $to_encode = array(
                    'result' => "error",
                    'message' => "action not alowed for current user",
                    'status' => 0
                );
            }
        }

    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "visit submission failed.",
            'status' => -1,

        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['createGeneric_link'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['candidateId'];


        $GenericLink = mysqli_query($databaseConnection, "select concat('review?i=',max(interviewId),'&c=',candidateId,'&s=',max(interviewSessionId)) as genericlink,max(interviewId) as interviewId,candidateId,max(interviewSessionId) as interviewSessionId from feedback_request where candidateId=" . $candidateId . " and review_status=2");

        if (mysqli_num_rows($GenericLink) >= 1) {
            $url = mysqli_fetch_all($GenericLink, MYSQLI_ASSOC);

            $to_encode = array(
                'result' => "Success",
                'message' => "data found",
                'url' => $url,
                'status' => 1
            );
        } else {
            $to_encode = array(
                'result' => "error",
                'errorCode' => "no data found",
                'status' => 0,
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "fetching data failed.",
            'status' => -1,

        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['getRatings'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $sessionId = $json['sessionId'];
        $isSubmit = $json['isSubmit'];

        $sql = "select * from `ratings` where interviewSessionId='" . $sessionId . "' and isSubmit='" . $isSubmit . "'";
        $result = mysqli_query($databaseConnection, $sql);
        if ($result) {
            if (mysqli_num_rows($result) >= 1) {
                $values = mysqli_fetch_all($result, MYSQLI_ASSOC);
                $to_encode = $values;
            } else {
                $to_encode = array(
                    'result' => "error",
                    'status' => 0,
                    'errorCode' => "no ratings found"
                );
            }
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 1,
                'query' => $sql

            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving ratings information"
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['submitTrainingVideoFeedback'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['candidateId'];
        $isSatisfiedWithInterviewFeedback = $json['isSatisfiedWithInterviewFeedback'];
        $interviewTypesForPractice = $json['interviewTypesForPractice'];

        $sql = "INSERT INTO `training_video_feedback`" . "(`candidateId`, `is_satisfied_with_interview_feedback`, `interview_types_for_practice`, `created_by`) VALUES " . "($candidateId, '$isSatisfiedWithInterviewFeedback', '$interviewTypesForPractice', $candidateId)";

        $trainingVideoFeedbackQuery = mysqli_query($databaseConnection, $sql);
        if ($trainingVideoFeedbackQuery) {
            $trainingVideoFeedbackId = mysqli_insert_id($databaseConnection);
            $to_encode = array(
                'result' => "Success",
                'message' => "Training Video Feedback Submitted",
                'status' => 1
            );
        } else {
            $to_encode = array(
                'result' => "error",
                'errorCode' => "Training Video Feedback Submission Failed!.",
                'status' => 0,
                'query' => $sql,
                'json' => $json
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Training Video Feedback Submission Failed!.",
            'status' => -1,
            'query' => $sql,
            'json' => $json
        );
    }

    echo json_encode($to_encode);
} else if (isset($_GET['updateExpertActivityData'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['userId'];
        $userType = $json['userType'];

        $sql = "UPDATE panel p inner join  (Select ers.feedbackGivenBy , max(ers.createdAt) as Active from expert_review ers  group by ers.feedbackGivenBy  order by ers.createdAt desc) as temp on temp.feedbackGivenBy = p.id SET p.lastActiveOnAssessment = temp.Active";

        $updateExpertActivity = mysqli_query($databaseConnection, $sql);
        if ($updateExpertActivity) {

            $to_encode = array(
                'result' => "Success",
                'message' => "Expert Activity Date updated",
                'status' => 1,
            );
        } else {
            $to_encode = array(
                'result' => "error",
                'errorCode' => "Expert Activity Date updated Failed!.",
                'status' => 0,
                'query' => $sql
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Expert Activity Date updated Failed!.",
            'status' => -1,
            'json' => $json
        );
    }

    echo json_encode($to_encode);
} else if (isset($_GET['submitFeedbackOnFeedback'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['candidateId'];
        $feedback_request_id = $json['feedback_request_id'];
        $interviewSessionId = $json['interviewSessionId'];
        $isAgree = $json['isAgree'];
        // $otherFeedback = $json['otherFeedback'];
        /* $isAgree = $json['isAgree'];
        $detailedFeedback = $json['detailedFeedback'];
        $actionableInputs = $json['actionableInputs'];
        $improvingYourself = $json['improvingYourself'];
        $otherFeedback = $json['otherFeedback'];
        $isAgreeMsg = $json['isAgreeMsg'];
        $detailedFeedbackMsg = $json['detailedFeedbackMsg'];
        $actionableInputsMsg = $json['actionableInputsMsg'];
        $improvingYourselfMsg = $json['improvingYourselfMsg'];*/

        $sqlCheck = "select id from `feedbackonfeedback` where interviewSessionId='" . $interviewSessionId . "' and candidateId ='" . $candidateId . "' and feedback_request_id ='" . $feedback_request_id . "'";
        //echo $sqlCheck;
        $result = mysqli_query($databaseConnection, $sqlCheck);
        if (mysqli_num_rows($result) > 0) {
            $row = mysqli_fetch_assoc($result);
            $ids = $row['id'];
            if ($ids) {
                $updateQuery = "update feedbackonfeedback set isAgree = '" . $isAgree . "' where id=  '" . $ids . "'";
                $updateQueryResult = mysqli_query($databaseConnection, $updateQuery);
                if ($updateQueryResult) {
                    $to_encode = array(
                        'result' => "Success",
                        'message' => "Feedback On Feedback Updated",
                        'status' => 1,
                    );
                } else {
                    $to_encode = array(
                        'result' => "error",
                        'errorCode' => "Feedback On Feedback Update Failed!.",
                        'status' => 0,
                    );
                }
            }
        } else {
            $sql = "INSERT INTO `feedbackonfeedback` (`candidateId`, `feedback_request_id`, `interviewSessionId`,`isAgree`) VALUES ('$candidateId', '$feedback_request_id', '$interviewSessionId', '$isAgree')";

            $feedbackonfeedbackQuery = mysqli_query($databaseConnection, $sql);
            if ($feedbackonfeedbackQuery) {
                $feedbackonfeedbackId = mysqli_insert_id($databaseConnection);

                $updateFeedbackRequest = mysqli_query($databaseConnection, "update `feedback_request` set isFbOnFbGiven='Y' where id='" . $feedback_request_id . "' and interviewSessionId='" . $interviewSessionId . "'");

                $to_encode = array(
                    'result' => "Success",
                    'message' => "Feedback On Feedback Inserted",
                    'status' => 1,
                    'isUpdate' => $updateFeedbackRequest
                );
            } else {
                $to_encode = array(
                    'result' => "error",
                    'errorCode' => "Feedback On Feedback Insertion Failed!.",
                    'status' => 0,
                    'query' => $sql
                );
            }
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Feedback On Feedback Submission Failed!.",
            'status' => -1,
            'json' => $json
        );
    }

    echo json_encode($to_encode);
} else if (isset($_GET['putProfessionalInfo'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['candidateId'];
        $qualification = $json['qualification'];
        $course = $json['course'];
        $specialization = $json['specialization'];
        $college = $json['college'];
        $year = $json['year'];
        $sCode = $json['sCode'];

        /*
         * Check if the user has provided the subscription code or not
         * If the subscription code is not provided then fetch the default subscription code
         * And create the record for that user to use that subscription code valid till the s_end_date of that code.
         */
        if ($sCode == '') {
            $sql = "SELECT * FROM scodes WHERE s_is_multiple = 'Y' AND DATE(NOW()) BETWEEN s_starting_date AND s_end_date";
            $res = mysqli_query($databaseConnection, $sql);
            $code = '';
            $scodeArray = array();
            /**
             * If we get the record of default subscription code then we will add that subscription code for that user in sCodes table
             * Otherwise we will set proceedFlag = false to return an error.
             */
            if (mysqli_num_rows($res) >= 1) {
                while ($row = mysqli_fetch_assoc($res)) {
                    $code = $row['s_value'];
                    $scodeArray = $row;
                    break;
                }
                /*
                 * If we got a result for the default subscription code, then
                 * create a sCodes record for that user with this default sCode valid
                 * till the s_end_date of that subscription
                 */
                $insertDefaultSCodeQry = 0;
                if (count($scodeArray) > 0) {
                    $scodeSQL = "INSERT INTO scodes (s_value, s_starting_date, s_end_date, s_is_multiple, s_group, s_is_availed, userId) " . " VALUES('" . $scodeArray['s_value'] . "', '" . $scodeArray['s_starting_date'] . "', '" . $scodeArray['s_end_date'] . "', 'N', '1', 'N', '" . $candidateId . "')";

                    $insertDefaultSCodeQry = mysqli_query($databaseConnection, $scodeSQL);
                    if ($insertDefaultSCodeQry) {
                        $sCode = $scodeArray['s_value'];
                        $proceedFlag = true;
                    } else {
                        $proceedFlag = false;
                    }
                }
            } else {
                $proceedFlag = false;
            }
        } else {
            $proceedFlag = true;
        }
        //$proceedFlag = true;
        $sCodeSql = "select * from scodes where s_value='" . $sCode . "' and s_is_availed='N' and userId is null;";
        $query = mysqli_query($databaseConnection, $sCodeSql);

        $sql = "INSERT INTO `professionaldetails` 
        (`candidateId`, `qualification`, `specialization`, `college`, `year`) VALUES 
        ('$candidateId', '$qualification', '$specialization', '$college', '$year');";

        if (mysqli_num_rows($query) >= 1) {
            if ($proceedFlag) {
                $usersQuery = mysqli_query($databaseConnection, $sql);
                if ($usersQuery) {
                    $userId = mysqli_insert_id($databaseConnection);
                    $sCodeData = "update scodes set s_is_availed='Y' , userId='" . $candidateId . "' where s_value='" . $sCode . "';";
                    $sCodeQuery = mysqli_query($databaseConnection, $sCodeData);
                    if ($sCodeQuery) {
                        $to_encode = array(
                            'result' => "Success",
                            'message' => "Data Created.",
                            'status' => 1,
                            'query' => $sql
                        );
                    } else {
                        $to_encode = array(
                            'result' => "error",
                            'message' => "Subscription code updation failed.",
                            'status' => 3,
                            'query' => $sCodeData
                        );
                    }
                } else {
                    $to_encode = array(
                        'result' => "error",
                        'errorCode' => "professional info insertion failed",
                        'status' => 2,
                        'query' => $sql
                    );
                }
            }
        } else {
            /*Changes By Anil 04-10-2018*/
            $to_encode = array(
                'result' => "error",
                'errorCode' => "Subscription Code already used or Invalid.",
                //'insertQry' => $scodeSQL,
                'status' => 0,
                'query' => $sCodeSql
            );
            /*Changes By Anil 04-10-2018*/
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Data Creation failed.",
            'status' => -1,
            'query' => $sCodeSql
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getProfessionalInfo'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        // $candidateId = getDecrypt($json['userData'])->userId;
        $candidateId = $json['candidateId'];

        /***********************/
        $data2 = "select id,collegeName as college from colleges order by id=188,collegeName";
        $query2 = mysqli_query($databaseConnection, $data2);
        $values['college'] = mysqli_fetch_all($query2, MYSQLI_ASSOC);
        /**********************/

        $data = "SELECT p.*, c.collegeName, locations.cityName as currentLocationCityName, u.firstName, u.mobileNumber,u.gender,u.instituteCode
        FROM professionaldetails p
        LEFT JOIN users u ON u.id = p.candidateId
        LEFT join colleges c on p.college = c.id
        LEFT join locations on locations.id = p.currentLocation
        WHERE p.candidateId='" . $candidateId . "' limit 1";
        $query = mysqli_query($databaseConnection, $data);
        if (mysqli_num_rows($query) >= 1) {
            $values['professionaldetails'] = mysqli_fetch_all($query, MYSQLI_ASSOC)[0];
            $countColumn = count(array_filter($values['professionaldetails']));

            if (isset($values['professionaldetails']['skills']) && $values['professionaldetails']['skills'] !== "") {

                $data4 = "SELECT id, favourite_subject.favourite_subject as name FROM favourite_subject WHERE active='Y' and id IN(" . $values['professionaldetails']['skills'] . ")";

                $query4 = mysqli_query($databaseConnection, $data4);

                if (mysqli_num_rows($query4) >= 1) {
                    $resultRowArray4 = [];
                    while ($row = mysqli_fetch_assoc($query4)) {
                        $resultRowArray4[] = $row;
                    }
                    $values['professionaldetails']['skillList'] = $resultRowArray4;
                } else {
                    $values['professionaldetails']['skillList'] = null;
                }
            } else {
                $values['professionaldetails']['skillList'] = null;
            }

            $to_encode = $values;
        } else {
            $values[0] = array(
                'status' => 0,
                'result' => "noinfo",
                'errorCode' => "User information not avaialble",
                'query' => $data
            );
            $to_encode = $values;
            // array_push($to_encode, $values2);
            // }
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error whire retrieving user information.",
            'query' => $data
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['submitJobRequest'])) {
    $candidateId = $_POST['candidateId'];
    $appliedFor = $_POST['appliedFor'];
    $name = addslashes($_POST['name']);
    $mobile = $_POST['mobile'];
    $email = $_POST['emailId'];

    $data = "INSERT INTO `careers`(`appliedFor`, `candidateId`, `name`, `mobile`, `email`) VALUES ('$appliedFor', NULLIF('$candidateId', ''), '$name', '$mobile', '$email')";
    $query = mysqli_query($databaseConnection, $data);
    if ($query) {
        $rowId = mysqli_insert_id($databaseConnection);

        if ($_FILES['resume']['name'] != "") {
            $filename = $rowId . '-' . $name;
            $extension = pathinfo($_FILES["resume"]["name"], PATHINFO_EXTENSION);
            $basename = $filename . '.' . $extension;
            $file_tmp = $_FILES['resume']['tmp_name'];
            move_uploaded_file($file_tmp, "../pracschool_app/public/careers/" . $basename);

            $updateResumeName = mysqli_query($databaseConnection, "update careers set resumeName='" . $basename . "' where id='" . $rowId . "'");

            $to_encode = array(
                'status' => 1,
                'errorCode' => "information saved",
                'rowId' => $rowId,
                'resume' => $updateResumeName
            );
        } else {
            $to_encode = array(
                'status' => 1,
                'errorCode' => "information saved",
                'rowId' => $rowId
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'errorCode' => "information not saved",
            'query' => $data
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['addOrUpdateMentorObservations'])) {
    /* this method is used for adding and updating mentor observations data for a candidate */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateQuery = mysqli_query($databaseConnection, "select emailId as candidateEmail,firstName as candidateName from users where id = '" . $json['candidateId'] . "';");
        if (mysqli_num_rows($candidateQuery) > 0) {
            $candidateDetails = mysqli_fetch_all($candidateQuery, MYSQLI_ASSOC);
            if ($json['rowId'] === '0') {
                if ($json['nextFollowupDate'] == 'None') {
                    $sql = "INSERT INTO `mentor_observations`( `candidateId`, `contactDate`, `studentIssue`, `adviceBox`,`mentoringStatus`) VALUE('" . $json['candidateId'] . "',CURDATE(), '" . addslashes($json['studentIssue']) . "', '" . addslashes($json['adviceBox']) . "','" . $json['mentoringStatus'] . "');";
                    $updateSql = "UPDATE `professionaldetails` SET `contact_Date`=CURDATE(),`student_issue`='" . addslashes($json['studentIssue']) . "',`advice_Box`='" . addslashes($json['adviceBox']) . "' , `nextMeetingDate` = NULL ,`mentoringStatus`='" . $json['mentoringStatus'] . "' WHERE candidateId = '" . $json['candidateId'] . "' ";
                } else {
                    $sql = "INSERT INTO `mentor_observations`( `candidateId`, `contactDate`, `studentIssue`, `adviceBox`, `nextFollowupDate`,`mentoringStatus`) VALUE('" . $json['candidateId'] . "',CURDATE(), '" . addslashes($json['studentIssue']) . "', '" . addslashes($json['adviceBox']) . "','" . $json['nextFollowupDate'] . "','" . $json['mentoringStatus'] . "');";
                    $updateSql = "UPDATE `professionaldetails` SET `contact_Date`=CURDATE(),`student_issue`='" . addslashes($json['studentIssue']) . "',`advice_Box`='" . addslashes($json['adviceBox']) . "',`nextMeetingDate`='" . $json['nextFollowupDate'] . "',`mentoringStatus` = '" . $json['mentoringStatus'] . "' WHERE candidateId = '" . $json['candidateId'] . "' ";
                }
            } else {
                if ($json['nextFollowupDate'] == 'None') {
                    $sql = "UPDATE `mentor_observations` SET `contactDate`=CURDATE(),`studentIssue`='" . addslashes($json['studentIssue']) . "',`adviceBox`='" . addslashes($json['adviceBox']) . "' , `nextFollowupDate`= NULL,`mentoringStatus` = '" . $json['mentoringStatus'] . "'  WHERE id ='" . $json['rowId'] . "' and candidateId = '" . $json['candidateId'] . "';";
                    $updateSql = "UPDATE `professionaldetails` SET `contact_Date`=CURDATE(),`student_issue`='" . addslashes($json['studentIssue']) . "',`advice_Box`='" . addslashes($json['adviceBox']) . "' ,`nextMeetingDate` = NULL ,`mentoringStatus` ='" . $json['mentoringStatus'] . "' WHERE candidateId = '" . $json['candidateId'] . "' ";
                } else {
                    $sql = "UPDATE `mentor_observations` SET `contactDate`=CURDATE(),`studentIssue`='" . addslashes($json['studentIssue']) . "',`adviceBox`='" . addslashes($json['adviceBox']) . "',`nextFollowupDate`='" . $json['nextFollowupDate'] . "',`mentoringStatus` = '" . $json['mentoringStatus'] . "'  WHERE id ='" . $json['rowId'] . "' and candidateId = '" . $json['candidateId'] . "';";
                    $updateSql = "UPDATE `professionaldetails` SET `contact_Date`=CURDATE(),`student_issue`='" . addslashes($json['studentIssue']) . "',`advice_Box`='" . addslashes($json['adviceBox']) . "',`nextMeetingDate`='" . $json['nextFollowupDate'] . "',`mentoringStatus`='" . $json['mentoringStatus'] . "' WHERE candidateId = '" . $json['candidateId'] . "' ";
                }
            }
            $mentorAdd = mysqli_query($databaseConnection, $sql);
            $mentor_observationUpdated = mysqli_query($databaseConnection, $updateSql);

            if ($mentorAdd && $mentor_observationUpdated) {


                $mentor_Email = mysqli_query($databaseConnection, "select emailId from users where id='" . $json['currentUserId'] . "'");
                if (mysqli_num_rows($mentor_Email) > 0) {
                    $email = mysqli_fetch_assoc($mentor_Email);
                }

                $message = "<p>Dear " . $candidateDetails[0]['candidateName'] . ",</p>
                <p>Greetings from GoPrac.com!!</p> 
                <p>" . $json['mailText'] . " </p>
                
                <p> Thanks & Regards,<br>GoPrac Team (" . $email['emailId'] . "),<br>Bangalore</p>
                ";
                sendEmailToUser($candidateDetails[0]['candidateEmail'], null, 'GoPrac.com: Mentor Observations', $message);
                // $twilio = new Twilio\Rest\Client("AC15e9898ef5c65ff5d29b8d6003952783", "785551c5b70c0e039ec8816b09f4be7d");

                // $message = $twilio->messages
                //                 ->create("whatsapp:+917044762026",
                //                         [
                //                             "from" => "whatsapp:+15705368602",
                //                             "body" => "Hello " .$candidateDetails[0]['candidateName']
                //                         ]
                //                 );


                $to_encode = array(
                    'result' => "Success",
                    'message' => "Mentor Observations Updated.",
                    'status' => 1

                );
            } else {
                $to_encode = array(
                    'result' => "error",
                    'message' => "Error while Updating mentor observation.",
                    'status' => 0,
                    'query' => $sql,
                    'query1' => $updateSql
                );
            }
        } else {
            $to_encode = array(
                'result' => "error",
                'errorCode' => "User Id is incorrect.",
                'status' => -1
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Adding Observation failed.",
            'status' => -1
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['addOrUpdateSalesObservations'])) {
    /* this method is used for adding and updating mentor observations data for a candidate */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $usertype = $json['usertype'];
        $candidateQuery = mysqli_query($databaseConnection, "select emailId as candidateEmail,firstName as candidateName from users where id = '" . $json['candidateId'] . "';");
        if (mysqli_num_rows($candidateQuery) > 0) {
            $candidateDetails = mysqli_fetch_all($candidateQuery, MYSQLI_ASSOC);
            if ($usertype != 'tpmentor') {
                if ($json['rowId'] === '0') {
                    if ($json['nextFollowupDate'] == 'None') {
                        $sql = "INSERT INTO `sales_observations`( `candidateId`, `contactDate`, `leadStatus`, `action`, `approxTime`, `adviceBox`) VALUE('" . $json['candidateId'] . "',CURDATE(), '" . $json['leadStatus'] . "' , '" . addslashes($json['action']) . "','" . $json['approxTime'] . "', '" . addslashes($json['adviceBox']) . "');";
                        $updateSql = "UPDATE `professionaldetails` SET `s_contact_Date`=CURDATE(),`s_student_issue`='" . addslashes($json['action']) . "',`s_emailText`='" . addslashes($json['adviceBox']) . "' , `s_nextcontact_Date` = NULL ,`leadStatus`='" . $json['leadStatus'] . "' WHERE candidateId = '" . $json['candidateId'] . "' ";
                    } else {
                        $sql = "INSERT INTO `sales_observations`( `candidateId`, `contactDate`, `leadStatus` , `action`, `approxTime` , `adviceBox`, `nextFollowupDate`) VALUE('" . $json['candidateId'] . "',CURDATE(), '" . $json['leadStatus'] . "' , '" . addslashes($json['action']) . "', '" . $json['approxTime'] . "' , '" . addslashes($json['adviceBox']) . "','" . $json['nextFollowupDate'] . "');";
                        $updateSql = "UPDATE `professionaldetails` SET `s_contact_Date`=CURDATE(),`s_student_issue`='" . addslashes($json['action']) . "',`s_emailText`='" . addslashes($json['adviceBox']) . "',`s_nextcontact_Date`='" . $json['nextFollowupDate'] . "',`leadStatus` = '" . $json['leadStatus'] . "' WHERE candidateId = '" . $json['candidateId'] . "' ";
                    }
                } else {
                    if ($json['nextFollowupDate'] == 'None') {
                        $sql = "UPDATE `sales_observations` SET `contactDate`=CURDATE(),`action`='" . addslashes($json['action']) . "',`adviceBox`='" . addslashes($json['adviceBox']) . "' , `nextFollowupDate`= NULL,`leadStatus` = '" . $json['leadStatus'] . "', `approxTime` = '" . $json['approxTime'] . "'  WHERE id ='" . $json['rowId'] . "' and candidateId = '" . $json['candidateId'] . "';";
                        $updateSql = "UPDATE `professionaldetails` SET `s_contact_Date`=CURDATE(),`s_student_issue`='" . addslashes($json['action']) . "',`s_emailText`='" . addslashes($json['adviceBox']) . "' ,`s_nextcontact_Date` = NULL ,`leadStatus` ='" . $json['leadStatus'] . "' WHERE candidateId = '" . $json['candidateId'] . "' ";
                    } else {
                        $sql = "UPDATE `sales_observations` SET `contactDate`=CURDATE(),`action`='" . addslashes($json['action']) . "',`adviceBox`='" . addslashes($json['adviceBox']) . "',`nextFollowupDate`='" . $json['nextFollowupDate'] . "',`leadStatus` = '" . $json['leadStatus'] . "', `approxTime` = '" . $json['approxTime'] . "'  WHERE id ='" . $json['rowId'] . "' and candidateId = '" . $json['candidateId'] . "';";
                        $updateSql = "UPDATE `professionaldetails` SET `s_contact_Date`=CURDATE(),`s_student_issue`='" . addslashes($json['action']) . "',`s_emailText`='" . addslashes($json['adviceBox']) . "',`s_nextcontact_Date`='" . $json['nextFollowupDate'] . "',`leadStatus`='" . $json['leadStatus'] . "' WHERE candidateId = '" . $json['candidateId'] . "' ";
                    }
                }
            }
            if ($usertype == 'tpmentor') {
                if ($json['rowId'] === '0') {
                    // $sql = "INSERT INTO `sales_observations`( `candidateId`, `contactDate`, `leadStatus`, `approxTime`, `productproposed`,`mentorid`) VALUE('" . $json['candidateId'] . "',CURDATE(), '" . $json['leadStatus'] . "' ,'" .$json['approxTime']. "','".addslashes($json['productproposed'])."','".$json['mentorid']."');";

                    $sql = "INSERT INTO `sales_observations`( `candidateId`, `contactDate`, `leadStatus`, `approxTime`, `productproposed`,`mentorid`,`followUpDate`,`followUpStatus`) VALUE('" . $json['candidateId'] . "',CURDATE(), '" . $json['leadStatus'] . "' ,'" . $json['approxTime'] . "','" . addslashes($json['productproposed']) . "','" . $json['mentorid'] . "',NULLIF('" . $json['followDate'] . "',''),'" . $json['followUpStatus'] . "');";

                    if ($json['leadStatus'] == 1 || $json['leadStatus'] == 2 || $json['leadStatus'] == 19) {

                        $updateSql = "UPDATE `professionaldetails` SET `s_contact_Date`=CURDATE(),`s_nextcontact_Date` = NULL ,`assignMentorId`= NULL, `mentorAssignDate`= NULL, `leadStatus`='" . $json['leadStatus'] . "' WHERE candidateId = '" . $json['candidateId'] . "' ";

                    } else {

                        $updateSql = "UPDATE `professionaldetails` SET `s_contact_Date`=CURDATE(),`s_nextcontact_Date` = NULL ,`leadStatus`='" . $json['leadStatus'] . "' WHERE candidateId = '" . $json['candidateId'] . "' ";
                    }
                } else {
                    $sql = "UPDATE `sales_observations` SET `contactDate`=CURDATE(), `nextFollowupDate`= NULL,`leadStatus` = '" . $json['leadStatus'] . "', `approxTime` = '" . $json['approxTime'] . "', `productproposed` = '" . addslashes($json['productproposed']) . "' WHERE id ='" . $json['rowId'] . "' and candidateId = '" . $json['candidateId'] . "';";

                    if ($json['leadStatus'] == 1 || $json['leadStatus'] == 2 || $json['leadStatus'] == 19) {

                        $updateSql = "UPDATE `professionaldetails` SET `s_contact_Date`=CURDATE(),`s_nextcontact_Date` = NULL ,`assignMentorId`= NULL, `mentorAssignDate`= NULL, `leadStatus`='" . $json['leadStatus'] . "' WHERE candidateId = '" . $json['candidateId'] . "' ";

                    } else {

                        $updateSql = "UPDATE `professionaldetails` SET `s_contact_Date`=CURDATE(),`s_nextcontact_Date` = NULL ,`leadStatus`='" . $json['leadStatus'] . "' WHERE candidateId = '" . $json['candidateId'] . "' ";
                    }
                }
            }

            $mentorAdd = mysqli_query($databaseConnection, $sql);
            $mentor_observationUpdated = mysqli_query($databaseConnection, $updateSql);

            if ($mentorAdd && $mentor_observationUpdated) {

                $mentor_Email = mysqli_query($databaseConnection, "select emailId from users where id='" . $json['currentUserId'] . "'");
                if (mysqli_num_rows($mentor_Email) > 0) {
                    $email = mysqli_fetch_assoc($mentor_Email);
                }
                if ($usertype != 'tpmentor') {
                    if ($json['adviceBox'] != '') {

                        $message = "<p>Dear " . $candidateDetails[0]['candidateName'] . ",</p>
                <p>Greetings from GoPrac.com!!</p> 
                <p>" . $json['mailText'] . " </p>
                <p> Thanks & Regards,<br>GoPrac Team (" . $email['emailId'] . "),<br>Bangalore</p>
                ";
                        sendEmailToUser($candidateDetails[0]['candidateEmail'], null, 'GoPrac.com: Mentor Observations', $message);
                        /* un comment this one later  */
                    }
                }

                // $twilio = new Twilio\Rest\Client("AC15e9898ef5c65ff5d29b8d6003952783", "785551c5b70c0e039ec8816b09f4be7d");

                // $message = $twilio->messages
                //                 ->create("whatsapp:+917044762026",
                //                         [
                //                             "from" => "whatsapp:+15705368602",
                //                             "body" => "Hello " .$candidateDetails[0]['candidateName']
                //                         ]
                //                 );


                $to_encode = array(
                    'result' => "Success",
                    'message' => "Mentor Observations Updated.",
                    'status' => 1

                );
            } else {
                $to_encode = array(
                    'result' => "error",
                    'message' => "Error while Updating mentor observation.",
                    'status' => 0,
                    'query' => $sql,
                    'query1' => $updateSql
                );
            }
        } else {
            $to_encode = array(
                'result' => "error",
                'errorCode' => "User Id is incorrect.",
                'status' => -1
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Adding Observation failed.",
            'status' => -1
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getTotalMentorMettingOnDate'])) {
    /* this method is used for getting total scheduled meeting on selected date by mentor  */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $query = "Select count(candidateId) as TotalMettings from professionaldetails where nextMeetingDate = '" . $json['nextFollowupDate'] . "' and assignMentorId = '" . $json['candidateId'] . "';";
        $queryResult = mysqli_query($databaseConnection, $query);
        if (mysqli_num_rows($queryResult) > 0) {
            $row = mysqli_fetch_all($queryResult, MYSQLI_ASSOC);
            $to_encode = array(
                'result' => "success",
                'status' => 1,
                'data' => $row,
                'count' => $row[0]['TotalMettings'],
                'query' => $query
            );
        } else {
            $to_encode = array(
                'result' => "success",
                'message' => "Total Meeting Scheduled: 0",
                'status' => 0,
                'query' => $quey
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Error while getting meetings",
            'status' => -1
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getMentorshipData'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['candidateId'];
        $values = array();
        $data1 = "select * from favourite_subject where isActiveForMentorship='Y' order by id=29, favourite_subject";
        $query1 = mysqli_query($databaseConnection, $data1);
        $values['favourite_subject'] = mysqli_fetch_all($query1, MYSQLI_ASSOC);

        $data2 = "select * from aspiration_company order by id=40,name";
        $query2 = mysqli_query($databaseConnection, $data2);
        $values['aspiration_company'] = mysqli_fetch_all($query2, MYSQLI_ASSOC);

        $data3 = "select * from favourite_domain  order by id=39,name";
        $query3 = mysqli_query($databaseConnection, $data3);
        $values['favourite_domain'] = mysqli_fetch_all($query3, MYSQLI_ASSOC);

        $data4 = "select * from fav_prog_skill order by id=9,fav_prog_skill";
        $query4 = mysqli_query($databaseConnection, $data4);
        $values['fav_prog_skill'] = mysqli_fetch_all($query4, MYSQLI_ASSOC);

        $data5 = "select * from language";
        $query5 = mysqli_query($databaseConnection, $data5);
        $values['languages'] = mysqli_fetch_all($query5, MYSQLI_ASSOC);
        $data6 = "select * from favourite_subject where streamId=1";
        $query6 = mysqli_query($databaseConnection, $data6);
        $values['computerScience'] = mysqli_fetch_all($query6, MYSQLI_ASSOC);

        $data7 = "select * from favourite_subject where streamId=21";
        $query7 = mysqli_query($databaseConnection, $data7);
        $values['coding'] = mysqli_fetch_all($query7, MYSQLI_ASSOC);

        $data8 = "select * from favourite_subject where streamId=18";
        $query8 = mysqli_query($databaseConnection, $data8);
        $values['circuitBranch'] = mysqli_fetch_all($query8, MYSQLI_ASSOC);

        $data9 = "select * from favourite_subject where streamId=4";
        $query9 = mysqli_query($databaseConnection, $data9);
        $values['mechanical'] = mysqli_fetch_all($query9, MYSQLI_ASSOC);

        $data10 = "select * from favourite_subject where streamId=5";
        $query10 = mysqli_query($databaseConnection, $data10);
        $values['civil'] = mysqli_fetch_all($query10, MYSQLI_ASSOC);

        $data11 = "select * from favourite_subject where streamId=19";
        $query11 = mysqli_query($databaseConnection, $data11);
        $values['businessAdministration'] = mysqli_fetch_all($query11, MYSQLI_ASSOC);

        $data12 = "select * from qualification order by id";
        $query12 = mysqli_query($databaseConnection, $data12);
        $values['qualification'] = mysqli_fetch_all($query12, MYSQLI_ASSOC);

        $data13 = "select * from colleges order by id";
        $query13 = mysqli_query($databaseConnection, $data13);
        $values['colleges'] = mysqli_fetch_all($query13, MYSQLI_ASSOC);

        $data14 = "select name from panel order by name";
        $query14 = mysqli_query($databaseConnection, $data14);
        $values['referrerName'] = mysqli_fetch_all($query14, MYSQLI_ASSOC);

        $data15 = "SELECT s.id,s.stream FROM stream s INNER JOIN favourite_subject fs ON s.id = fs.streamId WHERE s.id NOT IN (21,57,58) GROUP BY s.id;";
        $query15 = mysqli_query($databaseConnection, $data15);
        $values['streamList'] = mysqli_fetch_all($query15, MYSQLI_ASSOC);

        $data16 = "SELECT s.id as streamId,s.stream as streamName,fs.id as subjectId,fs.favourite_subject as subjectName FROM stream s INNER JOIN favourite_subject fs ON s.id = fs.streamId WHERE s.id NOT IN (21,57,58) ORDER BY s.stream,fs.favourite_subject ASC;";
        $query16 = mysqli_query($databaseConnection, $data16);
        $values['streamSubjectList'] = mysqli_fetch_all($query16, MYSQLI_ASSOC);

        $data17 = "select * from favourite_subject where streamId=57";
        $query17 = mysqli_query($databaseConnection, $data17);
        $values['cloudSub'] = mysqli_fetch_all($query17, MYSQLI_ASSOC);

        $data18 = "select * from favourite_subject where streamId=58";
        $query18 = mysqli_query($databaseConnection, $data18);
        $values['dataAnalyst'] = mysqli_fetch_all($query18, MYSQLI_ASSOC);

        $data19 = "select * from areasofinterest order by id asc";
        $query19 = mysqli_query($databaseConnection, $data19);
        $values['areasofinterest'] = mysqli_fetch_all($query19, MYSQLI_ASSOC);


        $productQ = "Select id as pro_id,name as p_name, description, eligibility from product";
        $proResult = mysqli_query($databaseConnection, $productQ);
        $values['product'] = mysqli_fetch_all($proResult, MYSQLI_ASSOC);
        $data = "select p.*, u.firstName as candidateName, u.panelId, u.usertype, s.stream, c.collegeName from professionaldetails p inner join users u on p.candidateId = u.id left outer join stream s on p.specialization = s.id left outer join colleges c on p.college = c.id where p.candidateId='" . $candidateId . "'";
        $query = mysqli_query($databaseConnection, $data);
        if (mysqli_num_rows($query) >= 1) {
            $values['mentorshipData'] = mysqli_fetch_array($query, MYSQLI_ASSOC);
            if ($values['mentorshipData']['usertype'] == 'expert') {
                $expertQuery = "Select p.*,pt.isExpertConfirmLater,pt.isExpertAssessmentApproved,pt.isExpertVideoApproved,pt.isExpertPeerApproved from panel p inner join panels_transection pt on pt.panelId = p.id where p.id='" . $values['mentorshipData']['panelId'] . "'";
                $expertResult = mysqli_query($databaseConnection, $expertQuery);
                $values['expertData'] = mysqli_fetch_array($expertResult, MYSQLI_ASSOC);
                //$values['expertData']['picture'] = 'panel_'.$values['expertData']['id'].'.png';  
            }
            $to_encode = $values;
        } else {
            $values['mentorshipData'] = null;
            $to_encode = $values;
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error whire retrieving user information."
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getMentorshipPlan'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['candidateId'];
        $values = array();
        $subSeqResult = array();
        $favSubResult = array();
        $preReqResult = array();
        $aspComResult = array();
        $favDomResult = array();
        $mentorshipOtherSubject = array();
        $mentorshipCompulsorySubject = array();
        $conceptInterviews = array();
        $conceptsInterviews = array();
        $conceptsInterview = array();
        $sessionCalendarResult = array();
        $index = 1;
        $date = date('Y-m-d');
        $value = array();
        $filterQuery = '';
        $tpmentorfilterquery = '';

        if ($json['userType'] == 'tpmentor') {
            $tpmentorfilterquery .= " AND so.mentorid IN (" . $json['userId'] . ")";
        }

        if ($json['userType'] == 'corporate') {
            $filterQuery .= " AND fr.review_status IN (2) AND i.companyId NOT IN (SELECT company_id FROM preInterview WHERE userId NOT IN (" . $json['userId'] . ")) ";
        } else {
            $filterQuery .= " AND fr.review_status IN (2,1,0,-3,-4,-2) ";
        }


        $data = "select p.*, u.firstName as candidateName,u.panelId,u.id as candidateId,u.usertype,u.emailId,u.mobileNumber,u.createdOn, s.stream,c.collegeName from professionaldetails p inner join users u on p.candidateId =  u.id  left outer join stream s on p.specialization = s.id left outer join colleges c on p.college = c.id where p.candidateId='" . $candidateId . "' limit 1";
        $query = mysqli_query($databaseConnection, $data);
        if (mysqli_num_rows($query) >= 1) {
            $values['mentorshipData'] = mysqli_fetch_array($query, MYSQLI_ASSOC);

            $userSubscription = getSubsciptionDetails($databaseConnection, $values['mentorshipData']['candidateId']);

            $values['mentorshipData']['s_end'] = $userSubscription['subscriptionEndTime'];
            $values['mentorshipData']['amount'] = $userSubscription['amount'];
            $values['mentorshipData']['endDate'] = $userSubscription['endDate'];
            $values['mentorshipData']['freeTrialAllowed'] = $userSubscription['freeTrialAllowed'];
            $productQuery = mysqli_query($databaseConnection, "SELECT p.id as pr_id, p.name,p.productUrl from product p order by p.id");
            $values['productList'] = mysqli_fetch_all($productQuery, MYSQLI_ASSOC);
            $freeProductQuery = mysqli_query($databaseConnection, "SELECT p.id as pr_id, p.name,p.productUrl from product p inner join interview i on i.productId = p.id where i.categoryType=8 group by p.id order by p.id ");
            $values['freeProductList'] = mysqli_fetch_all($freeProductQuery, MYSQLI_ASSOC);
            $values['productList'][0]['productAllowed'] = $userSubscription['mockInterviewAllowed'];
            $values['productList'][1]['productAllowed'] = $userSubscription['communicationInterviewAllowed'];
            $values['productList'][2]['productAllowed'] = $userSubscription['behaviouralInterviewAllowed'];
            $values['productList'][3]['productAllowed'] = $userSubscription['problemsolvingInterviewAllowed'];
            $values['productList'][4]['productAllowed'] = $userSubscription['codingInterviewAllowed'];
            $values['productList'][5]['productAllowed'] = 0;

            $stats = mysqli_query($databaseConnection, "SELECT sum(temp.totalAns) as totalAns, sum(temp.totalQues) as totalQues,SEC_TO_TIME(sum(TIME_TO_SEC(temp.duration))) as duration  from (SELECT  count(m.questionId) as totalAns,(select count(iqt.questionId) from interview_questions_transection iqt inner join questions qs on qs.id = iqt.questionId  where iqt.interviewId  = m.interviewId and qs.deleted_at is null and iqt.deleted_at is null)-1 as totalQues,SEC_TO_TIME(SUM(TIME_TO_SEC(m.totalTime)) + SUM(TIME_TO_SEC(vwd.prwatchDuration)) + SUM(TIME_TO_SEC(vwd.psWatchDuration)) + SUM(TIME_TO_SEC(vwd.gvWatchDuration))) as duration  FROM mergedVideos m inner join video_watched_details vwd on vwd.mergeId = m.mergeId WHERE m.candidateId='" . $candidateId . "'  group by m.interviewSessionId ) as temp;");
            $values['statsList'] = mysqli_fetch_all($stats, MYSQLI_ASSOC);

            $durationOfPracticeProductQry = mysqli_query($databaseConnection, "SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(m.totalTime)) + SUM(TIME_TO_SEC(vwd.prwatchDuration)) + SUM(TIME_TO_SEC(vwd.psWatchDuration)) + SUM(TIME_TO_SEC(vwd.gvWatchDuration))) as productDuration,i.productId FROM `mergedVideos` m inner join video_watched_details vwd on vwd.mergeId = m.mergeId inner join interview i on i.id = m.interviewId WHERE m.candidateId = '" . $values['mentorshipData']['candidateId'] . "' group by i.productId order by i.productId ;");
            $values['productWiseDuration'] = mysqli_fetch_all($durationOfPracticeProductQry, MYSQLI_ASSOC);

            $qq1 = "select    case  when isc.candidateStatus is null and (fr.id is not null and (fr.review_status=2)) then 'Assessment Completed'
  when ( (fr.id is not null and cit.completion_status is not null and fr.review_status in (0,1)) or    (fr.id is not null and cit.completion_status is not null and fr.review_status=-2) ) then 'Assessment Awaited' 
  when isc.candidateStatus is null and  ((fr.id is not null and (fr.review_status=-4 and fr.reasonOfRejection='duplicateAttempt')) or  (fr.id is not null and (fr.review_status=-4 and fr.reasonOfRejection='limitedFreeAssessment')) or   (fr.id is not null and (fr.review_status=-4 and fr.reasonOfRejection='unauthorizedUser')) or (fr.id is not null and (fr.review_status=-4 and fr.reasonOfRejection='incompleteInterview')) or (fr.id is not null and (fr.review_status=-4 and fr.reasonOfRejection='technicalIssue'))  or  (fr.id is not null and (fr.review_status=-4 and fr.reasonOfRejection not in ('technicalIssue','incompleteInterview')))  )  then 'Assessment Rejected'
   when isc.candidateStatus is null and ((fr.id is null and isc.scheduleTime<now())) then 'Missed Schedule'  
   when isc.candidateStatus is null and (fr.id is null and (DATEDIFF(isc.scheduleTime,now()))=0) then 'Scheduled Today' 
   when isc.candidateStatus is null and  (fr.id is null and isc.firstScheduleDate is null and (DATEDIFF(isc.scheduleTime,now()))>=1)  then 'Future Scheduled' 
   when isc.candidateStatus is null and   (fr.id is null and (isc.scheduleTime!=isc.firstScheduleDate) and (DATEDIFF(isc.scheduleTime,now()))>=1) then 'Re-Scheduled' 
  when isc.candidateStatus is null and isc.scheduleTime is null then 'Applied' 
  when (fr.id is null and fr.review_status is null) then 'Not Attempted' else 
  isc.candidateStatus end as newcandidStatus ,
       cm.connecttomentorname,cm.timetocontact,i.name,m.interviewId as interviewId,fs.favourite_subject as subject, p.id as i_pid,fr.review_status, fr.suggestion,count(m.questionId) as QA , CASE WHEN i.categoryType = 9 THEN  (SELECT COUNT( CASE WHEN iqt.attemptStatus is not NULL THEN iqt.questionId ELSE NULL END) FROM interview_questions_transection iqt inner join questions qs on qs.id = iqt.questionId WHERE iqt.interviewId=m.interviewId and qs.deleted_at is null and iqt.deleted_at is null ) ELSE (select count(iqt.questionId) from interview_questions_transection iqt inner join questions qs on qs.id = iqt.questionId  where iqt.interviewId  = m.interviewId and qs.deleted_at is null and iqt.deleted_at is null) -1 END  as QT,CASE WHEN i.categoryType = 9 THEN (SELECT CASE WHEN cit.completion_status is not NULL THEN cit.completion_status ELSE 'Incomplete' END from candidate_interview_transection cit where cit.interviewId = m.interviewId) END AS completion_status, CASE WHEN fr.review_status='-4' THEN (CASE WHEN fr.reasonOfRejection is null THEN 'Other Reason' WHEN fr.reasonOfRejection='selfRejected'  THEN 'Self Rejected' WHEN fr.reasonOfRejection = 'outOfProductScope' THEN 'Out of Product Scope' WHEN fr.reasonOfRejection = 'yourPracticeDurationIsDue' THEN 'Your Practice Duration is Due' WHEN fr.reasonOfRejection = 'audioIssue' THEN 'Audio Issue' WHEN fr.reasonOfRejection = 'assessmentOnHold' THEN 'Assessment on Hold' WHEN fr.reasonOfRejection = 'PracticeInterview' THEN 'Practice Interview'  WHEN fr.reasonOfRejection ='fixedNoOfAssessment' THEN 'Completed the Max no of Assessments'  WHEN fr.reasonOfRejection ='limitedFreeAssessment' THEN 'Limited FREE Assessment'   WHEN fr.reasonOfRejection = 'incompleteInterview' THEN 'Incomplete Interview' WHEN fr.reasonOfRejection = 'noAnswerProvided' THEN 'No Answer Provided' WHEN fr.reasonOfRejection = 'Testing' THEN 'Testing' WHEN fr.reasonOfRejection = 'nonSeriousInterview' THEN 'Non Serious Interview' WHEN fr.reasonOfRejection = 'videoIssue' THEN 'Video Issue' WHEN fr.reasonOfRejection = 'unauthorizedUser' THEN 'Unauthorized User' WHEN fr.reasonOfRejection = 'duplicateAttempt' THEN 'Duplicate Attempt' ELSE fr.reasonOfRejection END) ELSE 'Not Rejected' END AS reasonOfRejection, m.candidateId, m.interviewSessionId,CONCAT('/review?i=', m.interviewId, '&c=', m.candidateId, '&s=', m.interviewSessionId) as url, CASE WHEN ((count(m.questionId)/(CASE WHEN i.categoryType = 9 THEN  (SELECT COUNT( CASE WHEN iqt.attemptStatus is not NULL THEN iqt.questionId ELSE NULL END) FROM interview_questions_transection iqt inner join questions qs on qs.id = iqt.questionId WHERE iqt.interviewId=m.interviewId and qs.deleted_at is null and iqt.deleted_at is null ) ELSE (select count(iqt.questionId) from interview_questions_transection iqt inner join questions qs on qs.id = iqt.questionId  where iqt.interviewId  = m.interviewId and qs.deleted_at is null and iqt.deleted_at is null) -1 END ))*100)<75 then 'Y' ELSE 'N' END as isRetakeRequired from mergedVideos m inner join interview i on m.interviewId =i.id inner join product p on i.productId = p.id  inner join feedback_request fr on fr.candidateId = m.candidateId and fr.interviewSessionId = m.interviewSessionId inner join favourite_subject fs on i.subject_id = fs.id left outer join connect_mentor cm on cm.interviewId=i.id join interviewSchedule isc on isc.candidate_id=m.candidateId    left join candidate_interview_transection cit on cit.interviewId=m.interviewId  where m.candidateId='" . $candidateId . "'  and m.interviewSessionId is not null   " . $filterQuery . " group by m.interviewSessionId order by  m.interviewSessionId desc";
            //   echo $qq1;
            $AttendedinterviewList = mysqli_query($databaseConnection, $qq1);


            while ($row = mysqli_fetch_assoc($AttendedinterviewList)) {
                if ($row['review_status'] == 2) {
                    $overallRatingQuery = mysqli_query($databaseConnection, "SELECT AVG(`overallRating`) AS score FROM `expert_review` WHERE `feedback_request_id` = (SELECT id FROM `feedback_request` WHERE `interviewSessionId` LIKE '" . $row['interviewSessionId'] . "')");
                    $overallRatingResult = mysqli_fetch_assoc($overallRatingQuery);
                    $row['overallRating'] = $overallRatingResult['score'];
                    $row['score'] = $overallRatingResult['score'];
                    $row['totalscore'] = 10;
                    if ($row['score'] == 0) {
                        $row['perScore'] = 0;
                    } else {
                        $row['perScore'] = round(($row['score'] * 10) / $row['totalscore'], 1);
                    }
                }
                array_push($value, $row);
            }
            $values['AttendedinterviewList'] = $value;

            /* this is added for count unique interview in each product taken by candidate 30-sep-2021*/

            $uniqueProductCount = mysqli_query($databaseConnection, "select count(distinct i.id) as productProgress,p.totalInterviewAllowed, p.id as productId from mergedVideos m inner join interview i on m.interviewId =i.id inner join product p on i.productId = p.id inner join feedback_request fr on fr.candidateId = m.candidateId and fr.interviewSessionId = m.interviewSessionId inner join favourite_subject fs on i.subject_id = fs.id where m.candidateId='" . $candidateId . "' and m.interviewSessionId is not null " . $filterQuery . "  group by i.productId order by i.productId");
            if (mysqli_num_rows($uniqueProductCount) > 0) {
                $uniqueProductCountResult = mysqli_fetch_all($uniqueProductCount, MYSQLI_ASSOC);
            } else {
                $uniqueProductCountResult = [];
            }
            $values['uniqueProductCountResult'] = $uniqueProductCountResult;

            $progSkillQuery = mysqli_query($databaseConnection, "SELECT pd.fav_programming_skill, group_concat(fps.fav_prog_skill SEPARATOR ', ') AS fav_programming_skill_name FROM professionaldetails pd, fav_prog_skill fps WHERE FIND_IN_SET(fps.id, pd.fav_programming_skill) and candidateId = '" . $values['mentorshipData']['candidateId'] . "'");

            $progSkillResult = mysqli_fetch_array($progSkillQuery, MYSQLI_ASSOC);
            $values['mentorshipData']['fav_programming_skill_name'] = $progSkillResult['fav_programming_skill_name'];
            if (strpos($values['mentorshipData']['fav_programming_skill_name'], "Others") !== false) {
                $values['mentorshipData']['fav_programming_skill_name'] = str_replace("Others", $values['mentorshipData']['other_prog_skills'], $values['mentorshipData']['fav_programming_skill_name']);
            }

            $favSubjectsQuery = mysqli_query($databaseConnection, "SELECT pd.fav_subjects, group_concat(fs.favourite_subject SEPARATOR ', ') AS fav_subjects_name FROM professionaldetails pd, favourite_subject fs WHERE FIND_IN_SET(fs.id, pd.fav_subjects) and candidateId = '" . $values['mentorshipData']['candidateId'] . "'");
            $favSubjectsResult = mysqli_fetch_array($favSubjectsQuery, MYSQLI_ASSOC);


            $values['mentorshipData']['fav_subjects_name'] = $favSubjectsResult['fav_subjects_name'];
            if (strpos($values['mentorshipData']['fav_subjects_name'], "Others") !== false) {
                $values['mentorshipData']['fav_subjects_name'] = str_replace("Others", $values['mentorshipData']['other_subjects'], $values['mentorshipData']['fav_subjects_name']);
            }

            $aspCompaniesQuery = mysqli_query($databaseConnection, "SELECT pd.asp_companies, group_concat(ac.name SEPARATOR ', ') AS asp_companies_name FROM professionaldetails pd, aspiration_company ac WHERE FIND_IN_SET(ac.id, pd.asp_companies) and candidateId = '" . $values['mentorshipData']['candidateId'] . "'");
            $aspCompaniesResult = mysqli_fetch_array($aspCompaniesQuery, MYSQLI_ASSOC);
            $values['mentorshipData']['asp_companies_name'] = $aspCompaniesResult['asp_companies_name'];
            if (strpos($values['mentorshipData']['asp_companies_name'], "Others") !== false) {
                $values['mentorshipData']['asp_companies_name'] = str_replace("Others", $values['mentorshipData']['other_companies'], $values['mentorshipData']['asp_companies_name']);
            }

            $aspCompaniesQuery1 = mysqli_query($databaseConnection, "SELECT pd.preferredWorkLocation, group_concat(lc.cityName SEPARATOR ', ') AS asp_companies_name1 FROM professionaldetails pd, locations lc WHERE FIND_IN_SET(lc.id, pd.preferredWorkLocation) and candidateId = '" . $values['mentorshipData']['candidateId'] . "'");

            $aspCompaniesResult1 = mysqli_fetch_array($aspCompaniesQuery1, MYSQLI_ASSOC);
            $values['mentorshipData']['asp_companies_name1'] = $aspCompaniesResult1['asp_companies_name1'];
            if (strpos($values['mentorshipData']['asp_companies_name1'], "Others") !== false) {
                $values['mentorshipData']['asp_companies_name1'] = str_replace("Others", $values['mentorshipData']['other_companies'], $values['mentorshipData']['asp_companies_name1']);
            }

            //converting to current location value
            $aspCompaniesQuery2 = mysqli_query($databaseConnection, "SELECT pd.currentLocation, group_concat(lc.cityName SEPARATOR ', ') AS asp_companies_name2 FROM professionaldetails pd, locations lc WHERE FIND_IN_SET(lc.id, pd.currentLocation) and candidateId = '" . $values['mentorshipData']['candidateId'] . "'");

            $aspCompaniesResult2 = mysqli_fetch_array($aspCompaniesQuery2, MYSQLI_ASSOC);
            $values['mentorshipData']['asp_companies_name2'] = $aspCompaniesResult2['asp_companies_name2'];
            if (strpos($values['mentorshipData']['asp_companies_name2'], "Others") !== false) {
                $values['mentorshipData']['asp_companies_name2'] = str_replace("Others", $values['mentorshipData']['other_companies'], $values['mentorshipData']['asp_companies_name2']);
            }

            $languagesQuery = mysqli_query($databaseConnection, "SELECT pd.languages, group_concat(l.name SEPARATOR ', ') AS languages_name FROM professionaldetails pd, language l WHERE FIND_IN_SET(l.id, pd.languages) and candidateId = '" . $values['mentorshipData']['candidateId'] . "'");
            $languagesResult = mysqli_fetch_array($languagesQuery, MYSQLI_ASSOC);
            $values['mentorshipData']['languages_name'] = $languagesResult['languages_name'];

            $mentorCallQuery = mysqli_query($databaseConnection, "SELECT mcp.*, p.name as mentorName FROM mentor_call_planning mcp inner join panel p on p.id = mcp.mentorId WHERE mcp.candidateId = '" . $values['mentorshipData']['candidateId'] . "'");
            $mentorCallResult = mysqli_fetch_all($mentorCallQuery, MYSQLI_ASSOC);
            $values['mentorshipData']['mentorCallPlanning'] = $mentorCallResult;

            $mentoringHistoryQuery = mysqli_query($databaseConnection, "SELECT * FROM mentor_history WHERE candidateId = '" . $values['mentorshipData']['candidateId'] . "'");
            $mentoringHistoryResult = mysqli_fetch_all($mentoringHistoryQuery, MYSQLI_ASSOC);
            $values['mentorshipData']['mentoringHistory'] = $mentoringHistoryResult;

            $sessionCalendarQuery = mysqli_query($databaseConnection, "SELECT sc.*, fs.favourite_subject as subjectName, i.name as interviewName FROM session_calendar sc inner join favourite_subject fs on fs.id = sc.subjectId inner join interview i on i.id = sc.interviewId WHERE candidateId = '" . $values['mentorshipData']['candidateId'] . "'");
            //$sessionCalendarResult = mysqli_fetch_all($sessionCalendarQuery, MYSQLI_ASSOC);
            if (mysqli_num_rows($sessionCalendarQuery) > 0) {
                while ($sessionResult = mysqli_fetch_array($sessionCalendarQuery, MYSQLI_ASSOC)) {
                    $interviewTaken = "SELECT CASE WHEN fbr.review_status is NULL THEN 'Request Feedback' WHEN fbr.review_status = 2 THEN 'Feedback Completed' WHEN fbr.review_status = 1 THEN 'Feedback in-progess' WHEN fbr.review_status = 0 THEN 'Feedback is Open' WHEN fbr.review_status = -2 THEN 'Video Verification' WHEN fbr.review_status = -3 THEN 'Feedback Verification' WHEN fbr.review_status = -4 THEN 'Feedback Rejected' END as feedbackStatus, max(m.interviewSessionId) as interviewsTakenDate from mergedVideos m left outer join feedback_request fbr on fbr.interviewSessionId = m.interviewSessionId WHERE m.candidateId='" . $sessionResult['candidateId'] . "' AND m.interviewId = '" . $sessionResult['interviewId'] . "';";
                    $interviewTakenQuery = mysqli_query($databaseConnection, $interviewTaken);
                    if (mysqli_num_rows($interviewTakenQuery) > 0) {
                        $interviewTakenResult = mysqli_fetch_array($interviewTakenQuery, MYSQLI_ASSOC);
                        $sessionResult['interviewsTakenDate'] = $interviewTakenResult['interviewsTakenDate'];
                        $sessionResult['feedbackStatus'] = $interviewTakenResult['feedbackStatus'];
                    } else {
                        $sessionResult['interviewsTakenDate'] = null;
                        $sessionResult['feedbackStatus'] = null;
                    }
                    array_push($sessionCalendarResult, $sessionResult);
                }
            }
            $values['mentorshipData']['sessionCalendar'] = $sessionCalendarResult;

            $mentoringActionableAdviceQuery = mysqli_query($databaseConnection, "SELECT maa.*, fs.favourite_subject as subjectName, group_concat(i.name SEPARATOR ', ') as interviewName FROM interview i, mentoring_actionable_advice maa inner join favourite_subject fs on fs.id = maa.subjectId WHERE FIND_IN_SET(i.id, maa.interviewId) and candidateId = '" . $values['mentorshipData']['candidateId'] . "' group by maa.id");
            $mentoringActionableAdviceResult = mysqli_fetch_all($mentoringActionableAdviceQuery, MYSQLI_ASSOC);
            $values['mentorshipData']['mentoringActionableAdvice'] = $mentoringActionableAdviceResult;
            /* this is used for mentor observations */
            $mentor_observationQuery = mysqli_query($databaseConnection, "Select * from mentor_observations where candidateId='" . $candidateId . "'  order by contactDate;");
            $values['mentorObservation'] = mysqli_fetch_all($mentor_observationQuery, MYSQLI_ASSOC);

            $sales_observationQuery = mysqli_query($databaseConnection, "Select so.id, so.candidateId, so.contactDate,  (Select statusValue from salesLeadActionStatus where id = so.leadStatus) as leadStatus,so.leadStatus as leadStatusId,(Select statusValue from salesLeadActionStatus where id = so.action) as action,so.action as actionId, so.approxTime, so.adviceBox, so.nextFollowupDate,so.productproposed,pd.connecttomentorname,pd.timetocontact from sales_observations so inner join professionaldetails pd on pd.candidateId=so.candidateId where so.candidateId='" . $candidateId . "'" . $tpmentorfilterquery . " order by so.contactDate;");
            $values['salesObservation'] = mysqli_fetch_all($sales_observationQuery, MYSQLI_ASSOC);

            $connecttomentordetails = mysqli_query($databaseConnection, "Select pd.connecttomentorname,pd.timetocontact from professionaldetails pd where pd.candidateId='" . $candidateId . "';");
            $values['Connectomentee_info'] = mysqli_fetch_all($connecttomentordetails, MYSQLI_ASSOC);

            if ($json['userType'] == 'tpmentor') {
                $leadQuery = mysqli_query($databaseConnection, "Select id,statusValue as `value` from salesLeadActionStatus where id in(1,2,3,4,6,19,20)");
                $values['leadFilter'] = mysqli_fetch_all($leadQuery, MYSQLI_ASSOC);
            }
            if ($json['userType'] != 'tpmentor') {
                $leadQuery = mysqli_query($databaseConnection, "Select id,statusValue as `value` from salesLeadActionStatus where usedFor = 'L'");
                $values['leadFilter'] = mysqli_fetch_all($leadQuery, MYSQLI_ASSOC);
            }
            $connecttomentorQuery = mysqli_query($databaseConnection, "Select id,AreaOfInterest from areasofinterest order by id ASC");
            $values['connecttomentorFilter'] = mysqli_fetch_all($connecttomentorQuery, MYSQLI_ASSOC);
            $actionQuery = mysqli_query($databaseConnection, "Select id,statusValue as `value` from salesLeadActionStatus where usedFor = 'A'");
            $values['actionFilter'] = mysqli_fetch_all($actionQuery, MYSQLI_ASSOC);
            $isSalesPaid = mysqli_query($databaseConnection, "SELECT CASE WHEN COUNT(CASE WHEN slas.statusValue = 'paid' THEN pd.id ELSE NULL END) > 0 THEN 'Y' ELSE 'N' END as isPaid FROM `professionaldetails` pd INNER JOIN salesLeadActionStatus slas ON slas.id = pd.leadStatus WHERE pd.candidateId = " . $candidateId . "");
            $values['isPaid'] = mysqli_fetch_all($isSalesPaid, MYSQLI_ASSOC)[0]['isPaid'];

            $to_encode = $values;
            //$diff =  (strtotime($values['mentorshipData']['endDate'])-strtotime($date))/86400;
            //$values['mentorshipData']['s_end']= $diff;
            //round(sum(SUBSTRING_INDEX(i.duration,'-',-1))) as durationOfPractice

            // if ($values['mentorshipData']['specialization'] != '' && $values['mentorshipData']['fav_domain'] != '') {
            // 	$favDomQuery = mysqli_query($databaseConnection, "select m.name as menuName, ds.subject_id, fs.favourite_subject, ds.isGoodToHave from domain_subject ds inner join favourite_subject fs on fs.id = ds.subject_id left outer join menu_subject_transection mst on mst.subject_id = fs.id left outer join menu m on m.id = mst.menu_id where ds.domain_id in (".$values['mentorshipData']['fav_domain'].") and ds.stream_id = '".$values['mentorshipData']['specialization']."';");

            /*while ($row = mysqli_fetch_array($favDomQuery, MYSQLI_ASSOC)) {
                    $row['id'] = $index;
                    $index++;
                    $conceptQuery = mysqli_query($databaseConnection, "select id, name from concepts where subject_id = '".$row['subject_id']."' order by name");
                    $row['concepts'] = '';
                    $row['totalConcepts'] = 0;

                    if (mysqli_num_rows($conceptQuery) >= 1) {
                        $row['totalConcepts'] = mysqli_num_rows($conceptQuery);
                        while ($conceptInt = mysqli_fetch_array($conceptQuery, MYSQLI_ASSOC)) {
                            $subjectQuery = mysqli_query($databaseConnection, "select id, name from interview where concept_id = '".$conceptInt['id']."' and isActive = 'Y' and deleted_at is null order by name");
                            $conceptInt['interviews'] = '';
                            $conceptInt['totalInterviews'] = 0;
                            if (mysqli_num_rows($subjectQuery) >= 1) {
                                $conceptInt['totalInterviews'] = mysqli_num_rows($subjectQuery);
                                $conceptInt['interviews'] = mysqli_fetch_all($subjectQuery, MYSQLI_ASSOC);
                            }
                            array_push($conceptInterviews, $conceptInt);
                            unset($conceptInt);
                            $conceptInt = array();
                        }
                        $row['concepts'] = $conceptInterviews;
                        unset($conceptInterviews);
                        $conceptInterviews = array();
                    }

                    $removedSubjectQuery = mysqli_query($databaseConnection, "Select if(FIND_IN_SET('".$row['subject_id']."', '".$values['mentorshipData']['removeSubjects']."'), 'Y', 'N') as isRemovedSubject");
                    $removedSubjectResult = mysqli_fetch_array($removedSubjectQuery, MYSQLI_ASSOC);
                    $row['isRemovedSubject'] = $removedSubjectResult['isRemovedSubject'];
                    array_push($subSeqResult, $row);
                }
                $values['subjectSequence'] = $subSeqResult;
            }*/

            /*$mentorshipOtherQuery = mysqli_query($databaseConnection, "select m.name as menuName, fs.id as subject_id, fs.favourite_subject from favourite_subject fs left outer join menu_subject_transection mst on mst.subject_id = fs.id left outer join menu m on m.id = mst.menu_id where fs.id in (30, 21, 56) order by favourite_subject");
            while ($rows = mysqli_fetch_array($mentorshipOtherQuery, MYSQLI_ASSOC)) {
                $conceptsQuery = mysqli_query($databaseConnection, "select id, name from concepts where subject_id = '".$rows['subject_id']."' order by name");
                $rows['concepts'] = '';
                $rows['totalConcepts'] = 0;
                if (mysqli_num_rows($conceptsQuery) >= 1) {
                    $rows['totalConcepts'] = mysqli_num_rows($conceptsQuery);
                    while ($conceptsInt = mysqli_fetch_array($conceptsQuery, MYSQLI_ASSOC)) {
                        $subjectsQuery = mysqli_query($databaseConnection, "select id, name from interview where concept_id = '".$conceptsInt['id']."' and isActive = 'Y' and deleted_at is null order by name");
                        $conceptsInt['interviews'] = '';
                        $conceptsInt['totalInterviews'] = 0;
                        if (mysqli_num_rows($subjectsQuery) >= 1) {
                            $conceptsInt['totalInterviews'] = mysqli_num_rows($subjectsQuery);
                            $conceptsInt['interviews'] = mysqli_fetch_all($subjectsQuery, MYSQLI_ASSOC);
                        }
                        array_push($conceptsInterviews, $conceptsInt);
                    }
                    $rows['concepts'] = $conceptsInterviews;
                    unset($conceptsInterviews);
                    $conceptsInterviews = array();
                }
                $removedProgrammingSubjectQuery = mysqli_query($databaseConnection, "Select if(FIND_IN_SET('".$rows['subject_id']."', '".$values['mentorshipData']['removeProgSubjects']."'), 'Y', 'N') as isRemovedSubject");
                $removedProgrammingSubjectResult = mysqli_fetch_array($removedProgrammingSubjectQuery, MYSQLI_ASSOC);
                $rows['isRemovedSubject'] = $removedProgrammingSubjectResult['isRemovedSubject'];
                array_push($mentorshipOtherSubject, $rows);
            }
            $values['mentorshipOtherSubject'] = $mentorshipOtherSubject;*/

            /*$mentorshipCompulsoryQuery = mysqli_query($databaseConnection, "select m.name as menuName, fs.id as subject_id, fs.favourite_subject from favourite_subject fs left outer join menu_subject_transection mst on mst.subject_id = fs.id left outer join menu m on m.id = mst.menu_id where fs.id in (20, 40) order by favourite_subject");
            while ($compulsoryRows = mysqli_fetch_array($mentorshipCompulsoryQuery, MYSQLI_ASSOC)) {
                $compulsorySubjectsQuery = mysqli_query($databaseConnection, "select id, name from concepts where subject_id = '".$compulsoryRows['subject_id']."' order by name");
                $compulsoryRows['concepts'] = '';
                $compulsoryRows['totalConcepts'] = 0;
                if (mysqli_num_rows($compulsorySubjectsQuery) >= 1) {
                    $compulsoryRows['totalConcepts'] = mysqli_num_rows($compulsorySubjectsQuery);
                    //$compulsoryRows['interviews'] = mysqli_fetch_all($compulsorySubjectsQuery, MYSQLI_ASSOC);
                    while ($conceptsInter = mysqli_fetch_array($compulsorySubjectsQuery, MYSQLI_ASSOC)) {
                        $subQuery = mysqli_query($databaseConnection, "select id, name from interview where concept_id = '".$conceptsInter['id']."' and isActive = 'Y' and deleted_at is null order by name");
                        $conceptsInter['interviews'] = '';
                        $conceptsInter['totalInterviews'] = 0;
                        if (mysqli_num_rows($subQuery) >= 1) {
                            $conceptsInter['totalInterviews'] = mysqli_num_rows($subQuery);
                            $conceptsInter['interviews'] = mysqli_fetch_all($subQuery, MYSQLI_ASSOC);
                        }
                        array_push($conceptsInterview, $conceptsInter);
                    }
                    $compulsoryRows['concepts'] = $conceptsInterview;
                    unset($conceptsInterview);
                    $conceptsInterview = array();
                }
                $removedLifeSkillsQuery = mysqli_query($databaseConnection, "Select if(FIND_IN_SET('".$compulsoryRows['subject_id']."', '".$values['mentorshipData']['removeLifeSkillsSubjects']."'), 'Y', 'N') as isRemovedSubject");
                $removedLifeSkillsResult = mysqli_fetch_array($removedLifeSkillsQuery, MYSQLI_ASSOC);
                $compulsoryRows['isRemovedSubject'] = $removedLifeSkillsResult['isRemovedSubject'];
                array_push($mentorshipCompulsorySubject, $compulsoryRows);
            }
            $values['mentorshipCompulsorySubject'] = $mentorshipCompulsorySubject;*/

            /* if ($values['mentorshipData']['addedInterviewId'] != '') {
                $addedInterviewQuery = mysqli_query($databaseConnection, "SELECT m.addedInterviewId, i.id, i.name FROM menteelist m, interview i WHERE FIND_IN_SET(i.id, m.addedInterviewId) and m.candidateId = '".$values['mentorshipData']['candidateId']."'");
                $addedInterviewResult = mysqli_fetch_all($addedInterviewQuery, MYSQLI_ASSOC);
                $values['mentorshipAddedInterview'] = $addedInterviewResult;
            } else {
                $values['mentorshipAddedInterview'] = [];
            }*/
        } else {
            $values['mentorshipData'] = null;
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'mentorshipData' => $values['mentorshipData']
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error whire retrieving user information."
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getExpertMentorshipPlan'])) {
    /* It is for expert dashboard change by Naraayn  6/8/2021 */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['candidateId'];
        $values = array();
        $data = "Select p.*,u.firstName as candidateName,u.panelId,u.usertype,u.mobileNumber,u.createdOn,pd.year,s.stream from users u inner join  panel p on p.id =  u.panelId inner join professionaldetails pd on pd.candidateId = u.id inner join stream s on pd.specialization = s.id where u.id='" . $candidateId . "'";
        $query = mysqli_query($databaseConnection, $data);
        if (mysqli_num_rows($query) >= 1) {
            while ($expertData = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
                $expertData['picture'] = 'panel_' . $expertData['id'] . '.png';
                $areaOfQuery = mysqli_query($databaseConnection, "SELECT group_concat(fs.favourite_subject SEPARATOR ', ') AS areaOfExpertise_name FROM panel pd, favourite_subject fs WHERE FIND_IN_SET(fs.id, pd.areaOfExpertiseId) and pd.id = '" . $expertData['id'] . "'");
                $areaOfResult = mysqli_fetch_array($areaOfQuery, MYSQLI_ASSOC);
                $expertData['areaOfExpertise_name'] = $areaOfResult['areaOfExpertise_name'];
                $totalGivenFeedbackQuery = "select count(*) as totalGivenFeedback from (select er.id, er.feedbackGivenBy from expert_review_observation_details erod inner join observation_values ov on erod.observationValueId = ov.id inner join observation_area oa on ov.observation_id = oa.id inner join expert_review er on erod.expertReviewId = er.id inner join feedback_request fr on fr.id = er.feedback_request_id INNER JOIN feedback_status_question fsq ON fsq.feedbackRequestId = er.feedback_request_id AND fsq.questionId = er.questionId where oa.key_skill != '0' and oa.is_final_parameters = 'N' and oa.id != '25' and fsq.review_status = '2' and er.feedbackGivenBy = '" . $expertData['id'] . "' group by er.id) as temp";
                $totalGivenFeedbackResult = mysqli_query($databaseConnection, $totalGivenFeedbackQuery);
                $totalGivenFeedbackValues = mysqli_fetch_assoc($totalGivenFeedbackResult);
                if ($totalGivenFeedbackValues['totalGivenFeedback']) {
                    $expertData['totalGivenFeedback'] = $totalGivenFeedbackValues['totalGivenFeedback'];
                } else {
                    $expertData['totalGivenFeedback'] = '0';
                }

                $totalVideoFeedbackResult = mysqli_query($databaseConnection, "SELECT SEC_TO_TIME( SUM( TIME_TO_SEC( er.vidLength ) ) ) AS vidLength FROM expert_review er, feedback_request fr INNER JOIN feedback_status_question fsq ON fsq.feedbackRequestId = fr.id WHERE fr.id = er.feedback_request_id AND fsq.questionId = er.questionId and fsq.review_status = '2'  and er.isGvAvailable='N' and er.overallRating !='VideoIssue' and  er.feedbackGivenBy = '" . $expertData['id'] . "' ");
                $totalVideoFeedbackValues = mysqli_fetch_assoc($totalVideoFeedbackResult);
                if ($totalVideoFeedbackValues['vidLength']) {
                    $expertData['totalVideoFeedback'] = $totalVideoFeedbackValues['vidLength'];
                } else {
                    $expertData['totalVideoFeedback'] = '00:00:00';
                }
                $totalGvVideoFeedbackResult = mysqli_query($databaseConnection, "SELECT SEC_TO_TIME( SUM( TIME_TO_SEC( er.vidLength ) ) ) AS vidLength FROM expert_review er, feedback_request fr INNER JOIN feedback_status_question fsq ON fsq.feedbackRequestId = fr.id WHERE fr.id = er.feedback_request_id AND fsq.questionId = er.questionId and fsq.review_status = '2' and er.isGvAvailable='Y' and er.feedbackGivenBy = '" . $expertData['id'] . "' ");
                $totalGvVideoFeedbackValues = mysqli_fetch_assoc($totalGvVideoFeedbackResult);
                if ($totalGvVideoFeedbackValues['vidLength']) {
                    $expertData['totalGvVideoFeedback'] = $totalGvVideoFeedbackValues['vidLength'];
                } else {
                    $expertData['totalGvVideoFeedback'] = '00:00:00';
                }
                $totalCandidateVideoWatchResult = mysqli_query($databaseConnection, "SELECT SEC_TO_TIME( SUM( TIME_TO_SEC( vwd.vidWatchedDuration ) ) ) AS vidLength from mergedVideos m inner join video_watched_details vwd on vwd.mergeId = m.mergeId inner join feedback_request fr on fr.interviewSessionId = m.interviewSessionId inner join expert_review er on er.feedback_request_id = fr.id and er.questionId = m.questionId INNER JOIN feedback_status_question fsq ON fsq.feedbackRequestId = fr.id AND fsq.questionId = er.questionId WHERE er.overallRating !='VideoIssue'  and er.review_type='question' and fsq.review_status = '2' and er.feedbackGivenBy = '" . $expertData['id'] . "' ");
                $totalCandidateVideoWatchValues = mysqli_fetch_assoc($totalCandidateVideoWatchResult);
                if ($totalCandidateVideoWatchValues['vidLength']) {
                    $expertData['totalCandidateVideoWatch'] = $totalCandidateVideoWatchValues['vidLength'];
                } else {
                    $expertData['totalCandidateVideoWatch'] = '00:00:00';
                }
                $totalCandidateVideoResult = mysqli_query($databaseConnection, "select SEC_TO_TIME( SUM( TIME_TO_SEC( m.vidLength ) ) ) AS vidLength from mergedVideos m inner join feedback_request fr on fr.interviewSessionId = m.interviewSessionId inner join expert_review er on er.feedback_request_id = fr.id and er.questionId = m.questionId INNER JOIN feedback_status_question fsq ON fsq.feedbackRequestId = fr.id AND fsq.questionId = er.questionId WHERE er.overallRating !='VideoIssue'  and er.review_type='question' and fsq.review_status = '2' and er.feedbackGivenBy = '" . $expertData['id'] . "' ");
                $totalCandidateVideoValues = mysqli_fetch_assoc($totalCandidateVideoResult);
                if ($totalCandidateVideoValues['vidLength']) {
                    $expertData['totalCandidateVideo'] = $totalCandidateVideoValues['vidLength'];
                } else {
                    $expertData['totalCandidateVideo'] = '00:00:00';
                }

                $questionVideoResult = mysqli_query($databaseConnection, "SELECT count(fr.vidLength) as totalQuestion, SEC_TO_TIME( SUM( TIME_TO_SEC( fr.vidLength ) ) ) AS vidLength FROM questions_transection fr where fr.delegationType = 'questionVideo' and fr.uploadStatus = 2 and fr.expertId = '" . $expertData['id'] . "' ");
                $questionVideoValues = mysqli_fetch_assoc($questionVideoResult);
                if ($questionVideoValues['vidLength'] || $questionVideoValues['totalQuestion']) {
                    $expertData['totalQuestionVideoLength'] = $questionVideoValues['vidLength'];
                    $expertData['totalQuestionVideo'] = $questionVideoValues['totalQuestion'];
                } else {
                    $expertData['totalQuestionVideoLength'] = '00:00:00';
                    $expertData['totalQuestionVideo'] = '0';
                }

                $guidanceVideoResult = mysqli_query($databaseConnection, "SELECT count(fr.vidLength) as totalQuestion, SEC_TO_TIME( SUM( TIME_TO_SEC( fr.vidLength ) ) ) AS vidLength FROM questions_transection fr where fr.delegationType = 'guidanceVideo' and fr.uploadStatus = 2 and fr.expertId = '" . $expertData['id'] . "' ");
                $guidanceVideoValues = mysqli_fetch_assoc($guidanceVideoResult);
                if ($guidanceVideoValues['vidLength'] || $questionVideoValues['totalQuestion']) {
                    $expertData['totalGuidanceVideoLength'] = $guidanceVideoValues['vidLength'];
                    $expertData['totalGuidanceVideo'] = $questionVideoValues['totalQuestion'];
                } else {
                    $expertData['totalGuidanceVideoLength'] = '00:00:00';
                    $expertData['totalGuidanceVideo'] = '0';
                }

                $peerResponseVideoResult = mysqli_query($databaseConnection, "SELECT count(fr.vidLength) as totalQuestion, SEC_TO_TIME( SUM( TIME_TO_SEC( fr.vidLength ) ) ) AS vidLength FROM questions_transection fr where fr.delegationType = 'peerResponseVideo' and fr.uploadStatus = 2 and fr.expertId = '" . $expertData['id'] . "' ");
                $peerVideoValues = mysqli_fetch_assoc($peerResponseVideoResult);
                if ($peerVideoValues['vidLength'] || $peerVideoValues['totalQuestion']) {
                    $expertData['totalPeerResponseVideoLength'] = $peerVideoValues['vidLength'];
                    $expertData['totalPeerResponseVideo'] = $peerVideoValues['totalQuestion'];
                } else {
                    $expertData['totalPeerResponseVideoLength'] = '00:00:00';
                    $expertData['totalPeerResponseVideo'] = '0';
                }

                $totalTaggingQuery = mysqli_query($databaseConnection, "SELECT count(fr.id) as totalTaggingQuestion FROM questions_transection fr where fr.delegationType = 'tagging' and fr.uploadStatus = 2 and fr.expertId = '" . $expertData['id'] . "' ");
                $totalTaggingValue = mysqli_fetch_assoc($totalTaggingQuery);
                if ($totalTaggingValue['totalTaggingQuestion']) {
                    $expertData['totalTaggingQuestion'] = $totalTaggingValue['totalTaggingQuestion'];
                } else {
                    $expertData['totalTaggingQuestion'] = '0';
                }
                $filterContent = "0 ";
                $filterAssement = "0";
                if ($expertData['expertStatus'] == 1) {
                    $expertExpertise = explode(",", $expertData['areaOfExpertiseId']);

                    foreach ($expertExpertise as $afe) {
                        if ($expertData['isVideoApproved'] == 'Y' && $expertData['isTaggingApproved'] == 'Y') {
                            $filterContent .= " OR (FIND_IN_SET('" . $afe . "', q.subjectId) and fr.delegationType !='peerResponseVIdeo')";
                        }
                        if ($expertData['isVideoApproved'] !== 'Y' && $expertData['isTaggingApproved'] == 'Y') {
                            $filterContent .= " OR (FIND_IN_SET('" . $afe . "', q.subjectId) and fr.delegationType !='peerResponseVIdeo' and fr.delegationType !='guidanceVideo' and fr.delegationType !='questionVideo')";
                        }
                        if ($expertData['isVideoApproved'] == 'Y' && $expertData['isTaggingApproved'] !== 'Y') {
                            $filterContent .= " OR (FIND_IN_SET('" . $afe . "', q.subjectId) and fr.delegationType !='peerResponseVIdeo' and fr.delegationType !='tagging')";
                        }
                        if ($expertData['isPeerApproved'] == 'Y') {
                            $filterContent .= " OR (FIND_IN_SET('" . $afe . "', q.subjectId) and fr.delegationType ='peerResponseVIdeo')";
                        }
                        if ($expertData['isAssessmentApproved'] == 'Y') {
                            $filterAssement .= " OR FIND_IN_SET('" . $afe . "', q.subjectId)";
                        }
                    }
                }

                $totalContentQuery = mysqli_query($databaseConnection, "SELECT count(fr.id) as totalPendingContentQuestion FROM questions_transection fr  inner join questions q on q.id =fr.questionId  left outer join panel p on p.id = fr.expertId where (fr.uploadStatus = 1 OR fr.uploadStatus=0) and (((fr.expertId = '" . $expertData['id'] . "' and p.isVideoApproved='Y' and fr.delegationType !='peerResponseVideo') or (fr.expertId = '" . $expertData['id'] . "' and p.isPeerApproved='Y' and fr.delegationType ='peerResponseVideo')) or (fr.expertId is null and (" . $filterContent . ")))");

                $totalContentValue = mysqli_fetch_assoc($totalContentQuery);
                if ($totalContentValue['totalPendingContentQuestion']) {
                    $expertData['totalPendingContentQuestion'] = $totalContentValue['totalPendingContentQuestion'];
                } else {
                    $expertData['totalPendingContentQuestion'] = '0';
                }

                $totalPandingQuery = mysqli_query($databaseConnection, "select count(fsq.questionId) as totalPendingFeedback FROM `feedback_status_question` fsq inner join questions q on fsq.questionId = q.id left outer join panel p on p.id = fsq.expertId where fsq.review_status IN(0,1) and  (fsq.expertId = '" . $expertData['id'] . "' or (fsq.expertId is null and (" . $filterAssement . ")));");
                $totalPandingValue = mysqli_fetch_assoc($totalPandingQuery);
                if ($totalPandingValue['totalPendingFeedback']) {
                    $expertData['totalPendingFeedback'] = $totalPandingValue['totalPendingFeedback'];
                } else {
                    $expertData['totalPendingFeedback'] = '0';
                }

                $values['expertDataList'] = $expertData;
            }
            $to_encode = $values;
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "out Error whire retrieving Expert information."
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error whire retrieving Expert information."
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['updateMentorshipData'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['candidateId'];
        $fav_subjects = $json['fav_subjects'];
        $fav_programming_skill = $json['fav_programming_skill'];
        // $fav_domain = $json['fav_domain'];
        $asp_companies = $json['asp_companies'];
        $languages = $json['languages'];
        $cgpa = $json['cgpa'];
        $webinarTopic = addslashes($json['webinarTopic']);
        //$sessionStartDate = $json['sessionStartDate'];
        $other_subjects = addslashes($json['otherSubject']);
        $other_prog_skills = addslashes($json['otherProgSkill']);
        // $other_domain = addslashes($json['otherDomain']);
        $other_companies = addslashes($json['otherCompany']);
        $professionalCourseTaken = addslashes($json['professionalCourseTaken']);

        /* if($json['productId'] != null){
            $productId = implode(',', $json['productId']);
        }else{
            $productId = $json['productId'];
        }*/

        /* $s_sql="select * from subscription where candidateId ='".$candidateId."'";
        $s_query = mysqli_query($databaseConnection,$s_sql);
        if(mysqli_num_rows($s_query)>0){
            $updateSubQuery = "Update subscription SET productId='".$productId."' WHERE candidateId ='".$candidateId."'";
            $updateSubResult = mysqli_query($databaseConnection, $updateSubQuery);
            if ($updateSubResult) {
                $to_encode = array(
                    'status' => 1,
                    'result' => "success",
                    'message' => "Data updated successfully",
                );
            } else {
                $to_encode = array(
                    'status' => 0,
                    'result' => "error",
                    'message' => 'Error while updating subscription data',
                );
            }
        }*/

        /*if ($json['otherSubject'] != "") {
            array_pop($fav_subjects);
            $json['otherSubject'] = explode(",",$json['otherSubject']);
            for($i=0; $i<count($json['otherSubject']); $i++) {
                if(trim($json['otherSubject'][$i]) != '') {
                    $subjectQuery = mysqli_query($databaseConnection, "insert into favourite_subject(favourite_subject) values ('".addslashes($json['otherSubject'][$i])."');");
                    $subject_id = mysqli_insert_id($databaseConnection);
                    array_push($fav_subjects, $subject_id);
                }
            }
        }

        if ($json['otherProgSkill'] != "") {
            array_pop($fav_programming_skill);
            $json['otherProgSkill'] = explode(",",$json['otherProgSkill']);
            for($i=0; $i<count($json['otherProgSkill']); $i++) {
                if(trim($json['otherProgSkill'][$i]) != '') {
                    $favProgSkillQuery = mysqli_query($databaseConnection, "insert into fav_prog_skill(fav_prog_skill) values ('".addslashes($json['otherProgSkill'][$i])."');");
                    $favProgSkill_id = mysqli_insert_id($databaseConnection);
                    array_push($fav_programming_skill, $favProgSkill_id);
                }
            }
        }*/

        /* if ($json['otherDomain'] != "") {
            array_pop($fav_domain);
            $json['otherDomain'] = explode(",",$json['otherDomain']);
            for($i=0; $i<count($json['otherDomain']); $i++) {
                if(trim($json['otherDomain'][$i]) != '') {
                    $domainQuery = mysqli_query($databaseConnection, "insert into favourite_domain(name) values ('".addslashes($json['otherDomain'][$i])."');");
                    $domain_id = mysqli_insert_id($databaseConnection);
                    array_push($fav_domain, $domain_id);
                }
            }
        }*/

        if ($json['otherCompany'] != "") {
            array_pop($asp_companies);
            $json['otherCompany'] = explode(",", $json['otherCompany']);
            for ($i = 0; $i < count($json['otherCompany']); $i++) {
                if (trim($json['otherCompany'][$i]) != '') {
                    $companyQuery = mysqli_query($databaseConnection, "insert into aspiration_company(name) values ('" . addslashes($json['otherCompany'][$i]) . "');");
                    $company_id = mysqli_insert_id($databaseConnection);
                    array_push($asp_companies, $company_id);
                }
            }
        }

        $data = "update professionaldetails set fav_subjects = '" . implode(',', $fav_subjects) . "', cgpa = '" . $cgpa . "', other_subjects = NULLIF('$other_subjects',''), fav_programming_skill = '" . implode(',', $fav_programming_skill) . "', other_prog_skills = NULLIF('$other_prog_skills',''),webinarTopic='" . $webinarTopic . "', asp_companies = '" . implode(',', $asp_companies) . "', other_companies = NULLIF('$other_companies',''),languages = '" . implode(',', $languages) . "', professionalCourseTaken = NULLIF('" . $professionalCourseTaken . "', '') where candidateId='" . $candidateId . "'";

        $query = mysqli_query($databaseConnection, $data);
        if ($query) {
            mysqli_query($databaseConnection, "update users set isMentee = 'Y' where id = '" . $candidateId . "'");
            $to_encode = array(
                'status' => 1,
                'result' => "success"
            );
            /* $menteeData="select * from menteelist where candidateId = '".$candidateId."'";
            $menteeDataQuery = mysqli_query($databaseConnection,$menteeData);
            if(mysqli_num_rows($menteeDataQuery)>0){
                //$updateMenteeQuery = "Update menteelist SET hoursSpendPerWeek = ".$hoursSpendPerWeek.", sessionStartDate = NULLIF('$sessionStartDate','') WHERE candidateId = '".$candidateId."'";
               // $updateMenteeQuery = "Update menteelist SET hoursSpendPerWeek = ".$hoursSpendPerWeek." WHERE candidateId = '".$candidateId."'";
                $updateMenteeResult = mysqli_query($databaseConnection, $updateMenteeQuery);
            } else {
                $insertMenteeQuery = "insert into menteelist(candidateId, hoursSpendPerWeek, formSubmissionDate) values ('".$candidateId."', ".$hoursSpendPerWeek.", now())";
                $insertMenteeResult = mysqli_query($databaseConnection, $insertMenteeQuery);
            }
            $to_encode = array(
                'status' => 1,
                'result' => "success"
            );*/
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "in Error whire retrieving user information.",
                'query' => $data
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error whire retrieving user information."
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['updatetpMentorshipData'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['candidateId'];
        $interviewSessionId = $json['interviewSessionId'];
        $interviewId = $json['interviewId'];
        $connecttomentor = $json['connecttomentor'];
        $timetocontact = $json['timetocontact'];
        $connecttomentorname = $json['connecttomentorname'];
        $connecttomentornames = str_replace(',', ', ', $connecttomentorname);
        $connectInterest = $json['isInterested'];

        //    echo $candidateId;
        //    echo $interviewSessionId;
        //    echo $interviewId;
        //     echo $connecttomentor;
        //     echo $timetocontact;
        //     echo $connecttomentorname;
        //     echo $connecttomentornames;
        //     echo $connectInterest;

        $sql = "select * from connect_mentor where candidateId='" . $candidateId . "' and interviewId=" . $interviewId . "";

        $result = mysqli_query($databaseConnection, $sql);
        if (mysqli_num_rows($result) >= 1) {
            if ($connectInterest == 'Yes') {
                $data = "update connect_mentor set connecttomentor = '" . implode(',', $connecttomentor) . "',timetocontact= '" . $timetocontact . "',connecttomentorname = '" . $connecttomentornames . "',connectDate=now(),connectInterest='" . $connectInterest . "',interviewSessionId=" . $interviewSessionId . " where candidateId='" . $candidateId . "' and interviewId=" . $interviewId . "";
            }
            if ($connectInterest == 'No') {
                $data = "update connect_mentor set connectDate=now(),connectInterest='" . $connectInterest . "',interviewSessionId=" . $interviewSessionId . ",connecttomentor=NULL,timetocontact=NULL,connecttomentorname=NULL where candidateId='" . $candidateId . "' and interviewId=" . $interviewId . "";
            }

            // for payment 
            // sourabh-payment
            if ($connectInterest == 'paymentinprogress') {
                $data = "update connect_mentor set connecttomentor = NULL,timetocontact= '" . $timetocontact . "',connecttomentorname = NULL,connectDate=now(),connectInterest='" . $connectInterest . "',interviewSessionId=" . $interviewSessionId . " where candidateId='" . $candidateId . "' and interviewId=" . $interviewId . "";
            }
            if ($connectInterest == 'notinterested') {
                $data = "update connect_mentor set connectDate=now(),connectInterest='" . $connectInterest . "',interviewSessionId=" . $interviewSessionId . ",connecttomentor=NULL,timetocontact=NULL,connecttomentorname=NULL where candidateId='" . $candidateId . "' and interviewId=" . $interviewId . " and connectInterest !='paid' ";
            }
        } else {
            if ($connectInterest == 'Yes') {
                $data = "INSERT INTO connect_mentor(`candidateId`,`interviewId`,`interviewSessionId`,`connecttomentor`,`timetocontact`,`connecttomentorname`,`connectInterest`,`connectDate`) VALUES ('$candidateId',$interviewId,$interviewSessionId,'" . implode(',', $connecttomentor) . "','$timetocontact','$connecttomentornames','$connectInterest',now())";
            } else if ($connectInterest == 'No') {
                $data = "INSERT INTO connect_mentor(`candidateId`,`interviewId`,`interviewSessionId`,`connectInterest`,`connectDate`) VALUES ('$candidateId',$interviewId,$interviewSessionId,'$connectInterest',now())";
            }
            // for payment
            // sourabh-payment
            else if ($connectInterest == 'paymentinprogress') {
                $data = "INSERT INTO connect_mentor(`candidateId`,`interviewId`,`interviewSessionId`,`connectInterest`,`connectDate`) VALUES ('$candidateId',$interviewId,$interviewSessionId,'$connectInterest',now())";
            } else if ($connectInterest == 'notinterested') {
                $data = "INSERT INTO connect_mentor(`candidateId`,`interviewId`,`interviewSessionId`,`connectInterest`,`connectDate`) VALUES ('$candidateId',$interviewId,$interviewSessionId,'$connectInterest',now())";
            }
        }

        $query = mysqli_query($databaseConnection, $data);
        if ($query) {
            $to_encode = array(
                'status' => 1,
                'result' => "success"
            );

        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "in Error whire retrieving user information.",
                'query' => $data
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error whire retrieving user information."
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['updatePanelExpertiseData'])) {
    $candidateId = $_POST['candidateId'];
    $panelId = $_POST['panelId'];
    $areaOfExpertises = $_POST['areaOfExpertise'];
    $otherAreaOfExpertises = $_POST['otherAreaOfExpertise'];
    $otherAreaOfExpertisesValue = $_POST['otherAreaOfExpertiseValue'];
    $code = $_POST['coding'];
    $coding = str_replace(',', ', ', $code);
    $cloud = $_POST['cloudSubject'];
    $clouding = str_replace(',', ', ', $cloud);
    $dataAnalyst = $_POST['dataAnalystSubject'];
    $dataAnalysting = str_replace(',', ', ', $dataAnalyst);
    $collegeQ = "select id from colleges where collegeName='" . addslashes($_POST['college']) . "'";
    $collegeQuery = mysqli_query($databaseConnection, $collegeQ);
    if (mysqli_num_rows($collegeQuery) > 0) {
        $collegeResult = mysqli_fetch_assoc($collegeQuery);
        $updateUserCollege = mysqli_query($databaseConnection, "UPDATE `professionaldetails` SET `college`='" . $collegeResult['id'] . "' WHERE candidateId ='" . $candidateId . "' ");
    }

    if ($panelId == 0) {
        $user = "select emailId,mobileNumber from users where id='" . $candidateId . "'";


        $userQuery = mysqli_query($databaseConnection, $user);
        $userResult = mysqli_fetch_assoc($userQuery);
        $panelInsert = "INSERT INTO `panel`(`name`,`expertStatus`,`publishStatus`, `qualification`, `oraganisation`,`resumeVideo`, `experience`, `companiesWorked`, `emailId`, `phonenumber`, `panelTitle`,`linkedinProfile`,`expertType`,`coding`,`areaOfExpertiseId`, `otherAreaOfExpertiseId`, `otherAreaOfExpertiseValue`,`referrerName`,`whatsappNumber`,`cloud`,`dataAnalyst`) VALUES ('" . $_POST['name'] . "','0','0','" . $_POST['qualification'] . "','" . addslashes($_POST['college']) . "'," . $_POST['resumeVideo'] . ",'" . $_POST['experience'] . "','" . addslashes($_POST['companiesWorkedFor']) . "','" . $userResult['emailId'] . "', '" . $userResult['mobileNumber'] . "','" . $_POST['name'] . "','" . addslashes($_POST['linkedinProfile']) . "','" . $_POST['expertType'] . "','" . $coding . "','" . $areaOfExpertises . "', '" . $otherAreaOfExpertises . "','" . $otherAreaOfExpertisesValue . "','" . $_POST['referrerName'] . "','" . $_POST['whatsappNo'] . "','" . $_POST['cloudSubject'] . "','" . $_POST['dataAnalystSubject'] . "')";

        $panel_result = mysqli_query($databaseConnection, $panelInsert);
        if ($panel_result) {
            $insertedPanelId = mysqli_insert_id($databaseConnection);
            $updateUserFirstName = mysqli_query($databaseConnection, "UPDATE `users` SET `firstName`='" . $_POST['name'] . "' WHERE id='" . $candidateId . "' ");
            /*added for new expert type of work data  goes into panels_transection Naraayn  19-05-2021 */
            $panelsTransectionInsert = "INSERT INTO `panels_transection`(`PanelId`, `isExpertAssessmentApproved`, `isExpertVideoApproved`, `isExpertPeerApproved`, `isExpertConfirmLater`,`addQuestionorReview`) VALUES (" . $insertedPanelId . ",'" . $_POST['isAssessmentApproved'] . "','" . $_POST['isVideoApproved'] . "','" . $_POST['isPeerApproved'] . "','" . $_POST['confirmLater'] . "','" . $_POST['addQuestionorReview'] . "')";
            $panelsTransection_result = mysqli_query($databaseConnection, $panelsTransectionInsert);
            $updateUser = mysqli_query($databaseConnection, "update users set usertype='expert',panelId='" . $insertedPanelId . "' where id='" . $candidateId . "'");
            $filename = 'panel_' . $insertedPanelId; //panel_id

            if ($_POST['imgVal'] != "") {
                $extension = pathinfo($_FILES['picture']['name'], PATHINFO_EXTENSION); //png
                $basename = $filename . '.' . $extension;
                $file_tmp = $_FILES['picture']['tmp_name'];
                if (file_exists("../pracschool_app/public/images/" . $basename)) {
                    unlink("../pracschool_app/public/images/" . $basename);
                    move_uploaded_file($file_tmp, "../pracschool_app/public/images/" . $basename);
                } else {
                    move_uploaded_file($file_tmp, "../pracschool_app/public/images/" . $basename);
                }
            }

            $to_encode = array(
                'panelId' => $insertedPanelId,
                'result' => "Success",
                'errorCode' => "panel Created successfully.",
                'status' => 1,
            );
        } else {
            $to_encode = array(
                'result' => "error",
                'errorCode' => "panel Creation failed.",
                'status' => 0,
                'query' => $panelInsert
            );
        }
    } else {

        $data = "UPDATE `panel` SET `name`='" . $_POST['name'] . "',`qualification`='" . $_POST['qualification'] . "',`oraganisation`='" . addslashes($_POST['college']) . "',`coding`='" . $coding . "',`experience`='" . $_POST['experience'] . "',`companiesWorked`='" . addslashes($_POST['companiesWorkedFor']) . "',panelTitle='" . $_POST['name'] . "',linkedinProfile='" . addslashes($_POST['linkedinProfile']) . "',expertType='" . $_POST['expertType'] . "',areaOfExpertiseId='" . $areaOfExpertises . "', referrerName ='" . $_POST['referrerName'] . "', whatsappNumber='" . $_POST['whatsappNo'] . "', `otherAreaOfExpertiseId` = '" . $otherAreaOfExpertises . "', `otherAreaOfExpertiseValue` = '" . $otherAreaOfExpertisesValue . "',`cloud`='" . $clouding . "',`dataAnalyst`='" . $dataAnalysting . "' WHERE id='" . $panelId . "'";





        /*Expert only update his/her type of work in panels_transection added by Narayn 19-05-2021*/
        $data_transection = "UPDATE `panels_transection` SET `isExpertConfirmLater`='" . $_POST['confirmLater'] . "',`isExpertAssessmentApproved`='" . $_POST['isAssessmentApproved'] . "',`isExpertVideoApproved`='" . $_POST['isVideoApproved'] . "',`isExpertPeerApproved`='" . $_POST['isPeerApproved'] . "',`addQuestionorReview` ='" . $_POST['addQuestionorReview'] . "' WHERE panelId='" . $panelId . "'";
        $query = mysqli_query($databaseConnection, $data);
        $query_transection = mysqli_query($databaseConnection, $data_transection);
        if ($query) {
            $updateUserFirstName = mysqli_query($databaseConnection, "UPDATE `users` SET `firstName`='" . $_POST['name'] . "' WHERE id='" . $candidateId . "' ");
            $filename = 'panel_' . $panelId; //panel_id
            if ($_POST['imgVal'] != "") {
                $extension = pathinfo($_FILES['picture']['name'], PATHINFO_EXTENSION); //png
                $basename = $filename . '.' . $extension;
                $file_tmp = $_FILES['picture']['tmp_name'];
                if (file_exists("../pracschool_app/public/images/" . $basename)) {
                    unlink("../pracschool_app/public/images/" . $basename);
                    move_uploaded_file($file_tmp, "../pracschool_app/public/images/" . $basename);
                } else {
                    move_uploaded_file($file_tmp, "../pracschool_app/public/images/" . $basename);
                }
            }
            $to_encode = array(
                'status' => 1,
                'result' => "success"
            );
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "in Error whire updating panel information.",
                'query' => $data
            );
        }
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['updateMenteeSubjectData'])) {

    //$data = @file_get_contents("php://input");
    //$json = json_decode($data, true);
    //if (isset($json)) {
    $candidateId = $_POST['candidateId'];
    $removeSubjects = $_POST['removeSubjects'];
    $removeProgSubjects = $_POST['removeProgSubjects'];
    $removeLifeSkillsSubjects = $_POST['removeLifeSkillsSubjects'];
    //$assignedMentorsId = implode(",",$json['assignedMentorsId']);
    $assignedMentorsId = $_POST['assignedMentorsId'];

    if (isset($_POST["mentorCallDate"]) && is_array($_POST["mentorCallDate"])) {
        $numOfLinksMentorCall = count($_POST["mentorCallDate"]);
    } else {
        $numOfLinksMentorCall = 0;
    }

    if (isset($_POST["chatSummary"]) && is_array($_POST["chatSummary"])) {
        $numberOfLinks = count($_POST["chatSummary"]);
    } else {
        $numberOfLinks = 0;
    }

    if (isset($_POST["interviewId"]) && is_array($_POST["interviewId"])) {
        $numOfLinksSessionCalendar = count($_POST["interviewId"]);
    } else {
        $numOfLinksSessionCalendar = 0;
    }

    if (isset($_POST["actionableAdvice"]) && is_array($_POST["actionableAdvice"])) {
        $numOfLinksActionableAdvice = count($_POST["actionableAdvice"]);
    } else {
        $numOfLinksActionableAdvice = 0;
    }

    $data = "update menteelist set removeSubjects = NULLIF('$removeSubjects','null'), removeProgSubjects = NULLIF('$removeProgSubjects','null'), removeLifeSkillsSubjects = NULLIF('$removeLifeSkillsSubjects','null'), assignedMentorsId = NULLIF('$assignedMentorsId','') where candidateId='" . $candidateId . "';";
    $query = mysqli_query($databaseConnection, $data);
    if ($query) {
        $mentorCallQuery = mysqli_query($databaseConnection, 'DELETE FROM `mentor_call_planning` where candidateId=' . $candidateId);

        for ($i = 0; $i < $numOfLinksMentorCall; $i++) {
            if (trim($_POST["mentorCallId"][$i] != '')) {
                $mentorCall = "INSERT INTO mentor_call_planning(candidateId, mentorId, mentorCallDate) VALUES ('" . $candidateId . "', '" . $_POST['mentorCallId'][$i] . "', '" . $_POST['mentorCallDate'][$i] . "')";
                mysqli_query($databaseConnection, $mentorCall);
            }
        }

        $mentoringHistoryQuery = mysqli_query($databaseConnection, 'DELETE FROM `mentor_history` where candidateId=' . $candidateId);

        for ($i = 0; $i < $numberOfLinks; $i++) {
            if (trim($_POST["chatSummary"][$i] != '')) {
                $mentorHistory = "INSERT INTO mentor_history(candidateId, mentorName, chatSummary, createdAt) VALUES ('" . $candidateId . "', '" . addslashes($_POST["mentorName"][$i]) . "', '" . addslashes($_POST["chatSummary"][$i]) . "', '" . addslashes($_POST["chatDate"][$i]) . "')";
                mysqli_query($databaseConnection, $mentorHistory);
            }
        }

        $sessionCalendarQuery = mysqli_query($databaseConnection, 'DELETE FROM `session_calendar` where candidateId=' . $candidateId);

        for ($i = 0; $i < $numOfLinksSessionCalendar; $i++) {
            if (trim($_POST["interviewId"][$i] != '')) {
                $sessionCalendar = "INSERT INTO session_calendar(candidateId, subjectId, interviewId, doneBeforeDate) SELECT '" . $candidateId . "', i.subject_id, '" . $_POST['interviewId'][$i] . "', '" . addslashes($_POST['doneBeforeDate'][$i]) . "' FROM interview i WHERE i.id = '" . $_POST['interviewId'][$i] . "'";
                mysqli_query($databaseConnection, $sessionCalendar);
            }
        }

        $actionableAdviceQuery = mysqli_query($databaseConnection, 'DELETE FROM `mentoring_actionable_advice` where candidateId=' . $candidateId);

        for ($i = 0; $i < $numOfLinksActionableAdvice; $i++) {
            if (trim($_POST["actionableAdvice"][$i] != '')) {
                $actionableAdvice = "INSERT INTO mentoring_actionable_advice(candidateId, subjectId, interviewId, observations, actionableAdvice) VALUES ('" . $candidateId . "', '" . $_POST['subjectId'][$i] . "', '" . $_POST['interviewIds'][$i] . "', '" . addslashes($_POST['observations'][$i]) . "', '" . addslashes($_POST['actionableAdvice'][$i]) . "')";
                mysqli_query($databaseConnection, $actionableAdvice);
            }
        }

        $to_encode = array(
            'status' => 1,
            'result' => "success"
        );
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "in Error while updating user information.",
            'query' => $data
        );
    }
    /*} else {
        $to_encode = array(
            'status' => - 1,
            'result' => "error",
            'errorCode' => "out Error while updating user information."
        );
    }*/
    echo json_encode($to_encode);
} elseif (isset($_GET['updateProfessionalInfo'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        try {
            $candidateId = getDecrypt($json['userData'])->userId;
            if (validateField($json['emailId'], 'email'))
                $email = $json['emailId'];
            else
                throw new Exception("invalidField");

            $firstName = "";
            $gender = "";
            $mobileNumber = "";
            $instituteCode = "";


            $currentCompany = "";
            $currentSalary = "";
            $expectedSalary = "";
            $workexperience = "";
            $currentlocation = "";
            $noticePeriod = "";
            $currentLocation = "";
            $employmentStatus = "";
            $resume = "";
            $skills = "";

            $briefSummary = "";
            $offer = "";
            $offeredCTC = "";
            $outstationDeclaration = "";

            $roleId = $json['roleId'] ?? "NULL";
            $subjectId = $json['subjectId'] ?? "NULL";


            if (validateField($json['firstName'], 'name'))
                $firstName = $json['firstName'];
            else
                throw new Exception("invalidField");

            $gender = $json['gender'];

            if (validateField($json['mobileNumber'], 'mobile'))
                $mobileNumber = $json['mobileNumber'];
            else
                throw new Exception("invalidField");

            if ($json['instituteCode'] == '') {
                $instituteCode = NULL;
            } else {
                $instituteCode = $json['instituteCode'];
            }


            if ($json['briefSummary'] == '') {
                $briefSummary = NULL;
            } else {
                $briefSummary = mysqli_real_escape_string($databaseConnection, $json['briefSummary']);
            }

            if ($json['offer'] == '') {
                $offer = NULL;
            } else {
                $offer = $json['offer'];
            }

            if ($json['offeredCTC'] == '') {
                $offeredCTC = NULL;
            } else {
                $offeredCTC = $json['offeredCTC'];
            }
            if ($json['outstationDeclaration'] == '') {
                $outstationDeclaration = NULL;
            } else {
                $outstationDeclaration = $json['outstationDeclaration'];
            }


            if ($json['currentCompany'] == '') {
                $currentCompany = NULL;
            } else {
                $currentCompany = $json['currentCompany'];
            }

            if (!empty($json['noticePeriod'])) {
                if (is_array($json['noticePeriod'])) {
                    $noticePeriod = implode(',', $json['noticePeriod']);
                } else {
                    $noticePeriod = $json['noticePeriod'];
                }
            } else {
                $noticePeriod = null;
            }

            if ($json['currentSalary'] == '') {
                $currentSalary = NULL;
            } else {
                $currentSalary = str_replace(',', '', $json['currentSalary']); // Remove commas
            }

            if ($json['expectedSalary'] == '') {
                $expectedSalary = NULL;
            } else {
                $expectedSalary = str_replace(',', '', $json['expectedSalary']); // Remove commas
            }

            if ($json['workexperience'] == '') {
                $workexperience = null;
            } else {
                if (is_array($json['workexperience'])) {
                    $workexperience = implode(',', $json['workexperience']);
                } else {
                    $workexperience = $json['workexperience'];
                }
            }

            if ($json['currentLocation'] == '') {
                $currentLocation = null;
            } else {
                if (is_array($json['currentLocation'])) {
                    $currentLocation = implode(',', $json['currentLocation']);
                } else {
                    $currentLocation = $json['currentLocation'];
                }
            }


            if ($json['employmentStatus'] == '') {
                $employmentStatus = NULL;
            } else {
                $employmentStatus = $json['employmentStatus'];
            }

            if ($json['resume'] == '') {
                $resume = NULL;
            } else {
                if (is_array($json['resume'])) {
                    $resume = implode(',', $json['resume']);
                } else {
                    $resume = $json['resume'];
                }
            }

            if ($json['skills'] == '') {
                $skills = NULL;
            } else {
                $skills = $json['skills'];
            }

            $firstName = addslashes($firstName);
            $getUserEmail = "select * from users where id=" . $candidateId . "";
            $getUserEmailQuery = mysqli_query($databaseConnection, $getUserEmail);
            $userResult = mysqli_fetch_assoc($getUserEmailQuery);

            $getUserDetails = "select usertype,panelId from users where id  in ('" . $candidateId . "');";
            $getUserDetailsQuery = mysqli_query($databaseConnection, $getUserDetails);
            $UserDetailsResult = mysqli_fetch_assoc($getUserDetailsQuery);

            if (mysqli_num_rows($getUserEmailQuery) > 0) {

                $data = "UPDATE users set profile_updated='Y', firstName='" . $firstName . "',gender='" . $gender . "',mobileNumber='" . $mobileNumber . "', instituteCode='" . $instituteCode . "' where id='" . $candidateId . "'";

                $query = mysqli_query($databaseConnection, $data);

                if ($UserDetailsResult['usertype'] == 'expert') {
                    $updatePanel = mysqli_query($databaseConnection, "UPDATE panel set phonenumber='" . $mobileNumber . "' where id= '" . $UserDetailsResult['panelId'] . "'");
                }


                $profData = "select * from professionaldetails where candidateId='" . $candidateId . "' limit 0,1";
                $profQuery = mysqli_query($databaseConnection, $profData);

                if (mysqli_num_rows($profQuery) > 0) {

                    $data = "UPDATE professionaldetails 
                            SET currentCompany='" . $currentCompany . "', 
                                salary='" . $currentSalary . "', 
                                expectedSalary='" . $expectedSalary . "', 
                                workexperience='" . $workexperience . "', 
                                currentLocation='" . $currentLocation . "', 
                                noticePeriod='" . $noticePeriod . "', 
                                employmentStatus='" . $employmentStatus . "',
                                resume='" . $resume . "',
                                skills='" . $skills . "',
                                briefSummary='" . $briefSummary . "',
                                offer='" . $offer . "',
                                offeredCTC='" . $offeredCTC . "',
                                outstationDeclaration='" . $outstationDeclaration . "',
                                `roleId`='$roleId',
                                `subjectId`='$subjectId'
                            WHERE candidateId='" . $candidateId . "'";


                    // echo $data;

                    $query = mysqli_query($databaseConnection, $data);

                    if ($query) {
                        $to_encode = array(
                            'result' => "Success",
                            'response' => 'professional information Updated Successful.',
                            'status' => "1"
                        );

                        //
                        if (!empty($skills)) {
                            //"13,21,422,424,435,440,471,604,716,726,1014,1063,1099,1102"
                            // Fetch existing skills for the user from candidate_skills using both candidateId and emailId
                            $user_id = $candidateId;
                            $existingSkillsQuery = "
                            SELECT skillId, candidateId 
                            FROM candidate_skills 
                            WHERE candidateId = $user_id
                            OR emailId = (SELECT emailId FROM users WHERE id = $user_id);
                            ";

                            $existingSkillsResult = mysqli_query($databaseConnection, $existingSkillsQuery);
                            $existingSkills = [];
                            while ($row = mysqli_fetch_assoc($existingSkillsResult)) {
                                $existingSkills[] = $row['skillId']; // Collect existing skill IDs
                            }

                            // Process the incoming skill IDs
                            $skillsArray = explode(',', $skills);
                            $skillsArray = array_map('intval', $skillsArray); // Convert IDs to integers
                            $skillsList = implode(',', $skillsArray);

                            // Query to fetch skill names and IDs
                            $query = "SELECT id, favourite_subject AS name FROM favourite_subject WHERE id IN ($skillsList)";
                            $result = mysqli_query($databaseConnection, $query);

                            // Initialize array to store skills
                            $newSkillsArray = [];

                            if ($result && mysqli_num_rows($result) > 0) {
                                while ($row = mysqli_fetch_assoc($result)) {
                                    $newSkillsArray[] = $row; // Store each skill
                                }
                            }

                            // var_dump($newSkillsArray);
                            // exit();

                            // Process skills: Insert new, Delete old, Do nothing for matching ones
                            foreach ($newSkillsArray as $skill) {
                                $skillId = $skill['id'];
                                $skillName = mysqli_real_escape_string($databaseConnection, $skill['name']);
                                $yoe = 0;
                                $projectDetails = ''; // Set project details here if needed

                                // Check if the skill is already in the existing skills array
                                if (!in_array($skillId, $existingSkills)) {
                                    // Insert new skill if not already present
                                    $insertQuery = "
                                        INSERT INTO candidate_skills (candidateId, skillId, name, yoe, projectDetails, emailId)
                                        VALUES ($user_id, $skillId, '$skillName', '$yoe', " . ($projectDetails !== null ? "'$projectDetails'" : "NULL") . ", 
                                        (SELECT emailId FROM users WHERE id = $user_id))
                                    ";

                                    // echo $insertQuery;

                                    // Execute insert query
                                    $insertQueryResult = mysqli_query($databaseConnection, $insertQuery);

                                    if (!$insertQueryResult) {
                                        $to_encode = array(
                                            'result' => "error",
                                            'error' => "Error inserting skill: " . mysqli_error($databaseConnection),
                                            'status' => -6
                                        );
                                    }
                                }
                            }

                            // Update skills that exist in both existingSkills and newSkillsArray
                            foreach ($newSkillsArray as $skill) {
                                $skillId = $skill['id'];

                                if (in_array($skillId, $existingSkills)) {
                                    // Check if the skill exists in candidate_skills but has no candidateId set
                                    $updateQuery = "
                                        UPDATE candidate_skills 
                                        SET candidateId = IF(candidateId IS NULL, $user_id, candidateId)
                                        WHERE skillId = $skillId 
                                        AND (candidateId IS NULL OR candidateId != $user_id)
                                        AND emailId = (SELECT emailId FROM users WHERE id = $user_id);
                                    ";

                                    $updateQueryResult = mysqli_query($databaseConnection, $updateQuery);

                                    if (!$updateQueryResult) {
                                        $to_encode = array(
                                            'result' => "error",
                                            'error' => "Error updating skill: " . mysqli_error($databaseConnection),
                                            'status' => -8
                                        );
                                    }
                                }
                            }

                            // Delete skills that are no longer in the $newSkillsArray but are in the existingSkills
                            foreach ($existingSkills as $existingSkillId) {
                                if (!in_array($existingSkillId, $skillsArray)) {
                                    // Delete skill if it exists in existingSkills but not in the new skills list
                                    $deleteQuery = "
                                        DELETE FROM candidate_skills
                                        WHERE candidateId = $user_id AND skillId = $existingSkillId
                                    ";

                                    $deleteQueryResult = mysqli_query($databaseConnection, $deleteQuery);

                                    if (!$deleteQueryResult) {
                                        $to_encode = array(
                                            'result' => "error",
                                            'error' => "Error deleting skill: " . mysqli_error($databaseConnection),
                                            'status' => -7
                                        );
                                    }
                                }
                            }

                        }

                        //
                    } else {
                        $to_encode = array(
                            'result' => "error",
                            'errorCode' => "Professional information update failed.",
                            'status' => -1,
                            'query' => $query
                        );
                    }
                } else {
                    $to_encode = array(
                        'result' => "fail",
                        'response' => 'professional information Updated fail.',
                        'status' => "0"
                    );

                }

            } else {
                $to_encode = array(
                    'result' => "fail",
                    'errorCode' => "User information Updated fail.",
                    'status' => 0
                );
            }






        } catch (Exception $e) {
            if ($e->getMessage() == "invalidField") {
                $to_encode = array(
                    'result' => $e->getMessage(),
                    'errorCode' => "field not valid",
                    'status' => "-99",
                );
            } else {
                $to_encode = array(
                    'result' => "error",
                    'errorCode' => "user Id does not exist.",
                    'status' => "-70",
                    'msg' => $e->getMessage(),
                );
            }
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Professional information update failed.",
            'status' => -1
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['getInterviewInfo'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $interviewId = $json['interviewId'];
        $values2 = array();
        $data = "select i.*  from `interview` i  where i.id='" . $interviewId . "'";
        $query = mysqli_query($databaseConnection, $data);
        $values = mysqli_fetch_all($query, MYSQLI_ASSOC);


        $tutorial = "select * from `interview_tutorial` where interviewId='" . $interviewId . "' and isActive = 'Y'";
        $tutorialQuery = mysqli_query($databaseConnection, $tutorial);
        if (mysqli_num_rows($query) >= 1) {
            $tutorialValues = mysqli_fetch_all($tutorialQuery, MYSQLI_ASSOC);
            $values[0]['tutorialLink'] = $tutorialValues;
        } else {
            $values[0]['tutorialLink'] = null;
        }

        $data2 = "select q.* from questions q inner join interview_questions_transection iqt on iqt.questionId = q.id inner join interview i on i.id = iqt.interviewId where iqt.interviewId = '" . $interviewId . "' and q.isActive = 'Y' and q.deleted_at is null and iqt.deleted_at is null order by iqt.sequence";
        $query2 = mysqli_query($databaseConnection, $data2);
        //$values2 = mysqli_fetch_all($query2, MYSQLI_ASSOC);
        while ($row = mysqli_fetch_assoc($query2)) {
            $row['questionHtml'] = nl2br($row['questionText']);
            if ($row['source'] != null) {
                $aspCompaniesQuery = mysqli_query($databaseConnection, "SELECT q.source, group_concat(ac.name SEPARATOR ',') AS questionSource FROM questions q, aspiration_company ac WHERE FIND_IN_SET(ac.id, q.source) and q.id = '" . $row['id'] . "'");
                $aspCompaniesResult = mysqli_fetch_array($aspCompaniesQuery, MYSQLI_ASSOC);
                $row['questionSource'] = $aspCompaniesResult['questionSource'];
            }
            array_push($values2, $row);
        }
        $to_encode = $values;
        array_push($to_encode, $values2);
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error whire retrieving interview information."
        );
    }

    echo json_encode($to_encode);
}
elseif (isset($_GET['getCompanyInterviewInfo'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $companyId = $json['companyId'];
        $sectorId = $json['sectorId'];
        $userId = $json['userId'];
        $preInterviewId = $json['preInterviewId'];
        $values2 = array();


        $analytics_sql = "SELECT
            (SELECT COUNT(DISTINCT emailId)
            FROM interviewSchedule
            WHERE preInterviewId = ?) AS total_applicants,
            (SELECT COUNT(DISTINCT isc.emailId)
            FROM interviewSchedule isc
            JOIN feedback_request fr ON fr.interviewId = isc.interviewId
            WHERE fr.review_status = 2
                AND isc.preInterviewId = ?) AS screened_via_ai,
            (SELECT GROUP_CONCAT(
                        CONCAT(u.firstName, ' (', COALESCE(ROUND(sub.dk_score * 10, 0), 0), '%)')
                        ORDER BY sub.dk_score DESC
                        SEPARATOR ', '
            )
            FROM (
                SELECT isc.emailId, fr.dk_score
                FROM interviewSchedule isc
                JOIN feedback_request fr ON fr.interviewId = isc.interviewId
                WHERE isc.candidateStatus NOT IN ('Interview Scheduled', 'Profile Match', '')
                AND isc.preInterviewId = ?
                LIMIT 3
            ) AS sub
            LEFT JOIN users u ON u.emailId = sub.emailId
            WHERE sub.dk_score IS NOT NULL
            ORDER BY sub.dk_score DESC
            LIMIT 1
            ) AS top_shortlisted
            ";

        $stmt = mysqli_prepare($databaseConnection, $analytics_sql);
        mysqli_stmt_bind_param($stmt, "iii", $preInterviewId, $preInterviewId, $preInterviewId);
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt);
        $analytics_data = mysqli_fetch_assoc($result);



        $data = "SELECT
            ac.id,
            cd.jobCategory,
            cd.interviewExpireDate AS expireDate,
            MAX(
                CASE
                    WHEN cd.interviewName IS NOT NULL THEN cd.interviewName
                    WHEN cd.interviewName IS NULL THEN CONCAT(
                        ac.name,
                        CASE
                            WHEN cd.company_address IS NOT NULL THEN CONCAT(', ', cd.company_address, ' ')
                            ELSE ''
                        END
                    )
                END
            ) AS `name`,
             ac.name as companyName,
            CASE WHEN cd.company_url IS NOT NULL THEN cd.company_url ELSE '' END AS `url`,
            CASE WHEN cd.targetAudience IS NOT NULL THEN cd.targetAudience ELSE 'All Stream' END AS targetAudience,
            CASE WHEN cd.duration IS NOT NULL THEN cd.duration ELSE '25-30 min' END AS duration,
            CASE WHEN cd.categoryType IS NOT NULL THEN cd.categoryType ELSE 9 END AS categoryType,
            CASE WHEN cd.interviewLevel IS NOT NULL THEN cd.interviewLevel ELSE 'Medium' END AS interviewLevel,
            CASE WHEN cd.assessmentParameter IS NOT NULL THEN cd.assessmentParameter ELSE 'Communication Skill, Behavioural Skill, P.S Skill, Coding Skill (if Applicable)' END AS assessmentParameter,
            cd.jobType,
            cd.currentCompany,
            cd.currentProcess,
            cd.processType,
            cd.clientType,
            cd.workExperience,
            cd.currentSalary,
            cd.expectedSalary,
            cd.noticePeriod,
            cd.processPreference,
            cd.shift,
            cd.workLocationPreference,
            cd.timeToCall,
            cd.declaration,
            cd.preferedJobType,
            cd.scoreAcceptedBy,
            cd.showScoreAcceptedBy,
            cd.JDsection,
            cd.showJDsection,
            cd.interviewStartDate,
            cd.postedBy,
            cd.logoName,
            logoText,
            cd.description,
            cd.currentLocation,
            cd.PreferredWorkLocation,
            cd.Language,
            cd.skills,
            cd.certifications,
            cd.avgTenure,
            cd.resume,
            cd.joiningTimeline,
            cd.rolesAndResponsibilities,
            cd.iStrength,
            cd.iClientInterviewProcess,
            cd.iVariablePay,
            cd.iWorkingDays,
            cd.iRelocation,
            cd.iHeadcount,
            cd.iContractTenure,
            cd.iEmploymentType,
            cd.salaryRange,
            cd.JobWorkExperience,
            cd.JobMode,
            DATE_FORMAT(cd.resultDate, '%d %M %Y') AS resultDate,
            cd.judgingCriteria,
            cd.prizeList,
            cd.interviewType,
            cd.rules,
            cd.pendingInterviews,
            cd.outstationFlag,
            cd.VemploymentType,
            cd.VworkingDays,
            cd.vcdJobShift,
            cd.vcdJobMode,
            cd.vcdjobLocation,
            cd.Vresume,
            cd.vcdJobNoticePeriod,
            cd.VsalaryRange,
            cd.VworkExperienceRange,
            cd.VcurrentLocation,
            cd.VcurrentCompany,
            cd.VexpectedSalary,
            cd.VcompanySalaryRange,
            cd.ultraMandatorySkill,
            cd.requiredSkills,
            cd.publish,
            cd.serviceType,
            cd.employmentType,
            cd.bondAgreementRequired,
            cd.practiceType,
            cd.YOE,
            cd.prbCount,
            u.placementSupport,
            CONCAT(DATE_FORMAT(cd.interviewStartDate, '%d %M %Y'), ' - ', DATE_FORMAT(cd.interviewExpireDate, '%d %M %Y')) AS timeline,
            (SELECT COUNT(DISTINCT fr.candidateId) AS totalParticipants FROM feedback_request fr INNER JOIN interview i ON i.id = fr.interviewId WHERE i.preInterviewId = cd.id) AS 'totalParticipates',
            CASE WHEN st.preInterviewId IS NULL AND cd.jobCategory IN ('interview') THEN 'dummy' ELSE 'real' END AS intCat,
            AdvancedProfileMatch,
            CandidateDeclaration
        FROM preInterview cd
        LEFT JOIN aspiration_company ac ON ac.id = cd.company_id
        LEFT JOIN scps_transaction st ON st.preInterviewId = cd.id
        LEFT JOIN preInterview_corporate map ON map.preInterviewid = cd.id
        LEFT JOIN users u ON u.id = map.userId
        WHERE cd.id = " . $preInterviewId . "
        GROUP BY
            ac.id,
            cd.jobCategory,
            cd.interviewExpireDate,
            cd.jobType,
            cd.currentCompany,
            cd.currentProcess,
            cd.processType,
            cd.clientType,
            cd.workExperience,
            cd.currentSalary,
            cd.expectedSalary,
            cd.noticePeriod,
            cd.processPreference,
            cd.shift,
            cd.workLocationPreference,
            cd.timeToCall,
            cd.declaration,
            cd.preferedJobType,
            cd.scoreAcceptedBy,
            cd.showScoreAcceptedBy,
            cd.JDsection,
            cd.showJDsection,
            cd.interviewStartDate,
            cd.postedBy,
            cd.logoName,
            logoText,
            cd.description,
            cd.currentLocation,
            cd.PreferredWorkLocation,
            cd.Language,
            cd.skills,
            cd.certifications,
            cd.avgTenure,
            cd.resume,
            cd.joiningTimeline,
            cd.rolesAndResponsibilities,
            cd.iStrength,
            cd.iClientInterviewProcess,
            cd.iVariablePay,
            cd.iWorkingDays,
            cd.iRelocation,
            cd.iHeadcount,
            cd.iContractTenure,
            cd.iEmploymentType,
            cd.salaryRange,
            cd.JobWorkExperience,
            cd.JobMode,
            cd.resultDate,
            cd.judgingCriteria,
            cd.prizeList,
            cd.interviewType,
            cd.rules,
            cd.pendingInterviews,
            cd.outstationFlag,
            timeline,
            AdvancedProfileMatch,
            CandidateDeclaration,
            cd.publish,
            cd.serviceType
    ";
        // cleanup - expert details not required on job landinga page
        // $experts_id=mysqli_query($databaseConnection,"select id,expertPanelId,interviewType from preInterview where id=".$preInterviewId."");

        // $expertIdResult=mysqli_fetch_assoc($experts_id);

        // if($expertIdResult['interviewType']=='competition' && $expertIdResult['expertPanelId']!=null){

        //     $queryForExpertPanel=mysqli_query($databaseConnection,"select id as expertId,name as expertName,oraganisation,experience,qualification,null as imageUrl,companiesWorked from panel where id in(".$expertIdResult['expertPanelId'].") and deleted_at is null");

        // }else{

        //     $queryForExpertPanel=mysqli_query($databaseConnection,"select id as expertId,name as expertName,oraganisation,experience,qualification,null as imageUrl,companiesWorked from panel where id between 1 and 106 and deleted_at is null order by rand() limit 5");
        // }
        // $experts = mysqli_fetch_all($queryForExpertPanel, MYSQLI_ASSOC);

        $query = mysqli_query($databaseConnection, $data);
        $values = mysqli_fetch_all($query, MYSQLI_ASSOC);
        $role = "SELECT st.position,rr.name FROM `scps_transaction` st INNER JOIN relavant_role rr ON st.position = rr.id WHERE st.preInterviewId = " . $preInterviewId . " AND st.sector = " . $sectorId . " GROUP BY st.position;";
        // echo $role;
        $roleQuery = mysqli_query($databaseConnection, $role);
        $domainQuery = "SELECT pi.roleId as id, rr.name 
                FROM preInterview pi 
                INNER JOIN relavant_role rr ON pi.roleId = rr.id 
                WHERE pi.id = " . $preInterviewId;
        $domainResult = mysqli_query($databaseConnection, $domainQuery);
        if (mysqli_num_rows($query) >= 1) {
            $roleValues = mysqli_fetch_all($roleQuery, MYSQLI_ASSOC);
            $values[0]['role'] = $roleValues;
            if ($domainResult && mysqli_num_rows($domainResult) > 0) {
                $domainData = mysqli_fetch_assoc($domainResult);
                $values[0]['domain'] = $domainData;
            } else {
                $values[0]['domain'] = null;
            }

            // get required skills names from ids
            // $stmt = $databaseConnection->prepare("SELECT requiredSkills FROM preInterview WHERE id = ?");
            $stmt = $databaseConnection->prepare("SELECT ultraMandatorySkill FROM preInterview WHERE id = ?");
            $stmt->bind_param("i", $preInterviewId);
            $stmt->execute();
            $stmt->bind_result($requiredSkills);
            $stmt->fetch();
            $stmt->close();

            // Check if requiredSkills is NULL or empty
            if (empty($requiredSkills)) {
                $values[0]['requiredSkillsName'] = NULL;
            } else {
                // Process the IDs
                $skillsArray = explode(',', $requiredSkills);
                $skillsArray = array_map('intval', $skillsArray);
                $skillsList = implode(',', $skillsArray);

                $query = "SELECT GROUP_CONCAT(favourite_subject SEPARATOR ', ') AS requiredSkillsName 
                          FROM favourite_subject 
                          WHERE id IN ($skillsList)";
                $result = $databaseConnection->query($query);
                $skillsNames = $result->fetch_assoc();

                $values[0]['requiredSkillsName'] = $skillsNames['requiredSkillsName'] ?? NULL;
            }

            // // Check if requiredSkills is NULL or empty
            // if (empty($requiredSkills)) {
            //     $values[0]['requiredSkillsName'] = NULL; 
            // } else {
            //     // Process the IDs
            //     $skillsArray = explode(',', $requiredSkills);
            //     $skillsArray = array_map('intval', $skillsArray); 
            //     $skillsList = implode(',', $skillsArray);

            //     $query = "SELECT favourite_subject as name, id
            //                 FROM favourite_subject 
            //                 WHERE id IN ($skillsList)";
            //     $result = $databaseConnection->query($query);
            //     $skillsNames = $result->fetch_assoc();

            //     $values[0]['requiredSkillsArray'] = $skillsNames ?? NULL;
            // }

            // Check if requiredSkills is NULL or empty
            if (empty($requiredSkills)) {
                $values[0]['requiredSkillsArray'] = [];
            } else {
                // Process the IDs
                $skillsArray = explode(',', $requiredSkills);
                $skillsArray = array_map('intval', $skillsArray);
                $skillsList = implode(',', $skillsArray);

                // Query to fetch the skill names and IDs
                $query = "SELECT id, favourite_subject as name
                            FROM favourite_subject 
                            WHERE id IN ($skillsList)";
                $result = $databaseConnection->query($query);

                // Initialize an array to store the skills
                $skillsArray = [];

                if ($result && $result->num_rows > 0) {
                    // Fetch all rows as an array
                    while ($row = $result->fetch_assoc()) {
                        $skillsArray[] = $row;
                    }
                }

                // Assign the array to requiredSkillsArray
                $values[0]['requiredSkillsArray'] = $skillsArray;
            }


            $now = new DateTime();
            if ($values[0]['expireDate'] != NULL) {
                if ($values[0]['expireDate'] >= ($now->format('Y-m-d H:i:s'))) {
                    $values[0]['interview_allow'] = 1;
                } else {
                    if ($userId != '') {
                        $sql = mysqli_query($databaseConnection, "select cp.* from candidate_preInterview cp inner join preInterview cop on cop.id=cp.preInterviewId where cp.candidateId=" . $userId . " and cop.company_id='" . $values[0]['id'] . "' and cp.interviewExpireDate>=now()");
                        if (mysqli_num_rows($sql) >= 1) {
                            $values[0]['interview_allow'] = 1;
                        } else {
                            $values[0]['interview_allow'] = 0;
                        }
                    } else {
                        $values[0]['interview_allow'] = 0;
                    }
                }
            } else {
                $values[0]['interview_allow'] = 1;
            }

        } else {
            $values[0]['role'] = null;
        }



        $filter9 = "select * from profilePreferences where preInterviewId = " . $preInterviewId . " ";
        $filter9Result = mysqli_query($databaseConnection, $filter9);

        $values['profilePrefFields'] = mysqli_fetch_all($filter9Result, MYSQLI_ASSOC);

        $interviewStructure_sql = "SELECT section, GROUP_CONCAT(distinct(subject)) AS subjects,clusterLevel,position,GROUP_CONCAT(distinct(topics)) AS topics,weightage FROM (SELECT scps.subject,isc.sectionId,CASE WHEN scps.dropdown = 1 AND scps.subjectType = 'technical' THEN '3' WHEN scps.dropdown = 2 AND scps.subjectType = 'technical' THEN '4' WHEN scps.dropdown = 1 AND scps.subjectType = 'coding' THEN '5' END AS section,case when isc.clusterLevel='Basic,Average,Advanced' then 'Basic' when isc.clusterLevel in('Average,Basic,Advanced','Average,Advanced,Basic') then 'Average' when isc.clusterLevel='Advanced,Average,Basic' then 'Advanced' end as clusterLevel,scps.position,scps.topics,scps.weightage
      FROM scps_transaction scps inner join interviewStructure isc ON isc.preInterviewId = scps.preInterviewId WHERE scps.preInterviewId = '" . $json['preInterviewId'] . "') AS subquery
    GROUP BY section";

        $interviewStructure_query = mysqli_query($databaseConnection, $interviewStructure_sql);

        $values['interviewStructure'] = mysqli_fetch_all($interviewStructure_query, MYSQLI_ASSOC);



        $commaSepSubjects_sql = "SELECT GROUP_CONCAT(fs.favourite_subject ORDER BY fs.favourite_subject ASC SEPARATOR ', ') AS favourite_subjects
    FROM scps_transaction scps
    LEFT JOIN favourite_subject fs ON fs.id = scps.subject
    WHERE scps.preInterviewId = " . $json['preInterviewId'];

        $commaSepSubjects_query = mysqli_query($databaseConnection, $commaSepSubjects_sql);
        $commaSepSubjects_result = mysqli_fetch_assoc($commaSepSubjects_query);
        $values[0]['commaSepSubjects'] = $commaSepSubjects_result['favourite_subjects'];

        $values['analyticsData'] = $analytics_data;
        $to_encode = $values;
        array_push($to_encode);

    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error whire retrieving interview information."
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['saveProfileMatchDetails'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json) && is_array($json)) {
        $preInterviewId = isset($json['preInterviewId']) ? (int) $json['preInterviewId'] : 0;
        $userId = isset($json['userId']) ? (int) $json['userId'] : 0;
        $currentSalaryInput = isset($json['currentSalary']) ? trim((string) $json['currentSalary']) : '';
        $workExperienceInput = isset($json['workExperience']) ? trim((string) $json['workExperience']) : '';

        if ($preInterviewId <= 0 || $userId <= 0) {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "Invalid preInterviewId or userId"
            );
        } else {
            $sqlValue = function ($value) use ($databaseConnection) {
                if ($value === null || $value === '') {
                    return "NULL";
                }
                return "'" . mysqli_real_escape_string($databaseConnection, (string) $value) . "'";
            };

            $currentSalary = $currentSalaryInput === '' ? null : $currentSalaryInput;
            $workExperience = $workExperienceInput === '' ? null : $workExperienceInput;

            $userQuery = "SELECT firstName, emailId, mobileNumber FROM users WHERE id = " . $userId . " LIMIT 1";
            $userResult = mysqli_query($databaseConnection, $userQuery);

            if (!$userResult || mysqli_num_rows($userResult) === 0) {
                $to_encode = array(
                    'status' => 0,
                    'result' => "error",
                    'errorCode' => "User not found"
                );
            } else {
                $userDetails = mysqli_fetch_assoc($userResult);
                $candidateName = isset($userDetails['firstName']) ? $userDetails['firstName'] : null;
                $emailId = isset($userDetails['emailId']) ? $userDetails['emailId'] : null;
                $mobileNumber = isset($userDetails['mobileNumber']) ? $userDetails['mobileNumber'] : null;

                if ($emailId === null || $emailId === '') {
                    $to_encode = array(
                        'status' => 0,
                        'result' => "error",
                        'errorCode' => "Candidate email not found"
                    );
                } else {
                    $professionalDetailsQuery = mysqli_query(
                        $databaseConnection,
                        "SELECT candidateId FROM professionaldetails WHERE candidateId = '" . $userId . "'"
                    );

                    if (!$professionalDetailsQuery) {
                        $to_encode = array(
                            'status' => 0,
                            'result' => "error",
                            'errorCode' => "Error executing query: " . mysqli_error($databaseConnection)
                        );
                    } elseif (mysqli_num_rows($professionalDetailsQuery) === 0) {
                        $to_encode = array(
                            'status' => 0,
                            'result' => "error",
                            'errorCode' => "No professional details found for user with ID " . $userId
                        );
                    } else {
                        $companyId = null;
                        $sectorId = null;
                        $serviceType = isset($json['serviceType']) ? strtoupper(trim((string) $json['serviceType'])) : null;
                        $screeningQuestionsFlag = 'N';
                        $validatedScreeningAnswers = array();
                        $preInterviewQuery = mysqli_query(
                            $databaseConnection,
                            "SELECT company_id, sectorId, serviceType, screeningQuestions FROM preInterview WHERE id = " . $preInterviewId . " LIMIT 1"
                        );
                        if ($preInterviewQuery && mysqli_num_rows($preInterviewQuery) > 0) {
                            $preInterviewDetails = mysqli_fetch_assoc($preInterviewQuery);
                            $companyId = isset($preInterviewDetails['company_id']) ? $preInterviewDetails['company_id'] : null;
                            $sectorId = isset($preInterviewDetails['sectorId']) ? $preInterviewDetails['sectorId'] : null;
                            $screeningQuestionsFlag = isset($preInterviewDetails['screeningQuestions']) && $preInterviewDetails['screeningQuestions'] == 'Y' ? 'Y' : 'N';
                            if ($serviceType === null || $serviceType === '') {
                                $serviceType = isset($preInterviewDetails['serviceType']) ? strtoupper(trim((string) $preInterviewDetails['serviceType'])) : null;
                            }
                        }

                        if ($screeningQuestionsFlag == 'Y') {
                            $screeningQuestionsResult = mysqli_query(
                                $databaseConnection,
                                "SELECT id, questionText, questionType, optionsJson FROM jobScreeningQuestions WHERE preInterviewId = " . $preInterviewId . " AND (isActive IS NULL OR isActive = 'Y') ORDER BY sortOrder ASC, id ASC"
                            );
                            $activeScreeningQuestions = array();
                            if ($screeningQuestionsResult) {
                                $activeScreeningQuestions = mysqli_fetch_all($screeningQuestionsResult, MYSQLI_ASSOC);
                            }

                            $screeningAnswersInput = isset($json['screeningAnswers']) && is_array($json['screeningAnswers']) ? $json['screeningAnswers'] : array();
                            $screeningAnswersByQuestion = array();
                            foreach ($screeningAnswersInput as $screeningAnswerInput) {
                                if (!is_array($screeningAnswerInput)) {
                                    continue;
                                }
                                $answerQuestionId = 0;
                                if (isset($screeningAnswerInput['scrnQuestionId'])) {
                                    $answerQuestionId = (int) $screeningAnswerInput['scrnQuestionId'];
                                } else if (isset($screeningAnswerInput['questionId'])) {
                                    $answerQuestionId = (int) $screeningAnswerInput['questionId'];
                                } else if (isset($screeningAnswerInput['id'])) {
                                    $answerQuestionId = (int) $screeningAnswerInput['id'];
                                }

                                if ($answerQuestionId <= 0) {
                                    continue;
                                }

                                if (isset($screeningAnswerInput['answerText'])) {
                                    $screeningAnswersByQuestion[$answerQuestionId] = trim((string) $screeningAnswerInput['answerText']);
                                } else if (isset($screeningAnswerInput['answer'])) {
                                    $screeningAnswersByQuestion[$answerQuestionId] = trim((string) $screeningAnswerInput['answer']);
                                } else if (isset($screeningAnswerInput['value'])) {
                                    $screeningAnswersByQuestion[$answerQuestionId] = trim((string) $screeningAnswerInput['value']);
                                }
                            }

                            $missingScreeningQuestionIds = array();
                            $invalidScreeningAnswers = array();
                            foreach ($activeScreeningQuestions as $screeningQuestion) {
                                $screeningQuestionId = (int) $screeningQuestion['id'];
                                $questionType = strtoupper(trim((string) $screeningQuestion['questionType']));
                                $answerText = isset($screeningAnswersByQuestion[$screeningQuestionId]) ? trim((string) $screeningAnswersByQuestion[$screeningQuestionId]) : '';

                                if ($answerText === '') {
                                    $missingScreeningQuestionIds[] = $screeningQuestionId;
                                    continue;
                                }

                                if ($questionType == 'NUMBER') {
                                    if (!is_numeric($answerText) || (float) $answerText < 0) {
                                        $invalidScreeningAnswers[] = array('scrnQuestionId' => $screeningQuestionId, 'message' => 'Please enter a valid number');
                                        continue;
                                    }
                                } else if ($questionType == 'YES_NO') {
                                    $yesNoValue = strtolower($answerText);
                                    if (in_array($yesNoValue, array('y', 'yes', 'true', '1'))) {
                                        $answerText = 'Y';
                                    } else if (in_array($yesNoValue, array('n', 'no', 'false', '0'))) {
                                        $answerText = 'N';
                                    } else {
                                        $invalidScreeningAnswers[] = array('scrnQuestionId' => $screeningQuestionId, 'message' => 'Please select Yes or No');
                                        continue;
                                    }
                                } else if ($questionType == 'SINGLE_SELECT') {
                                    $options = array();
                                    $decodedOptions = json_decode((string) $screeningQuestion['optionsJson'], true);
                                    if (is_array($decodedOptions)) {
                                        $options = $decodedOptions;
                                    } else if (!empty($screeningQuestion['optionsJson'])) {
                                        $options = explode(',', (string) $screeningQuestion['optionsJson']);
                                    }

                                    $matchedOption = null;
                                    foreach ($options as $option) {
                                        $cleanOption = trim((string) $option);
                                        if ($cleanOption !== '' && strtolower($cleanOption) == strtolower($answerText)) {
                                            $matchedOption = $cleanOption;
                                            break;
                                        }
                                    }

                                    if ($matchedOption === null) {
                                        $invalidScreeningAnswers[] = array('scrnQuestionId' => $screeningQuestionId, 'message' => 'Please select a valid option');
                                        continue;
                                    }
                                    $answerText = $matchedOption;
                                }

                                $validatedScreeningAnswers[] = array(
                                    'scrnQuestionId' => $screeningQuestionId,
                                    'answerText' => $answerText
                                );
                            }

                            if (count($missingScreeningQuestionIds) > 0 || count($invalidScreeningAnswers) > 0) {
                                $to_encode = array(
                                    'status' => 0,
                                    'result' => "error",
                                    'errorCode' => "SCREENING_ANSWERS_REQUIRED",
                                    'message' => "Please answer all screening questions",
                                    'missingQuestionIds' => $missingScreeningQuestionIds,
                                    'invalidAnswers' => $invalidScreeningAnswers
                                );
                                echo json_encode($to_encode);
                                exit();
                            }
                        }

                        $professionalDetailsUpdate = "UPDATE professionaldetails SET "
                            . "workExperience = " . $sqlValue($workExperience) . ", "
                            . "salary = " . $sqlValue($currentSalary)
                            . " WHERE candidateId = '" . $userId . "'";

                        $professionalDetailsUpdateResult = mysqli_query($databaseConnection, $professionalDetailsUpdate);

                        if (!$professionalDetailsUpdateResult) {
                            $to_encode = array(
                                'status' => 0,
                                'result' => "error",
                                'errorCode' => "Error updating professionaldetails: " . mysqli_error($databaseConnection)
                            );
                        } else {
                            $scheduleAction = "none";
                            $scheduleQuery = "SELECT * FROM interviewSchedule WHERE emailId = " . $sqlValue($emailId) . " AND preInterviewId = " . $preInterviewId . " ORDER BY id DESC";
                            $scheduleResult = mysqli_query($databaseConnection, $scheduleQuery);

                            if (!$scheduleResult) {
                                $to_encode = array(
                                    'status' => 0,
                                    'result' => "error",
                                    'errorCode' => "Error checking interviewSchedule: " . mysqli_error($databaseConnection)
                                );
                            } else {
                                if (mysqli_num_rows($scheduleResult) > 0) {
                                    $scheduleRow = mysqli_fetch_assoc($scheduleResult);
                                    if (empty($scheduleRow['interviewId'])) {
                                        $scheduleUpdateQuery = "UPDATE interviewSchedule SET candidate_id = '" . $userId . "', ";
                                        if ($companyId !== null && $companyId !== '') {
                                            $scheduleUpdateQuery .= "company_id = " . $sqlValue($companyId) . ", ";
                                        }
                                        if ($sectorId !== null && $sectorId !== '') {
                                            $scheduleUpdateQuery .= "sectorId = " . $sqlValue($sectorId) . ", ";
                                        }
                                        $scheduleUpdateQuery .= "workExperience = " . $sqlValue($workExperience) . ", ";
                                        $scheduleUpdateQuery .= "currentSalary = " . $sqlValue($currentSalary) . " ";
                                        $scheduleUpdateQuery .= "WHERE emailId = " . $sqlValue($emailId) . " AND preInterviewId = " . $preInterviewId;

                                        $updateScheduleResult = mysqli_query($databaseConnection, $scheduleUpdateQuery);
                                        if (!$updateScheduleResult) {
                                            $to_encode = array(
                                                'status' => 0,
                                                'result' => "error",
                                                'errorCode' => "Error updating interviewSchedule: " . mysqli_error($databaseConnection)
                                            );
                                        } else {
                                            $scheduleAction = "update";
                                            $to_encode = array(
                                                'status' => 1,
                                                'result' => "success",
                                                'action' => $scheduleAction
                                            );
                                        }
                                    } else {
                                        $apmStatus = isset($scheduleRow['apmStatus']) && $scheduleRow['apmStatus'] !== '' ? $scheduleRow['apmStatus'] : null;
                                        $apm = isset($scheduleRow['apm']) && $scheduleRow['apm'] !== '' ? $scheduleRow['apm'] : null;
                                        $promotionSource = isset($scheduleRow['promotionSource']) && $scheduleRow['promotionSource'] !== '' ? $scheduleRow['promotionSource'] : null;

                                        $scheduleInsertQuery = "INSERT INTO interviewSchedule (`company_id`, `candidate_id`, `candidateName`, `emailId`, `mobileNumber`, `sectorId`, `workExperience`, `currentSalary`, `preInterviewId`, `apmStatus`, `apm`, `promotionSource`) VALUES ("
                                            . $sqlValue($companyId) . ", "
                                            . $sqlValue($userId) . ", "
                                            . $sqlValue($candidateName) . ", "
                                            . $sqlValue($emailId) . ", "
                                            . $sqlValue($mobileNumber) . ", "
                                            . $sqlValue($sectorId) . ", "
                                            . $sqlValue($workExperience) . ", "
                                            . $sqlValue($currentSalary) . ", "
                                            . $sqlValue($preInterviewId) . ", "
                                            . $sqlValue($apmStatus) . ", "
                                            . $sqlValue($apm) . ", "
                                            . $sqlValue($promotionSource)
                                            . ")";

                                        $insertScheduleResult = mysqli_query($databaseConnection, $scheduleInsertQuery);
                                        if (!$insertScheduleResult) {
                                            $to_encode = array(
                                                'status' => 0,
                                                'result' => "error",
                                                'errorCode' => "Error inserting interviewSchedule: " . mysqli_error($databaseConnection)
                                            );
                                        } else {
                                            $scheduleAction = "insert";
                                            $to_encode = array(
                                                'status' => 1,
                                                'result' => "success",
                                                'action' => $scheduleAction
                                            );
                                        }
                                    }
                                } else {
                                    $scheduleInsertQuery = "INSERT INTO interviewSchedule (`company_id`, `candidate_id`, `candidateName`, `emailId`, `mobileNumber`, `sectorId`, `workExperience`, `currentSalary`, `preInterviewId`) VALUES ("
                                        . $sqlValue($companyId) . ", "
                                        . $sqlValue($userId) . ", "
                                        . $sqlValue($candidateName) . ", "
                                        . $sqlValue($emailId) . ", "
                                        . $sqlValue($mobileNumber) . ", "
                                        . $sqlValue($sectorId) . ", "
                                        . $sqlValue($workExperience) . ", "
                                        . $sqlValue($currentSalary) . ", "
                                        . $sqlValue($preInterviewId)
                                        . ")";

                                    $insertScheduleResult = mysqli_query($databaseConnection, $scheduleInsertQuery);
                                    if (!$insertScheduleResult) {
                                        $to_encode = array(
                                            'status' => 0,
                                            'result' => "error",
                                            'errorCode' => "Error inserting interviewSchedule: " . mysqli_error($databaseConnection)
                                        );
                                    } else {
                                        $scheduleAction = "insert";
                                        $to_encode = array(
                                            'status' => 1,
                                            'result' => "success",
                                            'action' => $scheduleAction
                                        );
                                    }
                                }

                                if (
                                    isset($to_encode['status']) &&
                                    (int) $to_encode['status'] === 1 &&
                                    $serviceType === 'IAS'
                                ) {
                                    $iasUpdateQuery = "UPDATE interviewSchedule SET "
                                        . "apmStatus = 4, "
                                        . "candidateStatus = 'Interview Scheduled', "
                                        . "submissionFlag = 'Y' "
                                        . "WHERE emailId = " . $sqlValue($emailId)
                                        . " AND preInterviewId = " . $preInterviewId;
                                    $iasUpdateResult = mysqli_query($databaseConnection, $iasUpdateQuery);

                                    if (!$iasUpdateResult) {
                                        $to_encode = array(
                                            'status' => 0,
                                            'result' => "error",
                                            'errorCode' => "Error updating IAS interview schedule status: " . mysqli_error($databaseConnection)
                                        );
                                    } else {
                                        $resumeLeadSql = "UPDATE resume_apm SET leadStatus = 'Applied' WHERE emailId = "
                                            . $sqlValue($emailId)
                                            . " AND preInterviewId = " . $preInterviewId;
                                        mysqli_query($databaseConnection, $resumeLeadSql);
                                    }
                                }

                                if (
                                    isset($to_encode['status']) &&
                                    (int) $to_encode['status'] === 1 &&
                                    $screeningQuestionsFlag == 'Y' &&
                                    count($validatedScreeningAnswers) > 0
                                ) {
                                    foreach ($validatedScreeningAnswers as $validatedScreeningAnswer) {
                                        $screeningAnswerQuestionId = (int) $validatedScreeningAnswer['scrnQuestionId'];
                                        $screeningAnswerText = mysqli_real_escape_string($databaseConnection, (string) $validatedScreeningAnswer['answerText']);
                                        $screeningAnswerUpsert = "INSERT INTO jobScreeningAnswers (preInterviewId, scrnQuestionId, candidateId, answerText, createdAt, updatedAt) VALUES ("
                                            . $preInterviewId . ", "
                                            . $screeningAnswerQuestionId . ", "
                                            . $userId . ", "
                                            . "'" . $screeningAnswerText . "', "
                                            . "NOW(), NOW()) "
                                            . "ON DUPLICATE KEY UPDATE answerText = VALUES(answerText), updatedAt = NOW()";
                                        $screeningAnswerResult = mysqli_query($databaseConnection, $screeningAnswerUpsert);
                                        if (!$screeningAnswerResult) {
                                            $to_encode = array(
                                                'status' => 0,
                                                'result' => "error",
                                                'errorCode' => "Error saving screening answers: " . mysqli_error($databaseConnection)
                                            );
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    } else {
        $to_encode = array('status' => 0, 'result' => "error", 'errorCode' => "Invalid request format");
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getEmployabilityInterviewInfo'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $sectorId = $json['sectorId'];
        $values2 = array();

        // $data = "SELECT * ,'Freshers' as targetAudience,'25-30 min' as duration,9 as categoryType,'Medium' as interviewLevel,'Communication Skill, Behavioural Skill, P.S Skill, Coding Skill (if Applicable).' as assessmentParameter  FROM `sector` WHERE id = ".$sectorId."";

        //  Query last updated by Arun on 25 aug 22 for devOps engineer interview

        $data = "SELECT * ,CASE WHEN (id = 10) THEN 'Freshers & Experienced Candidates' ELSE CASE WHEN (id=11) THEN 'Any Graduate with 4 - 8 years of experience' ELSE 'Freshers' END END as targetAudience,CASE WHEN (id = 10) THEN '10-15 min' ELSE CASE WHEN (id=11) THEN '30 min' ELSE ' 25-30 min' END END as duration,9 as categoryType,'Medium' as interviewLevel,CASE WHEN (id = 10) THEN 'Communication & Confidence' ELSE CASE WHEN (id=11) THEN 'Communication Skill, Concept Knowledge, Problem Solving Skills' ELSE 'Communication Skill, Behavioural Skill, P.S Skill, Coding Skill (if Applicable).' END END as assessmentParameter  FROM sector WHERE id = " . $sectorId . "";
        $query = mysqli_query($databaseConnection, $data);
        $values = mysqli_fetch_all($query, MYSQLI_ASSOC);

        $role = "SELECT st.position,rr.name FROM `scps_transaction` st INNER JOIN relavant_role rr ON st.position = rr.id WHERE st.sector = " . $sectorId . " GROUP BY st.position;";
        $roleQuery = mysqli_query($databaseConnection, $role);
        if (mysqli_num_rows($roleQuery) >= 1) {
            $roleValues = mysqli_fetch_all($roleQuery, MYSQLI_ASSOC);
            $values[0]['role'] = $roleValues;
        } else {
            $values[0]['role'] = null;
        }
        $to_encode = $values;
        array_push($to_encode, $values2);
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error whire retrieving interview information."
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['getEmployabilityInterviewSubject'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $sectorId = $json['sectorId'];
        $positionId = $json['positionId'];

        // $data = "SELECT st.subject as id,fs.favourite_subject as favourite_subject,ist.noOfAnswer,ist.noOfSkip,COUNT( DISTINCT CASE WHEN q.deleted_at IS null AND q.isFollowUp IN ('Y','N') THEN q.id ELSE null END) as numberOfQues  FROM `scps_transaction` st INNER JOIN favourite_subject fs ON st.subject = fs.id LEFT JOIN fav_prog_skill fps ON fps.fav_prog_skill LIKE CONCAT('%',fs.favourite_subject,'%') INNER JOIN interviewStructure ist ON (ist.sectorId = st.sector AND (ist.companyId = st.company OR ist.companyId = 0) AND (ist.roleId = st.position OR ist.roleId = 0)) LEFT OUTER JOIN questions q ON q.subjectId = st.subject  WHERE fps.id IS null AND st.sector = ".$sectorId." AND st.position = ".$positionId."  GROUP BY st.subject HAVING numberOfQues >= (ist.noOfAnswer + ist.noOfSkip -1);";
        /* this query is updated  by Narayan for count those question who is ready to use 18 May 2022 */
        $data = "SELECT st.subject as id,st.dropdown as dropdown,fs.favourite_subject as favourite_subject,ist.noOfAnswer,ist.noOfSkip,COUNT( DISTINCT CASE WHEN q.deleted_at IS null AND q.isFollowUp IN ('Y','N')   AND q.questionType = 'Universal' THEN q.id ELSE null END) as numberOfQues  FROM `scps_transaction` st INNER JOIN favourite_subject fs ON st.subject = fs.id LEFT JOIN fav_prog_skill fps ON fps.fav_prog_skill LIKE CONCAT('%',fs.favourite_subject,'%') INNER JOIN interviewStructure ist ON (ist.sectorId = st.sector AND (ist.companyId = st.company OR ist.companyId = 0) AND (ist.roleId = st.position OR ist.roleId = 0)) LEFT OUTER JOIN questions q ON q.subjectId = st.subject  WHERE fps.id IS null AND st.sector = " . $sectorId . " AND st.position = " . $positionId . "  GROUP BY st.subject HAVING numberOfQues >= 4;";

        /*   echo $data;
         */
        $query = mysqli_query($databaseConnection, $data);

        if (mysqli_num_rows($query) > 0) {
            $companyList = mysqli_fetch_all($query, MYSQLI_ASSOC);
        } else {
            $companyList = [];
        }

        /* $ISTdata = "SELECT ist.id FROM interviewStructure ist WHERE ist.companyId = 0  AND ist.sectorId = ".$sectorId." AND ist.roleId = ".$positionId." AND ist.sectionId IN (3,4);";  */

        $ISTdata = "SELECT ist.id FROM interviewStructure ist WHERE ist.companyId = 0  AND ist.sectorId = " . $sectorId . " AND ist.roleId = " . $positionId . " AND ist.sectionId IN (3,4,8);";
        $ISTquery = mysqli_query($databaseConnection, $ISTdata);
        if (mysqli_num_rows($ISTquery) == 0) {
            $validationState = '0';
        } elseif (mysqli_num_rows($ISTquery) == 1) {
            $validationState = '1';
        } elseif (mysqli_num_rows($ISTquery) == 2) {
            $validationState = '2';
        } elseif (mysqli_num_rows($ISTquery) == 3) {
            $validationState = '3';
        }

        $dataprog = "SELECT st.subject as id,fs.favourite_subject as favourite_subject,ist.noOfAnswer,ist.noOfSkip,COUNT( DISTINCT CASE WHEN q.deleted_at IS null AND q.isFollowUp IN ('Y','N') AND q.questionType = 'Universal'  THEN q.id ELSE null END) as numberOfQues  FROM `scps_transaction` st INNER JOIN favourite_subject fs ON st.subject = fs.id LEFT JOIN fav_prog_skill fps ON fps.fav_prog_skill LIKE CONCAT('%',fs.favourite_subject,'%') INNER JOIN interviewStructure ist ON (ist.sectorId = st.sector AND (ist.companyId = st.company OR ist.companyId = 0) AND (ist.roleId = st.position OR ist.roleId = 0)) LEFT OUTER JOIN questions q ON q.subjectId = st.subject  WHERE fps.id IS NOT null AND st.sector = " . $sectorId . " AND st.position = " . $positionId . "  GROUP BY st.subject HAVING numberOfQues >= 4;";
        $queryprog = mysqli_query($databaseConnection, $dataprog);
        if (mysqli_num_rows($queryprog) > 0) {
            $progList = mysqli_fetch_all($queryprog, MYSQLI_ASSOC);
        } else {
            $progList = [];
        }

        $to_encode = array(
            'list' => $companyList,
            'progList' => $progList,
            'validationState' => $validationState,
            'status' => 1,
            'qry' => $data,
        );
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error whire retrieving interview information."
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['getCompanyInterviewSubject'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $companyId = $json['companyId'];
        $sectorId = $json['sectorId'];
        $roleId = $json['role'];

        /*    $ISTdata = "SELECT ist.id FROM interviewStructure ist WHERE ist.companyId = ".$json['companyId']."  AND ist.sectorId = ".$json['sectorId']." AND ist.roleId = ".$json['role']." AND ist.sectionId IN (3,4);";
         */
        //this query is modified by arun on 13 sep 2022 for two core sub drop down


        $ISTdata = "SELECT ist.id FROM interviewStructure ist WHERE ist.preInterviewId='" . $json['preInterviewId'] . "' AND ist.sectionId IN (3,4,8);";

        $ISTquery = mysqli_query($databaseConnection, $ISTdata);
        if (mysqli_num_rows($ISTquery) == 0) {
            $validationState = '0';
        } elseif (mysqli_num_rows($ISTquery) == 1) {
            $validationState = '1';
        } elseif (mysqli_num_rows($ISTquery) == 2) {
            $validationState = '2';
        } elseif (mysqli_num_rows($ISTquery) == 3) {
            $validationState = '3';
        }
        // $data = "SELECT st.subject as id,st.dropdown as dropdown,fs.favourite_subject as favourite_subject,ist.noOfAnswer,ist.noOfSkip,COUNT( DISTINCT CASE WHEN q.deleted_at IS null AND q.isFollowUp IN ('Y','N')  AND q.questionType = 'Universal' THEN q.id ELSE null END) as numberOfQues  FROM `scps_transaction` st INNER JOIN favourite_subject fs ON st.subject = fs.id LEFT JOIN fav_prog_skill fps ON fps.fav_prog_skill LIKE CONCAT('%',fs.favourite_subject,'%') INNER JOIN interviewStructure ist ON (ist.sectorId = st.sector AND (ist.companyId = st.company OR ist.companyId = 0) AND (ist.roleId = st.position OR ist.roleId = 0)) LEFT OUTER JOIN questions q ON q.subjectId = st.subject  WHERE fps.id IS null AND st.sector = ".$sectorId." AND st.company IN (".$companyId.") AND st.position = ".$roleId."  GROUP BY st.subject HAVING numberOfQues >= 4;";

        //new query updated by arun on 29 jun 2023 displaying subjects based on scps transaction (citizen ship)

        // $data = "SELECT st.subject as id,st.dropdown as dropdown,fs.favourite_subject as favourite_subject,ist.noOfAnswer,ist.noOfSkip,COUNT( DISTINCT CASE WHEN q.deleted_at IS null AND q.isFollowUp IN ('Y','N')  AND q.questionType = 'Universal' THEN q.id ELSE null END) as numberOfQues  FROM `scps_transaction` st INNER JOIN favourite_subject fs ON st.subject = fs.id INNER JOIN interviewStructure ist ON (ist.sectorId = st.sector AND (ist.companyId = st.company OR ist.companyId = 0) AND (ist.roleId = st.position OR ist.roleId = 0)) LEFT OUTER JOIN questions q ON q.subjectId = st.subject  WHERE fs.id IS not null AND st.sector = ".$sectorId." AND st.company IN (".$companyId.") AND st.position = ".$roleId." AND st.subjectType!='coding' GROUP BY st.subject HAVING numberOfQues >= 4;";

        $data = "SELECT st.subject as id,st.dropdown as dropdown,fs.favourite_subject as favourite_subject,ist.noOfAnswer,ist.noOfSkip,COUNT( DISTINCT CASE WHEN q.deleted_at IS null AND q.isFollowUp IN ('Y','N')  AND q.questionType = 'Universal' THEN q.id ELSE null END) as numberOfQues  FROM `scps_transaction` st INNER JOIN favourite_subject fs ON st.subject = fs.id INNER JOIN interviewStructure ist ON ist.preInterviewId=st.preInterviewId LEFT OUTER JOIN questions q ON q.subjectId = st.subject  WHERE fs.id IS not null AND st.preInterviewId='" . $json['preInterviewId'] . "' AND st.subjectType!='coding' GROUP BY st.subject HAVING numberOfQues >= 4";

        $query = mysqli_query($databaseConnection, $data);
        if (mysqli_num_rows($query) > 0) {
            $companyList = mysqli_fetch_all($query, MYSQLI_ASSOC);
        } else {
            $companyList = [];
        }

        /* this query is updated  by Narayan for count those question who is ready to use 18 May 2022 */
        // $dataprog = "SELECT st.subject as id,fs.favourite_subject as favourite_subject,ist.noOfAnswer,ist.noOfSkip,COUNT( DISTINCT CASE WHEN q.deleted_at IS null AND q.isFollowUp IN ('Y','N')   and q.questionType = 'Universal' THEN q.id ELSE null END) as numberOfQues  FROM `scps_transaction` st INNER JOIN favourite_subject fs ON st.subject = fs.id LEFT JOIN fav_prog_skill fps ON fps.fav_prog_skill LIKE CONCAT('%',fs.favourite_subject,'%') INNER JOIN interviewStructure ist ON (ist.sectorId = st.sector AND (ist.companyId = st.company OR ist.companyId = 0) AND (ist.roleId = st.position OR ist.roleId = 0)) LEFT OUTER JOIN questions q ON q.subjectId = st.subject  WHERE fps.id IS NOT null AND st.sector = ".$sectorId." AND st.company IN (".$companyId.") AND st.position = ".$roleId."  GROUP BY st.subject HAVING numberOfQues >= 5;";


        // $dataprog = "SELECT st.subject as id,fs.favourite_subject as favourite_subject,ist.noOfAnswer,ist.noOfSkip,COUNT( DISTINCT CASE WHEN q.deleted_at IS null AND q.isFollowUp IN ('Y','N')   and q.questionType = 'Universal' THEN q.id ELSE null END) as numberOfQues  FROM `scps_transaction` st INNER JOIN favourite_subject fs ON st.subject = fs.id INNER JOIN interviewStructure ist ON (ist.sectorId = st.sector AND (ist.companyId = st.company OR ist.companyId = 0) AND (ist.roleId = st.position OR ist.roleId = 0)) LEFT OUTER JOIN questions q ON q.subjectId = st.subject  WHERE fs.favourite_subject IS NOT null AND st.sector = ".$sectorId." AND st.company IN (".$companyId.") AND st.position = ".$roleId." AND st.subjectType='coding' GROUP BY st.subject HAVING numberOfQues >= 5;";

        $dataprog = "SELECT st.subject as id,fs.favourite_subject as favourite_subject,ist.noOfAnswer,ist.noOfSkip,COUNT( DISTINCT CASE WHEN q.deleted_at IS null AND q.isFollowUp IN ('Y','N')   and q.questionType = 'Universal' THEN q.id ELSE null END) as numberOfQues  FROM `scps_transaction` st INNER JOIN favourite_subject fs ON st.subject = fs.id INNER JOIN interviewStructure ist ON ist.preInterviewId=st.preInterviewId LEFT OUTER JOIN questions q ON q.subjectId = st.subject  WHERE fs.favourite_subject IS NOT null AND st.preInterviewId='" . $json['preInterviewId'] . "' AND st.subjectType='coding' GROUP BY st.subject HAVING numberOfQues >= 5";

        // $dataprog = "SELECT st.subject as id,fs.favourite_subject as favourite_subject FROM `scps_transaction` st INNER JOIN favourite_subject fs ON st.subject = fs.id LEFT JOIN fav_prog_skill fps ON fps.fav_prog_skill LIKE CONCAT('%',fs.favourite_subject,'%') WHERE fps.id IS NOT NULL AND st.sector = ".$sectorId." AND st.company IN (".$companyId.") AND st.position IN (". $roleId .") GROUP BY st.subject;";
        $queryprog = mysqli_query($databaseConnection, $dataprog);
        if (mysqli_num_rows($queryprog) > 0) {
            $progList = mysqli_fetch_all($queryprog, MYSQLI_ASSOC);
        } else {
            $progList = [];
        }

        $interviewSections = mysqli_query($databaseConnection, " Select ins.name as SectionName from interviewStructure  its inner join interviewSection ins on its.sectionId = ins.id  where its.preInterviewId='" . $json['preInterviewId'] . "' order by its.sectionSequence");

        $result = mysqli_fetch_all($interviewSections);
        $to_encode = array(
            'list' => $companyList,
            'progList' => $progList,
            'interviewSection' => $result,
            'validationState' => $validationState,
            'status' => 1,
            'qry' => $data,
        );
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error whire retrieving interview information."
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['getJobTopics'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $preInterviewId = $json['preInterviewId'];
        $userId = $json['userId'] ?? null;


        $topicSequence = array();
        $data = array();


        $sql = "Select * from scps_transaction where preInterviewId = '" . $preInterviewId . "' order by id ASC";
        // echo $sql;

        $query = mysqli_query($databaseConnection, $sql);


        if (mysqli_num_rows($query) > 0) {

            while ($topics = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
                $topicIds = $topics['topics'];
                $subject = $topics['subject'];

                $sql = "SELECT * FROM topic WHERE id IN (" . $topicIds . ")";
                // echo $sql;
                $innerQuery = mysqli_query($databaseConnection, $sql);

                if ($innerQuery) {
                    $result = mysqli_fetch_all($innerQuery, MYSQLI_ASSOC);

                    foreach ($result as &$topic) {
                        $topic['subject'] = $subject;
                    }

                    $data = array_merge($data, $result);

                } else {
                    $to_encode1 = array(
                        'data' => 0,
                        'status' => 1,
                    );
                }
            }
            // print_r($data);
            // exit();

            $to_encode1 = array(
                'data' => $data,
                'status' => 1,
            );

        } else {
            $to_encode1 = array(
                'data' => 0,
                'status' => 0,
            );
        }



        if ($userId) {
            $sql1 = "select iqt.id, iqt.interviewId, iqt.questionId , q.topic_id, iqt.attemptStatus from interview_questions_transection iqt inner join interview i on i.id=iqt.interviewId inner join feedback_request fr on fr.interviewId=i.id inner join questions q on iqt.questionId=q.id where fr.candidateId='" . $userId . "' and i.preInterviewId='" . $preInterviewId . "' and iqt.attemptStatus='Respond'";
            //echo $sql1;

            $query1 = mysqli_query($databaseConnection, $sql1);

            $query1Result = mysqli_fetch_all($query1, MYSQLI_ASSOC);
            $to_encode2 = array(
                'result' => $query1Result
            );

            $probAttemptedSql = "
                SELECT COUNT(DISTINCT mv.questionId) AS ProbAttempted
                FROM interview i
                INNER JOIN feedback_request fr ON fr.interviewId = i.id
                INNER JOIN mergedVideos mv ON mv.interviewId = fr.interviewId
                WHERE i.preInterviewId = '" . $preInterviewId . "'
                AND fr.candidateId = '" . $userId . "'
                AND fr.review_status = 2
                AND mv.candidateId = '" . $userId . "'
            ";
            
            $probAttemptedQuery = mysqli_query($databaseConnection, $probAttemptedSql);
            $probAttemptedResult = mysqli_fetch_assoc($probAttemptedQuery);
            $to_encode2['ProbAttempted'] = $probAttemptedResult ? $probAttemptedResult['ProbAttempted'] : 0;

        } else {
            $to_encode2 = array(
                'result' => []
            );
        }

        $to_encode = array_merge($to_encode1, $to_encode2);

        // if ($userId) {
        //     // best score and its subject for the preInterview
        //     $bestScoreSql = "
        //         SELECT s.subject, MAX(s.subjectScore) AS bestScore
        //         FROM subjectWiseScores s
        //         WHERE s.candidateId = '" . $userId . "'
        //         AND s.subject IN (
        //             SELECT subject FROM scps_transaction WHERE preInterviewId = '" . $preInterviewId . "'
        //         )
        //         GROUP BY s.subject
        //         ORDER BY bestScore DESC
        //         LIMIT 1
        //     ";
        //     $bestScoreQuery = mysqli_query($databaseConnection, $bestScoreSql);
        //     $bestScoreResult = mysqli_fetch_assoc($bestScoreQuery);

        //     $to_encode['bestScoreInfo'] = $bestScoreResult ? $bestScoreResult : [];
        // } else {
        //     $to_encode['bestScoreInfo'] = [];
        // }

    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getPracticeModule'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json) && isset($json['preInterviewId']) && $json['preInterviewId'] != '') {
        $preInterviewId = (int) $json['preInterviewId'];
        $subjectId = (isset($json['subjectId']) && $json['subjectId'] !== '') ? (int) $json['subjectId'] : 0;

        $scpsSql = "SELECT subject, topics FROM scps_transaction WHERE preInterviewId = " . $preInterviewId;
        if ($subjectId > 0) {
            $scpsSql .= " AND subject = " . $subjectId;
        }
        $scpsSql .= " ORDER BY id ASC";

        $scpsQuery = mysqli_query($databaseConnection, $scpsSql);

        $subjectTopicPairs = array();
        $topicIds = array();
        $subjectIds = array();

        if ($scpsQuery && mysqli_num_rows($scpsQuery) > 0) {
            while ($row = mysqli_fetch_array($scpsQuery, MYSQLI_ASSOC)) {
                $subject = (int) $row['subject'];
                $subjectIds[$subject] = $subject;
                $rowTopicIds = array_filter(array_map('trim', explode(',', (string) $row['topics'])));

                foreach ($rowTopicIds as $topicId) {
                    $topicId = (int) $topicId;
                    if ($topicId <= 0) {
                        continue;
                    }

                    $pairKey = $subject . '_' . $topicId;
                    if (!isset($subjectTopicPairs[$pairKey])) {
                        $subjectTopicPairs[$pairKey] = array(
                            'subject' => $subject,
                            'topic_id' => $topicId,
                        );
                        $topicIds[$topicId] = $topicId;
                    }
                }
            }
        }

        if (count($subjectTopicPairs) == 0) {
            $to_encode = array(
                'status' => 1,
                'data' => array(),
            );
        } else {
            $topicNameMap = array();
            $topicSql = "SELECT id, name FROM topic WHERE id IN (" . implode(',', $topicIds) . ")";
            $topicQuery = mysqli_query($databaseConnection, $topicSql);
            if ($topicQuery) {
                while ($topicRow = mysqli_fetch_array($topicQuery, MYSQLI_ASSOC)) {
                    $topicNameMap[(int) $topicRow['id']] = $topicRow['name'];
                }
            }

            $moduleMap = array();
            $moduleSql = "SELECT q.subjectId, q.topic_id,
                        COUNT(DISTINCT CASE
                            WHEN q.moduleName IS NOT NULL
                            AND TRIM(q.moduleName) <> ''
                            AND LOWER(TRIM(q.moduleName)) <> 'null'
                            THEN TRIM(q.moduleName)
                        END) as moduleCount,
                        GROUP_CONCAT(DISTINCT CASE
                            WHEN q.moduleName IS NOT NULL
                            AND TRIM(q.moduleName) <> ''
                            AND LOWER(TRIM(q.moduleName)) <> 'null'
                            THEN TRIM(q.moduleName)
                        END ORDER BY TRIM(q.moduleName) SEPARATOR '||') as moduleNames
                    FROM questions q
                    WHERE q.subjectId IN (" . implode(',', $subjectIds) . ")
                    AND q.topic_id IN (" . implode(',', $topicIds) . ")
                    AND q.deleted_at IS NULL
                    AND q.isFollowUp IN ('Y','N')
                    AND q.questionType = 'Universal'
                    GROUP BY q.subjectId, q.topic_id";
            $moduleQuery = mysqli_query($databaseConnection, $moduleSql);

            if ($moduleQuery) {
                while ($moduleRow = mysqli_fetch_array($moduleQuery, MYSQLI_ASSOC)) {
                    $pairKey = (int) $moduleRow['subjectId'] . '_' . (int) $moduleRow['topic_id'];
                    $moduleMap[$pairKey] = array(
                        'moduleCount' => (int) $moduleRow['moduleCount'],
                        'moduleNames' => $moduleRow['moduleNames'],
                    );
                }
            }

            $moduleData = array();
            foreach ($subjectTopicPairs as $pairKey => $pair) {
                $moduleName = null;
                if (isset($moduleMap[$pairKey]) && $moduleMap[$pairKey]['moduleCount'] === 1) {
                    $names = explode('||', (string) $moduleMap[$pairKey]['moduleNames']);
                    $moduleName = $names[0] ?? null;
                }

                $moduleData[] = array(
                    'subject' => $pair['subject'],
                    'topic_id' => $pair['topic_id'],
                    'topic_name' => $topicNameMap[$pair['topic_id']] ?? '',
                    'moduleName' => $moduleName,
                );
            }

            $to_encode = array(
                'status' => 1,
                'data' => $moduleData,
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => 'error',
            'errorCode' => 'preInterviewId is required.'
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['checkQuestionCluster'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $sectorId = $json['sectorId'];
        $companyId = $json['companyId'];
        $positionId = $json['positionId'];
        $subjectId = $json['subjectId'];
        $programminglang = $json['programminglang'];
        $clusterFilter = " 1 ";
        $subjectIds = "";

        if ($sectorId != '') {
            $clusterFilter .= " AND sectorId = " . $sectorId . " ";
        }
        if ($companyId != '') {
            $clusterFilter .= " AND companyId IN (" . $companyId . ",0) ";
        }
        if ($positionId != '') {
            $clusterFilter .= " AND roleId IN (" . $positionId . ",0) ";
        }

        if ($subjectId != '') {
            $subjectIds .= $subjectId;
        }
        if ($programminglang != '') {
            $subjectIds .= "," . $programminglang;
        }

        $clusterQry = "SELECT noOfAnswer,noOfSkip FROM interviewStructure WHERE " . $clusterFilter . " LIMIT 1;";
        $clusterResult = mysqli_query($databaseConnection, $clusterQry);
        if (mysqli_num_rows($clusterResult) > 0) {
            $clusterData = mysqli_fetch_all($clusterResult, MYSQLI_ASSOC);
            $clusterRequired = $clusterData[0]['noOfAnswer'] + $clusterData[0]['noOfSkip'];
        } else {
            $clusterData = [];
            $clusterRequired = 5;
        }

        $questionQuery = "SELECT COUNT(DISTINCT CASE WHEN q.deleted_at IS null AND q.isFollowUp IN ('Y','N') AND q.questionType = 'Universal' THEN q.id ELSE null END) as totalQues,CASE WHEN COUNT(DISTINCT CASE WHEN q.deleted_at IS null AND q.isFollowUp IN ('Y','N') THEN q.id ELSE null END) > " . $clusterRequired . " THEN 'Y' ELSE 'N' END as isAvailable,fs.favourite_subject as subjectName FROM questions q RIGHT JOIN favourite_subject fs ON fs.id = q.subjectId  WHERE fs.id IN (" . $subjectIds . ") GROUP BY fs.id;";
        $questionResult = mysqli_query($databaseConnection, $questionQuery);
        if (mysqli_num_rows($questionResult) > 0) {
            $questionData = mysqli_fetch_all($questionResult, MYSQLI_ASSOC);
        } else {
            $questionData = [];
        }

        $to_encode = array(
            'questionData' => $questionData,
            'status' => 1,
        );
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error whire retrieving interview information."
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['getInterviewInfoOnInterviewPage'])) {
    /* this method is added for interview page of loading all question with interview details */

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $interviewId = $json['interviewId'];
        $sessionId = $json['sessionId'];
        $candidateId = $json['candidateId'];
        $values2 = array();
        $data = "select i.*  from `interview` i  where i.id='" . $interviewId . "'";
        $query = mysqli_query($databaseConnection, $data);
        $values = mysqli_fetch_all($query, MYSQLI_ASSOC);


        $tutorial = "select * from `interview_tutorial` where interviewId='" . $interviewId . "' and isActive = 'Y'";
        $tutorialQuery = mysqli_query($databaseConnection, $tutorial);
        if (mysqli_num_rows($query) >= 1) {
            $tutorialValues = mysqli_fetch_all($tutorialQuery, MYSQLI_ASSOC);
            $values[0]['tutorialLink'] = $tutorialValues;
        } else {
            $values[0]['tutorialLink'] = null;
        }


        if ($sessionId != '0') {
            $data2 = "select q.* from questions q inner join interview_questions_transection iqt on iqt.questionId = q.id inner join interview i on i.id = iqt.interviewId where iqt.interviewId = '" . $interviewId . "' and q.isActive = 'Y' and q.deleted_at is null and iqt.deleted_at is null AND q.id NOT in (SELECT questionId FROM `mergedVideos` WHERE interviewSessionId = '" . $sessionId . "' and candidateId = '" . $candidateId . "' and interviewId = '" . $interviewId . "' ) order by iqt.sequence";

        } else {
            $data2 = "select q.* from questions q inner join interview_questions_transection iqt on iqt.questionId = q.id inner join interview i on i.id = iqt.interviewId where iqt.interviewId = '" . $interviewId . "' and q.isActive = 'Y' and q.deleted_at is null and iqt.deleted_at is null order by iqt.sequence";
        }

        $query2 = mysqli_query($databaseConnection, $data2);
        //$values2 = mysqli_fetch_all($query2, MYSQLI_ASSOC);
        while ($row = mysqli_fetch_assoc($query2)) {
            $row['questionHtml'] = nl2br($row['questionText']);
            if ($row['source'] != null) {
                $aspCompaniesQuery = mysqli_query($databaseConnection, "SELECT q.source, group_concat(ac.name SEPARATOR ',') AS questionSource FROM questions q, aspiration_company ac WHERE FIND_IN_SET(ac.id, q.source) and q.id = '" . $row['id'] . "'");
                $aspCompaniesResult = mysqli_fetch_array($aspCompaniesQuery, MYSQLI_ASSOC);
                $row['questionSource'] = $aspCompaniesResult['questionSource'];
            }
            array_push($values2, $row);
        }
        $to_encode = $values;
        array_push($to_encode, $values2);
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error whire retrieving interview information."
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['getQuestionInfo'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $youtubeId = $json['youtubeId'];
        $interviewId = $json['interviewId'];
        $data = "select * from `questions` where youtubeId='" . $youtubeId . "' and interviewId='" . $interviewId . "'";
        $query = mysqli_query($databaseConnection, $data);
        $values = mysqli_fetch_all($query, MYSQLI_ASSOC);
        $to_encode = $values;
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error whire retrieving Question information."
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['getStudentActivityAllFilters'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['candidateId'];
        $result = array();

        $data1 = "SELECT id,statusValue as `value` FROM `salesLeadActionStatus` WHERE usedFor = 'L';";
        $query1 = mysqli_query($databaseConnection, $data1);
        $values1 = mysqli_fetch_all($query1, MYSQLI_ASSOC);

        $data4 = "select * from favourite_subject where isActiveForMentorship = 'Y' order by id=29,favourite_subject";
        $query4 = mysqli_query($databaseConnection, $data4);
        $values4 = mysqli_fetch_all($query4, MYSQLI_ASSOC);

        $data5 = "select * from fav_prog_skill order by id=9,fav_prog_skill";
        $query5 = mysqli_query($databaseConnection, $data5);
        $values5 = mysqli_fetch_all($query5, MYSQLI_ASSOC);


        $data7 = "select * from aspiration_company order by id=40,name";
        $query7 = mysqli_query($databaseConnection, $data7);
        $values7 = mysqli_fetch_all($query7, MYSQLI_ASSOC);

        $data8 = "SELECT * FROM `sector`";
        $query8 = mysqli_query($databaseConnection, $data8);
        $values8 = mysqli_fetch_all($query8, MYSQLI_ASSOC);

        $data9 = "SELECT empstatus as `value` FROM `candidateEmp_status`GROUP BY empstatus;";
        $query9 = mysqli_query($databaseConnection, $data9);
        $values9 = mysqli_fetch_all($query9, MYSQLI_ASSOC);

        $data10 = "SELECT id,favourite_subject as `value` FROM `favourite_subject`;";
        $query10 = mysqli_query($databaseConnection, $data10);
        $values10 = mysqli_fetch_all($query10, MYSQLI_ASSOC);

        $result['salesLead'] = $values1;
        $result['favourite_subject'] = $values4;
        $result['fav_prog_skill'] = $values5;
        $result['aspiration_company'] = $values7;
        $result['sectors'] = $values8;
        $result['empStatus'] = $values9;
        $result['subjectList'] = $values10;
        $to_encode = $result;
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error whire retrieving Question information."
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['getPanelDashboardFilter'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['candidateId'];
        $result = array();

        $data = "select id,collegeName as college from colleges order by id=188,collegeName";
        $query = mysqli_query($databaseConnection, $data);
        $values = mysqli_fetch_all($query, MYSQLI_ASSOC);

        $data2 = "select * from stream where isActive = 'Y' order by id=11,stream";
        $query2 = mysqli_query($databaseConnection, $data2);
        $values2 = mysqli_fetch_all($query2, MYSQLI_ASSOC);

        $data10 = "select * from favourite_subject where streamId=1";
        $query10 = mysqli_query($databaseConnection, $data10);
        $values10 = mysqli_fetch_all($query10, MYSQLI_ASSOC);

        $data11 = "select * from favourite_subject where streamId=21";
        $query11 = mysqli_query($databaseConnection, $data11);
        $values11 = mysqli_fetch_all($query11, MYSQLI_ASSOC);

        $data12 = "select * from favourite_subject where streamId=18";
        $query12 = mysqli_query($databaseConnection, $data12);
        $values12 = mysqli_fetch_all($query12, MYSQLI_ASSOC);

        $data13 = "select * from favourite_subject where streamId=4";
        $query13 = mysqli_query($databaseConnection, $data13);
        $values13 = mysqli_fetch_all($query13, MYSQLI_ASSOC);

        $data14 = "select * from favourite_subject where streamId=5";
        $query14 = mysqli_query($databaseConnection, $data14);
        $values14 = mysqli_fetch_all($query14, MYSQLI_ASSOC);

        $data15 = "select * from favourite_subject where streamId=19";
        $query15 = mysqli_query($databaseConnection, $data15);
        $values15 = mysqli_fetch_all($query15, MYSQLI_ASSOC);

        $data16 = "select * from favourite_subject where streamId  is not null order by streamId";
        $query16 = mysqli_query($databaseConnection, $data16);
        $values16 = mysqli_fetch_all($query16, MYSQLI_ASSOC);

        $data17 = "select name,id from panel where deleted_at is null and expertStatus=1 order by name ";
        $query17 = mysqli_query($databaseConnection, $data17);
        $values17 = mysqli_fetch_all($query17, MYSQLI_ASSOC);

        $data18 = "select * from favourite_subject where streamId=57";
        $query18 = mysqli_query($databaseConnection, $data18);
        $values18 = mysqli_fetch_all($query18, MYSQLI_ASSOC);


        $data19 = "select * from favourite_subject where streamId=58";
        $query19 = mysqli_query($databaseConnection, $data19);
        $values19 = mysqli_fetch_all($query19, MYSQLI_ASSOC);


        $result['college'] = $values;
        $result['stream'] = $values2;
        $result['computerScience'] = $values10;
        $result['coding'] = $values11;
        $result['circuitBranch'] = $values12;
        $result['mechanical'] = $values13;
        $result['civil'] = $values14;
        $result['businessAdministration'] = $values15;
        $result['expertise'] = $values16;
        $result['referrerName'] = $values17;
        $result['cloud'] = $values18;
        $result['dataAnalyst'] = $values19;


        $to_encode = $result;
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error whire retrieving Question information."
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['getAllList'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['candidateId'];
        $result = array();

        $data = "select id,collegeName as college from colleges order by id=188,collegeName";
        $query = mysqli_query($databaseConnection, $data);
        $values = mysqli_fetch_all($query, MYSQLI_ASSOC);

        $data2 = "select * from stream where isActive = 'Y' order by id=11,stream";
        $query2 = mysqli_query($databaseConnection, $data2);
        $values2 = mysqli_fetch_all($query2, MYSQLI_ASSOC);

        $data3 = "select * from qualification order by id=10,qualification";
        $query3 = mysqli_query($databaseConnection, $data3);
        $values3 = mysqli_fetch_all($query3, MYSQLI_ASSOC);

        $data4 = "select * from favourite_subject where isActiveForMentorship = 'Y' order by id=29,favourite_subject";
        $query4 = mysqli_query($databaseConnection, $data4);
        $values4 = mysqli_fetch_all($query4, MYSQLI_ASSOC);

        $data5 = "select * from fav_prog_skill order by id=9,fav_prog_skill";
        $query5 = mysqli_query($databaseConnection, $data5);
        $values5 = mysqli_fetch_all($query5, MYSQLI_ASSOC);

        $data6 = "select * from category";
        $query6 = mysqli_query($databaseConnection, $data6);
        $values6 = mysqli_fetch_all($query6, MYSQLI_ASSOC);

        $data7 = "select * from aspiration_company order by id=40,name";
        $query7 = mysqli_query($databaseConnection, $data7);
        $values7 = mysqli_fetch_all($query7, MYSQLI_ASSOC);

        $data8 = "select * from favourite_domain where isActive = 'Y' order by id=39,name";
        $query8 = mysqli_query($databaseConnection, $data8);
        $values8 = mysqli_fetch_all($query8, MYSQLI_ASSOC);

        $data9 = "select * from language";
        $query9 = mysqli_query($databaseConnection, $data9);
        $values9 = mysqli_fetch_all($query9, MYSQLI_ASSOC);

        $data10 = "select * from favourite_subject where streamId=1";
        $query10 = mysqli_query($databaseConnection, $data10);
        $values10 = mysqli_fetch_all($query10, MYSQLI_ASSOC);

        $data11 = "select * from favourite_subject where streamId=21";
        $query11 = mysqli_query($databaseConnection, $data11);
        $values11 = mysqli_fetch_all($query11, MYSQLI_ASSOC);

        $data12 = "select * from favourite_subject where streamId=18";
        $query12 = mysqli_query($databaseConnection, $data12);
        $values12 = mysqli_fetch_all($query12, MYSQLI_ASSOC);

        $data13 = "select * from favourite_subject where streamId=4";
        $query13 = mysqli_query($databaseConnection, $data13);
        $values13 = mysqli_fetch_all($query13, MYSQLI_ASSOC);

        $data14 = "select * from favourite_subject where streamId=5";
        $query14 = mysqli_query($databaseConnection, $data14);
        $values14 = mysqli_fetch_all($query14, MYSQLI_ASSOC);

        $data15 = "select * from favourite_subject where streamId=19";
        $query15 = mysqli_query($databaseConnection, $data15);
        $values15 = mysqli_fetch_all($query15, MYSQLI_ASSOC);

        $data16 = "select * from favourite_subject where streamId  is not null order by streamId";
        $query16 = mysqli_query($databaseConnection, $data16);
        $values16 = mysqli_fetch_all($query16, MYSQLI_ASSOC);

        $data17 = "select name,id from panel where deleted_at is null and expertStatus=1 order by name ";
        $query17 = mysqli_query($databaseConnection, $data17);
        $values17 = mysqli_fetch_all($query17, MYSQLI_ASSOC);

        $result['college'] = $values;
        $result['stream'] = $values2;
        $result['qualification'] = $values3;
        $result['favourite_subject'] = $values4;
        $result['fav_prog_skill'] = $values5;
        $result['category'] = $values6;
        $result['aspiration_company'] = $values7;
        $result['favourite_domain'] = $values8;
        $result['languages'] = $values9;
        $result['computerScience'] = $values10;
        $result['coding'] = $values11;
        $result['circuitBranch'] = $values12;
        $result['mechanical'] = $values13;
        $result['civil'] = $values14;
        $result['businessAdministration'] = $values15;
        $result['expertise'] = $values16;
        $result['referrerName'] = $values17;


        $to_encode = $result;
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error whire retrieving Question information."
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['peerTransection'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['candidateId'];
        $peerResponse = $json['peerResponse'];
        $data = "select pr.* from peer_response pr where pr.mergeId = (select m.mergeId from mergedVideos m where m.youtubeId='" . $peerResponse . "');";
        $query = mysqli_query($databaseConnection, $data);
        if (mysqli_num_rows($query) >= 1) {
            $values = mysqli_fetch_all($query, MYSQLI_ASSOC);
            $sqlQuery = "INSERT INTO `peer_transection` (`userId`, `peerId`, `watchingTime`) VALUES ('$candidateId', '" . $values[0]['id'] . "', ROUND(UNIX_TIMESTAMP()*1000));";
            $usersQuery = mysqli_query($databaseConnection, $sqlQuery);
            if ($usersQuery) {
                $peerTransectionId = mysqli_insert_id($databaseConnection);
                $to_encode = array(
                    'result' => "Success",
                    'response' => 'Peer Transection Created.',
                    'status' => 1,
                    'peerTransectionId' => $peerTransectionId
                );
            } else {
                $to_encode = array(
                    'status' => 0,
                    'result' => "error",
                    'errorCode' => "in Error whire retrieving Question information."
                );
            }
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "in Error whire retrieving Question information."
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error whire retrieving Question information."
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['updatePeerTransection'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['candidateId'];
        $peerTransectionId = $json['peerTransectionId'];

        $data = "select * from peer_transection where id = '" . $peerTransectionId . "';";
        $query = mysqli_query($databaseConnection, $data);
        if (mysqli_num_rows($query) >= 1) {
            $values = mysqli_fetch_all($query, MYSQLI_ASSOC);
            $sqlQuery = "UPDATE `peer_transection` SET  isWatchedFull = 'Y' where id = '" . $peerTransectionId . "';";
            $usersQuery = mysqli_query($databaseConnection, $sqlQuery);
            if ($usersQuery) {
                //$peerTransectionId = mysqli_insert_id($databaseConnection);
                $to_encode = array(
                    'result' => "Success",
                    'response' => 'Peer Transection Updated.',
                    'status' => 1
                );
            } else {
                $to_encode = array(
                    'status' => 0,
                    'result' => "error",
                    'errorCode' => "in Error whire retrieving Peer Transection."
                );
            }
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "in Error whire retrieving Question information."
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error whire retrieving Question information."
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['updateCandidateVideoWatch'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $interviewId = $json['interviewId'];
        $questionId = $json['questionId'];
        $candidateId = $json['candidateId'];
        $answerVideoLength = $json['answerVideoLength'];
        $currentFeedbackRequestId = $json['currentFeedbackRequestId'];
        $interviewSessionId = $json['interviewSessionId'];
        $videoWatchDurationArray = implode(", ", $json['videoWatchDurationArray']);

        $data = "select m.*, vwd.vidWatchedDuration from mergedVideos m inner join video_watched_details vwd on vwd.mergeId = m.mergeId where m.interviewSessionId = '" . $interviewSessionId . "' and m.questionId = '" . $questionId . "';";
        $query = mysqli_query($databaseConnection, $data);
        $values = mysqli_fetch_assoc($query);

        if (strtotime($values['vidWatchedDuration']) < strtotime($answerVideoLength)) {
            $result = mysqli_query($databaseConnection, "update video_watched_details set vidWatchedDuration = '" . $answerVideoLength . "',vidWatchedDurationArray = '" . $videoWatchDurationArray . "'  where mergeId = '" . $values['mergeId'] . "'");

            if ($result) {
                $to_encode = array(
                    'result' => "Success",
                    'status' => 1,
                    'message' => 'data saved'
                );
            } else {
                $to_encode = array(
                    'status' => 0,
                    'result' => "error",
                    'errorCode' => "in Error while updating information."
                );
            }
        } else {
            $to_encode = array(
                'result' => "Success",
                'status' => 1,
                'message' => 'video duration less than previous one'
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while updating information."
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['updateVideoWatch'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $mergeId = $json['mergeId'];
        $answerVideoLength = $json['answerVideoLength'];
        $watchedVideoType = $json['watchedVideoType'];

        $data = "select * from video_watched_details where mergeId = '" . $mergeId . "';";
        $query = mysqli_query($databaseConnection, $data);
        $values = mysqli_fetch_assoc($query);

        $result = mysqli_query($databaseConnection, "update video_watched_details set " . $watchedVideoType . " = '" . sum_the_time([$values[$watchedVideoType], $answerVideoLength]) . "' where mergeId = '" . $mergeId . "';");
        if ($result) {
            $to_encode = array(
                'result' => "Success",
                'status' => 1,
                'message' => 'data saved'
            );
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "in Error while updating information."
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while updating information."
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getquestionReviewData'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['candidateId'];
        $values = array();

        $data = "select q.id as qId, iqt.interviewId, q.youtubeId as questionId, q.questionText, q.questionDesc, q.quesDiagram, i.name from questions q inner join interview_questions_transection iqt on iqt.questionId = q.id INNER JOIN interview i on iqt.interviewId = i.id where q.isActive = 'Y' and q.deleted_at is NULL and iqt.deleted_at is null and i.isActive = 'Y' and i.deleted_at is NULL order by q.id desc;";
        $query = mysqli_query($databaseConnection, $data);

        if (mysqli_num_rows($query) >= 1) {
            while ($row = mysqli_fetch_assoc($query)) {
                $row['questionHtml'] = nl2br($row['questionText']);
                $querys = mysqli_query($databaseConnection, "SELECT er.id,er.expert_review_suggestion,m.youtubeId FROM expert_review er inner join feedback_request fr on er.feedback_request_id = fr.id inner join mergedVideos m on m.interviewSessionId = fr.interviewSessionId WHERE er.questionVideoId LIKE '" . $row['questionId'] . "' AND er.review_type LIKE 'question' AND m.questionVideoId LIKE '" . $row['questionId'] . "'");
                $row['review_exists'] = 0;
                if (mysqli_num_rows($querys) > 0) {
                    $row['review_exists'] = 1;
                }
                array_push($values, $row);
            }
        }
        $to_encode = $values;
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error whire retrieving review information.",
            'sql' => $data
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['getCurrentQuestionReviewData'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $questionId = $json['questionId'];
        $reviewData = array();
        $allReviewData = array();

        $querys = mysqli_query($databaseConnection, "SELECT er.id,er.expert_review_suggestion,m.youtubeId FROM expert_review er inner join feedback_request fr on er.feedback_request_id = fr.id inner join mergedVideos m on m.interviewSessionId = fr.interviewSessionId WHERE er.questionVideoId LIKE '" . $questionId . "' AND er.review_type LIKE 'question' AND m.questionVideoId LIKE '" . $questionId . "'");
        if (mysqli_num_rows($querys) > 0) {
            while ($expert_review = mysqli_fetch_assoc($querys)) {
                $allReviewData['expert_review_id'] = $expert_review['id'];
                $allReviewData['expert_review_suggestion'] = nl2br($expert_review['expert_review_suggestion']);
                $allReviewData['answerId'] = $expert_review['youtubeId'];
                $review_query = mysqli_query($databaseConnection, "SELECT erpd.observationValueId,p.observation_name,pv.observation_values FROM `expert_review_observation_details` as erpd , observation_area as p,observation_values as pv WHERE erpd.expertReviewId = " . $expert_review['id'] . " and erpd.observationValueId=pv.id and pv.observation_id=p.id and p.key_skill != 0");
                if (mysqli_num_rows($review_query) > 0) {
                    $allReviewData['review_data'] = mysqli_fetch_all($review_query, MYSQLI_ASSOC);
                }
                array_push($reviewData, $allReviewData);
                unset($allReviewData);
                $allReviewData = array();
            }
        }
        $to_encode = $reviewData;
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error whire retrieving review information.",
            'sql' => $data
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['getExportQuestionReviewData'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $values = array();

        $data = "SELECT i.name as interviewName, q.youtubeId as questionId, m.youtubeId as answerId, erpd.observationValueId, p.observation_name, pv.observation_values, q.id as qId, q.interviewId, q.questionText, q.questionDesc, er.id as expert_review_id, if(er.expert_review_suggestion='',NULL,er.expert_review_suggestion) as expert_review_suggestion FROM expert_review_observation_details as erpd, observation_area as p, observation_values as pv, questions q, interview i, expert_review er, mergedVideos m, feedback_request fr, key_skill ks WHERE erpd.observationValueId=pv.id and pv.observation_id=p.id and p.key_skill != 0 and erpd.expertReviewId = er.id and er.questionVideoId = q.youtubeId and er.interviewId = i.id and er.feedback_request_id = fr.id and m.interviewSessionId = fr.interviewSessionId and er.questionVideoId = m.questionVideoId and ks.key_skill = p.observation_name order by i.id;";
        $query = mysqli_query($databaseConnection, $data);

        if (mysqli_num_rows($query) >= 1) {
            //$values = mysqli_fetch_all($query, MYSQLI_ASSOC);
            while ($row = mysqli_fetch_assoc($query)) {
                $row['communicationSkill'] = NULL;
                $row['technicalSkill'] = NULL;
                $row['behaviouralSkill'] = NULL;
                $row['confidence'] = NULL;
                $row['codingSkill'] = NULL;
                switch ($row['observation_name']) {
                    case 'Communication Skill':
                        $row['communicationSkill'] = $row['observation_values'];
                        break;
                    case 'Technical Skill':
                        $row['technicalSkill'] = $row['observation_values'];
                        break;
                    case 'Behavioural Skill':
                        $row['behaviouralSkill'] = $row['observation_values'];
                        break;
                    case 'Confidence':
                        $row['confidence'] = $row['observation_values'];
                        break;
                    case 'Coding Skill':
                        $row['codingSkill'] = $row['observation_values'];
                        break;
                }
                array_push($values, $row);
            }
        }
        $to_encode = $values;
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error whire retrieving review information.",
            'sql' => $data
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['videoIssueFeedbackSave'])) {
    /* this method is added for question level video issue feedback by admin 20-oct-2021 */

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['candidateId'];
        $questionId = $json['questionId'];
        $interviewId = $json['interviewId'];
        $questionVideoId = $json['questionVideoId'];
        $interviewSessionId = $json['interviewSessionId'];
        $observation_values = $json['observation_values'];
        $feedbackRequestId = mysqli_query($databaseConnection, "select id,review_status from feedback_request where interviewSessionId='" . $interviewSessionId . "'");
        $feedback_id = mysqli_fetch_assoc($feedbackRequestId);
        $feedbackRequestId = $feedback_id['id'];

        if ($feedback_id['review_status'] == 2) {
            if ($observation_values == 308 || $observation_values == 443 || $observation_values == 442 || $observation_values == 447) {

                $sqldelQuery = mysqli_query($databaseConnection, "delete from expert_review_observation_details where feedback_request_id='" . $feedbackRequestId . "'  and questionId ='" . $questionId . "' and observationValueId in (308,443,442)");

                $expertQuery = mysqli_query($databaseConnection, "select id from expert_review where questionId = '" . $questionId . "' and feedback_request_id = '" . $feedbackRequestId . "'");

                if (mysqli_num_rows($expertQuery) > 0) {
                    $expertId = mysqli_fetch_assoc($expertQuery)['id'];
                    $Expert_observationDetails1 = mysqli_query($databaseConnection, "INSERT INTO `expert_review_observation_details`(expertReviewId,observationAreaId,observationValueId,questionId,feedback_request_id) VALUES($expertId,25,$observation_values,$questionId,$feedbackRequestId)");
                }
            }

            if ($Expert_observationDetails1) {
                $to_encode = array(
                    'status' => "1",
                    'result' => "Success",
                    'msg' => "Data Inserted into observation details.",
                    'questionId' => $questionId
                );
            }

        } else {

            $sql1 = mysqli_query($databaseConnection, "delete from expert_review_observation_details where expertReviewId in(select id from expert_review where feedback_request_id='" . $feedbackRequestId . "'  and questionId ='" . $questionId . "')");
            $sql2 = mysqli_query($databaseConnection, "delete from expert_review where feedback_request_id='" . $feedbackRequestId . "'  and questionId ='" . $questionId . "'");


            // sibin aug 31 2022 for giving review for issue type malpractice also
            if ($observation_values == 308 || $observation_values == 443 || $observation_values == 442 || $observation_values == 447) {
                $sql2 = mysqli_query($databaseConnection, "delete from expert_review_observation_details where feedback_request_id='" . $feedbackRequestId . "'  and questionId ='" . $questionId . "'");

                $Expert_observationDetails = mysqli_query($databaseConnection, "INSERT INTO `expert_review_observation_details`(observationAreaId,observationValueId,questionId,feedback_request_id) VALUES(25,$observation_values,$questionId,$feedbackRequestId)");

                $feedback_status_question = mysqli_query($databaseConnection, "DELETE FROM `feedback_status_question` WHERE feedbackRequestId='" . $feedbackRequestId . "'  and questionId ='" . $questionId . "'");

                if ($Expert_observationDetails) {
                    $to_encode = array(
                        'status' => "1",
                        'result' => "Success",
                        'msg' => "Data Inserted into observation details.",
                        'questionId' => $questionId
                    );

                } else {
                    $to_encode = array(
                        'status' => 0,
                        'result' => "error",
                        'errorCode' => "Error while inserting into observation details."
                    );

                }
            } else {

                $sql2 = mysqli_query($databaseConnection, "delete from expert_review_observation_details where feedback_request_id='" . $feedbackRequestId . "'  and questionId ='" . $questionId . "' and expertReviewId is null");
                if ($observation_values == 91 || $observation_values == 92 || $observation_values == 93) {
                    $expert_reviewQuery = mysqli_query($databaseConnection, "INSERT INTO `expert_review`(interviewId, candidateId, feedbackGivenBy,questionId,  `questionVideoId`, `streamId`,feedback_request_id,overallRating,questionTag) VALUES($interviewId, $candidateId,62,$questionId,'$questionVideoId','streamId',$feedbackRequestId, 'videoIssue','technicalIssue')");
                } else if ($observation_values == 446) {
                    $expert_reviewQuery = mysqli_query($databaseConnection, "INSERT INTO `expert_review`(interviewId, candidateId, feedbackGivenBy,questionId,  `questionVideoId`, `streamId`,feedback_request_id,overallRating,questionTag) VALUES($interviewId, $candidateId,62,$questionId,'$questionVideoId','streamId',$feedbackRequestId,0,'nonSerious')");
                } else {
                    $expert_reviewQuery = mysqli_query($databaseConnection, "INSERT INTO `expert_review`(interviewId, candidateId, feedbackGivenBy,questionId,  `questionVideoId`, `streamId`,feedback_request_id,overallRating) VALUES($interviewId, $candidateId,62,$questionId,'$questionVideoId','streamId',$feedbackRequestId, 'videoIssue')");
                }


                if ($expert_reviewQuery) {
                    $expert_Review_Id = mysqli_insert_id($databaseConnection);
                    $Expert_observationDetails = mysqli_query($databaseConnection, "INSERT INTO `expert_review_observation_details`(expertReviewId,observationAreaId,observationValueId) VALUES($expert_Review_Id,25,$observation_values)");
                    if ($Expert_observationDetails) {
                        $param_id = mysqli_insert_id($databaseConnection);
                        $expertReviewParamQryResult = mysqli_query($databaseConnection, "update `expert_review` set review_param_valueId=" . $param_id . " where id=" . $expert_Review_Id);

                        $sql3 = mysqli_query($databaseConnection, "delete from feedback_status_question where feedbackRequestId='" . $feedbackRequestId . "'  and questionId ='" . $questionId . "'");

                        $feedback_status_question = mysqli_query($databaseConnection, "INSERT INTO `feedback_status_question`(feedbackRequestId,expertId,questionId,review_status) VALUES($feedbackRequestId,62,$questionId,2)");
                        if ($feedback_status_question) {
                            $to_encode = array(
                                'status' => "1",
                                'result' => "Success",
                                'msg' => "Data Inserted SucessFully All places.",
                                'questionId' => $questionId
                            );

                        } else {
                            $to_encode = array(
                                'status' => 0,
                                'result' => "error",
                                'errorCode' => "Error while inserting into Feedback_status_question."
                            );

                        }


                    } else {
                        $to_encode = array(
                            'status' => 0,
                            'result' => "error",
                            'msg' => "Error while inserting into Expert_observationDetails."
                        );

                    }
                } else {
                    $to_encode = array(
                        'status' => 0,
                        'result' => "error",
                        'errorCode' => "Error while inserting into Expert_Review."
                    );
                }
            }

        }

    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "in Error while retrieving review information."
        );
    }

    echo json_encode($to_encode);
}


elseif (isset($_GET['getReviewInfo'])) {
    // node-api
    header('Content-Type: application/json');
    $raw = file_get_contents("php://input");
    $json = json_decode($raw, true);
    $to_encode = [];

    try {
        if (!is_array($json)) {
            throw new Exception('Invalid JSON');
        }

        // Inputs
        $interviewId        = (int)$json['interviewId'];
        $interviewSessionId = (int)$json['interviewSessionId'];
        $candidateId        = (int)$json['candidateId'];
        $userDataEnc        = $json['userData'];

        // Authorization
        $userType = getDecrypt($userDataEnc)->usertype;
        if (isUserAuthorised($databaseConnection, $userDataEnc, $candidateId) === 'unAuthorized') {
            throw new Exception('unAuthorized');
        }

        // paymentStatus
        $paymentStatus = '0';
        $pres = mysqli_query($databaseConnection,
            "SELECT status FROM payment_transaction
             WHERE user_id=$candidateId AND interview_id=$interviewId AND subscriptionType='job'
             ORDER BY (status='PAID') DESC LIMIT 1"
        );
        if ($pres && mysqli_num_rows($pres)) {
            $paymentStatus = mysqli_fetch_assoc($pres)['status'];
        }

        // Malpractice Summary Count
        $malpracticeCounts = [
            "GENUINE" => 0,
            "SUSPICIOUS" => 0,
            "MALPRACTICE" => 0
        ];

        $summarySql = "
            SELECT malpracticeValue, COUNT(*) as count
            FROM mergedVideos
            WHERE interviewSessionId = ?
            GROUP BY malpracticeValue
        ";

        $summaryStmt = $databaseConnection->prepare($summarySql);
        $summaryStmt->bind_param("s", $interviewSessionId);
        $summaryStmt->execute();
        $summaryResult = $summaryStmt->get_result();

        while ($row = $summaryResult->fetch_assoc()) {
            $value = strtoupper($row["malpracticeValue"]);
            if (array_key_exists($value, $malpracticeCounts)) {
                $malpracticeCounts[$value] = (int)$row["count"];
            }
        }


        // interviewType
        $interviewType = 'job';
        $tres = mysqli_query($databaseConnection,
            "SELECT pr.interviewType FROM interview i
             JOIN preInterview pr ON i.preInterviewId=pr.id
             WHERE i.id=$interviewId"
        );
        if ($tres && mysqli_num_rows($tres)) {
            $interviewType = mysqli_fetch_assoc($tres)['interviewType'];
        }

        // badScoreQuestion
        $badScoreQuestion = null;
        $bsres = mysqli_query($databaseConnection,
            "SELECT questionId FROM expert_review
             WHERE interviewId=$interviewId AND overallRating IS NOT NULL AND overallRating!=0
             ORDER BY overallRating ASC LIMIT 1"
        );
        if ($bsres && mysqli_num_rows($bsres)) {
            $badScoreQuestion = (int)mysqli_fetch_assoc($bsres)['questionId'];
        }

        // Main fetch
        $mainSql = " SELECT iqt.id AS iqtId,
                iqt.questionId,
                iqt.attemptStatus,
                   fs.favourite_subject,
                   q.questionText AS questionText,
                   CASE WHEN iqt.attemptStatus IN ('Respond1','Idk1') THEN q.idk1
                        WHEN iqt.attemptStatus IN ('Respond2','Idk2') THEN q.idk2
                        ELSE q.questionText END AS questionText,
                   q.questionText AS originalQuestionText,
                   SUBSTRING(SEC_TO_TIME(q.thinkingTime*60),1,8) AS expectedThinkingTime,
                   q.peerResponseVideo,
                   q.shortExpectedAns,
                   q.quesDiagram,
                   q.instruction,
                   q.source,
                   q.mbr_id,
                   q.isFollowUp,
                   q.expertAdvice,
                   IF(q.isWbRequired='Y','Yes','No') AS isWbRequired,
                   mv.mergeId,
                   mv.totalTime,
                   mv.vidLength,
                   mv.youtubeId,
                   vwd.prWatchDuration,
                   vwd.psWatchDuration,
                   vwd.gvWatchDuration,
                   qt.whiteboardText AS inorganicPeerWB,
                   topic.name AS topicName
            FROM interview_questions_transection iqt
            JOIN questions q ON q.id=iqt.questionId
            JOIN favourite_subject fs ON fs.id=q.subjectId
            LEFT JOIN mergedVideos mv ON mv.questionId=q.id
                 AND mv.interviewId=iqt.interviewId
                 AND mv.candidateId=$candidateId
                 AND mv.interviewSessionId=$interviewSessionId
            LEFT JOIN video_watched_details vwd ON vwd.mergeId=mv.mergeId
            LEFT JOIN questions_transection qt ON qt.vimeoId=q.peerResponseVideo
            LEFT JOIN topic ON topic.id=q.topic_id
            WHERE iqt.interviewId=$interviewId
              AND iqt.attemptStatus IS NOT NULL
            ORDER BY iqt.id ASC
        ";
        $mres = mysqli_query($databaseConnection, $mainSql);
        if (!$mres || mysqli_num_rows($mres) < 1) {
            throw new Exception('NoData');
        }

        // Prepare IDs
        $rawRows     = mysqli_fetch_all($mres, MYSQLI_ASSOC);
                $caseStudy = null;
                $caseStudySql = "SELECT q.scenario AS caseStudy
                                                 FROM interview_questions_transection iqt
                                                 JOIN questions q ON q.id = iqt.questionId
                                                 WHERE iqt.interviewId=$interviewId
                                                     AND iqt.attemptStatus IS NOT NULL
                                                     AND q.scenario IS NOT NULL
                                                     AND TRIM(q.scenario) <> ''
                                                     AND (q.followUp = 'Parent' OR q.isFollowUp = 'N')
                                                 ORDER BY CASE WHEN q.followUp = 'Parent' THEN 0 ELSE 1 END, iqt.id ASC
                                                 LIMIT 1";
                $caseStudyResult = mysqli_query($databaseConnection, $caseStudySql);
                if ($caseStudyResult && mysqli_num_rows($caseStudyResult) > 0) {
                        $caseStudyRow = mysqli_fetch_assoc($caseStudyResult);
                        $caseStudy = trim($caseStudyRow['caseStudy']);
                }
        $questionIds = array_unique(array_column($rawRows, 'questionId'));
        $mergeIds    = array_values(array_filter(array_column($rawRows, 'mergeId')));
        $expAdvice   = array_unique(array_filter(array_column($rawRows, 'expertAdvice')));

        function inList(array $arr) { return $arr ? implode(',', array_map('intval',$arr)) : 'NULL'; }

        // Malpractice values map(new)
        $malMap = [];
        $malSql = "SELECT questionId, malpracticeValue
                FROM mergedVideos
                WHERE malpracticeStatus = 2
                    AND candidateId = $candidateId
                    AND interviewId = $interviewId
                    AND interviewSessionId = $interviewSessionId
                    AND questionId IN (" . inList($questionIds) . ")";

        $malRes = mysqli_query($databaseConnection, $malSql);
        if ($malRes) {
            while ($row = mysqli_fetch_assoc($malRes)) {
                $qid = (int)$row['questionId'];
                $malMap[$qid] = $row['malpracticeValue'];
            }
        }


        // Aspiration companies
        $aspSql = "SELECT q.id AS questionId, GROUP_CONCAT(ac.name) AS questionSource
                   FROM questions q
                   JOIN aspiration_company ac ON FIND_IN_SET(ac.id,q.source)
                   WHERE q.id IN (".inList($questionIds).")
                   GROUP BY q.id";
        $aspMap=[];
        $ares = mysqli_query($databaseConnection,$aspSql);
        while($r=mysqli_fetch_assoc($ares)){
            $aspMap[(int)$r['questionId']] = $r['questionSource'];
        }

        //  HowToThink
        $httSql="SELECT questionId, skillId, howToThink FROM howToThink
                 WHERE questionId IN (".inList($questionIds).")";
        $httMap=[];
        $hres=mysqli_query($databaseConnection,$httSql);
        while($r=mysqli_fetch_assoc($hres)){
            $httMap[(int)$r['questionId']] = ['skillId'=>$r['skillId'],'howToThink'=>$r['howToThink']];
        }

        // 5c) Whiteboard texts
        $wbSql="SELECT w.questionId, wd.text FROM whiteboard w
                JOIN whiteboard_details wd ON wd.whiteBoardId=w.whiteboardId
                WHERE w.interviewSessionId=$interviewSessionId
                  AND w.interviewId=$interviewId
                  AND w.candidateId=$candidateId
                  AND w.questionId IN (".inList($questionIds).")
                ORDER BY wd.id DESC";
        $wbMap=[]; $seen=[];
        $wbres=mysqli_query($databaseConnection,$wbSql);
        while($r=mysqli_fetch_assoc($wbres)){
            $qid=(int)$r['questionId'];
            if(!isset($seen[$qid])){ $wbMap[$qid]=$r['text']; $seen[$qid]=1; }
        }

        // Expert reviews
        $expertMap = [];
        $expertReviewMap=[];
        $erSql="SELECT er.questionId, er.id AS
                        reviewId,
                        er.overallRating,
                       er.expert_review_suggestion,
                       fsq.review_status,
                       m.youtubeId AS feedbackVideoURL,
                       m.mergeId AS expertMergeId,
                       GROUP_CONCAT(DISTINCT ov.observation_values) AS observations,
                       oa.observation_name,
                       ov.observation_values,
                     CASE
                        WHEN ov.observation_values = 'Technical Issue: Video not available' THEN 'NA'
                        ELSE ROUND(
                            (
                                SELECT COUNT(*)
                                FROM expert_review_observation_details AS inner_erod
                                INNER JOIN observation_area AS inner_oa ON inner_oa.id = inner_erod.observationAreaId
                                LEFT OUTER JOIN observation_values AS inner_ov ON inner_ov.id = inner_erod.observationValueId
                                WHERE inner_oa.observation_name = oa.observation_name AND inner_ov.observation_values < ov.observation_values
                            ) / NULLIF(
                                (
                                    SELECT COUNT(*)
                                    FROM expert_review_observation_details AS inner_erod
                                    INNER JOIN observation_area AS inner_oa ON inner_oa.id = inner_erod.observationAreaId
                                    LEFT OUTER JOIN observation_values AS inner_ov ON inner_ov.id = inner_erod.observationValueId
                                    WHERE inner_oa.observation_name = oa.observation_name
                                ), 0
                            ) * 100, 2
                        )
                     END AS percentile
                FROM expert_review er
                JOIN feedback_status_question fsq ON fsq.feedbackRequestId=er.feedback_request_id AND fsq.questionId=er.questionId
                LEFT JOIN mergedVideos m ON m.outputVideoURL=er.feedbackVideoURL
                LEFT JOIN expert_review_observation_details erod ON erod.expertReviewId=er.id
                LEFT JOIN observation_area as oa on oa.id = erod.observationAreaId
                LEFT JOIN observation_values ov ON ov.id=erod.observationValueId
                WHERE er.interviewId=$interviewId AND er.questionId IN (".inList($questionIds).")
                GROUP BY er.questionId";

        $eres=mysqli_query($databaseConnection,$erSql);
        while($r=mysqli_fetch_assoc($eres)){
            $qid=(int)$r['questionId'];
            $expertReviewMap[$qid]=[
                'expert_review_suggestion'=>nl2br($r['expert_review_suggestion']),
                'expert_review_id'=>$r['reviewId'],
                'overallRating'=>$r['overallRating'],
                'feedbackVideoURL'=>$r['feedbackVideoURL'],
                'expertMergeId'=>$r['expertMergeId'],
                'quesFeedbackStatus'=>$r['review_status'],
                'review_data'=>explode(',',$r['observations']),
                'observation_name'=>$r['observation_name'],
                'observation_values'=>$r['observation_values']
            ];

                 $expertMap[$qid] = [
                    'percentile' =>  $r['percentile']
                ];
        }

        // Expert feedback data
        $feedbackSql = "SELECT questionId, skill, feedbackSummary, keyTopicExploration, candidateThoughtProcess, actionableThinkingAdvice
                        FROM expert_review_observation_feedback
                        WHERE interviewId=$interviewId
                          AND questionId IN (".inList($questionIds).")";
        $feedbackMap = [];
        $frRes = mysqli_query($databaseConnection, $feedbackSql);
        if ($frRes) {
            while ($f = mysqli_fetch_assoc($frRes)) {
                $fid = (int)$f['questionId'];
                $feedbackMap[$fid][] = [
                    'skill' => $f['skill'],
                    'feedbackSummary' => $f['feedbackSummary'],
                    'keyTopicExploration' => $f['keyTopicExploration'],
                    'candidateThoughtProcess' => $f['candidateThoughtProcess'],
                    'actionableThinkingAdvice' => $f['actionableThinkingAdvice']
                ];
            }
        }

        // File status & avgTime
        $fileStatusMap=[]; $avgTimeMap=[];
        if(!empty($mergeIds)){
            $fsSql="SELECT `key` AS mergeId, `status` FROM file_upload_status
                    WHERE `key` IN (".inList($mergeIds).")";
            $fsr=mysqli_query($databaseConnection,$fsSql);
            while($r=mysqli_fetch_assoc($fsr)){
                $fileStatusMap[(int)$r['mergeId']]=$r['status'];
            }

            $atSql="SELECT mv.mergeId,
                           SUBSTR(SEC_TO_TIME(AVG(TIME_TO_SEC(mvv.totalTime))),1,8) AS averageTotalTime
                    FROM mergedVideos mv
                    JOIN mergedVideos mvv ON mvv.questionId=mv.questionId
                    JOIN feedback_request fr ON fr.interviewSessionId=mvv.interviewSessionId
                                              AND fr.review_status=2
                    WHERE mv.mergeId IN (".inList($mergeIds).")
                    GROUP BY mv.mergeId";
            $atr=mysqli_query($databaseConnection,$atSql);
            while($r=mysqli_fetch_assoc($atr)){
                $avgTimeMap[(int)$r['mergeId']]=$r['averageTotalTime'];
            }
        }



        // Peer reviews

        $peerReviewMap = [];

        // REMOVED peer summary / feedback data joins
        $prSql = "WITH top_reviews AS (
                    SELECT 
                        er.*,
                            ROW_NUMBER() OVER (
                        PARTITION BY er.questionId
                        ORDER BY CAST(er.overallRating AS DECIMAL(10,2)) DESC
                        ) AS rn
                    FROM expert_review AS er
                    WHERE
                    er.questionId IN (".inList($questionIds).") AND er.review_type = 'question'
                    ORDER BY
                        er.questionId,
                        CAST(er.overallRating AS DECIMAL(10,2)) DESC
                    )
                    SELECT
                    tr.questionId,
                    m.mergeId                       AS expertMergeId
                    FROM top_reviews AS tr
                    JOIN feedback_status_question AS fsq
                    ON fsq.feedbackRequestId = tr.feedback_request_id
                    AND fsq.questionId        = tr.questionId
                    LEFT JOIN mergedVideos AS m ON m.interviewId = tr.interviewId AND m.questionId  = tr.questionId
                    WHERE rn = 1
                    ORDER BY
                    tr.questionId;";

        // echo $prSql;

        $pres = mysqli_query($databaseConnection,$prSql);
        if($pres && mysqli_num_rows($pres)){
            while($pr = mysqli_fetch_assoc($pres)){
                $qid = (int)$pr['questionId'];
                $peerReviewMap[$qid] = [
                    'expertMergeId'            => $pr['expertMergeId']
                ];
            }
        }

        // Peer feedback data
        if (!empty($peerReviewMap)) {
        // $peerFbSql = "SELECT questionId, skill, feedbackSummary, keyTopicExploration, candidateThoughtProcess
        //                 FROM expert_review_observation_feedback
        //                 WHERE interviewId IN (" . implode(',', array_column($peerReviewMap, 'interviewId')) . ")
        //                 AND questionId IN (".inList($questionIds).")";

                $peerFbSql = "SELECT erof.questionId,
                                skill,
                                feedbackSummary,
                                keyTopicExploration,
                                candidateThoughtProcess,
                                actionableThinkingAdvice
                                FROM expert_review_observation_feedback erof
                                JOIN mergedVideos mv ON mv.interviewId  = erof.interviewId AND mv.questionId  = erof.questionId
                                WHERE mv.mergeId IN (" . implode(',', array_column($peerReviewMap, 'expertMergeId')) . ")";

                        // echo $peerFbSql;
        $pfRes = mysqli_query($databaseConnection, $peerFbSql);
        if ($pfRes) {
            while ($pf = mysqli_fetch_assoc($pfRes)) {
                $fqid = (int)$pf['questionId'];
            }
        }
    }

        // $x = [];
        // $x['peerFeedbackMap']= $peerFeedbackMap;
        // $x['peerReviewMap']= $peerReviewMap;
            //  $x['expertReviewMap']= $expertReviewMap;
        // $to_encode=$x;
        // echo json_encode($to_encode);
        // exit;

        // Hydrate
        $values = [];
        foreach ($rawRows as $row) {
            $qid = (int)$row['questionId'];
            $mid = $row['mergeId'];

            // Base enrichments
            // $row['percentile']          = $peerReviewMap[$qid]['percentile'] ?? 0;
            $row['questionHtml']        = nl2br($row['questionText']);
            $row['inorganicPeerWB']     = nl2br(htmlspecialchars($row['inorganicPeerWB']));
            $row['questionSource']      = $aspMap[$qid] ?? null;
            $row['shortExpectedAnsHtml']= nl2br($row['shortExpectedAns']);
            $row['whiteboard_text']     = nl2br(htmlspecialchars($wbMap[$qid] ?? ''));
            $row['htt']                 = $httMap[$qid] ?? null;
            $row['malpracticeValue']    = $malMap[$qid] ?? null;

            // Expert review
            if (isset($expertReviewMap[$qid])) {
                // $row = array_merge($row, $expertReviewMap[$qid]);
                $row['review_data'] = $expertReviewMap[$qid];
               $row['reviewreview_exists_data']  = 1;
            }else{
                $row['review_data'] = null;
               $row['reviewreview_exists_data']  = 0;

            }

            // Peer review
            if (isset($expertMap[$qid])) {
                $row = array_merge($row, $expertMap[$qid]);
            }


            // Peer response video details
            if (!empty($row['peerResponseVideo']) && isset($peerResponseMap[$row['peerResponseVideo']])) {
                $row['peerResponse_details'] = $peerResponseMap[$row['peerResponseVideo']];
            } else {
                $row['peerResponse_details'] = null;
            }

            // File status & avg time
            if ($mid) {
                $row['fileUploadStatus']   = $fileStatusMap[$mid]  ?? 'NULL';
                $row['averageTotalTime']   = $avgTimeMap[$mid]     ?? '00:00:00';
            }

            //
            // **Expert feedback (exactly as original)**
            //
            if (isset($feedbackMap[$qid]) && count($feedbackMap[$qid]) > 0) {
                if ($paymentStatus === 'PAID' || $userType === 'admin' || $interviewType === 'Practice' || $qid === $badScoreQuestion) {
                    $row['feedback_data']   = $feedbackMap[$qid];
                    $row['feedback_exists'] = 2;
                } else {
                    $combined = '';
                    foreach ($feedbackMap[$qid] as $fb) {
                        $combined .= $fb['feedbackSummary'] . "\n" . $fb['keyTopicExploration'] . "\n";
                    }
                    $row['feedback_data']   = null;
                    // Mask with 'x'
                    $row['feedback_text']   = preg_replace_callback('/[^\s]/', fn($m) => 'x', trim($combined));
                    $row['feedback_exists'] = 1;
                }
            } else {
                $row['feedback_data']   = null;
                $row['feedback_exists'] = 0;
            }

            //
            // **Peer feedback (exactly as original)**
            //

            // var_dump($peerFeedbackMap[$qid]);


            $values[] = $row;
        }

        // Sort & output & output
        usort($values, fn($a,$b)=> $a['questionId']<=>$b['questionId']);
        $to_encode=[
            'caseStudy' => $caseStudy,
            'questions' => $values,
        ];

    } catch(Exception $e) {
        if($e->getMessage()==='unAuthorized'){
            $to_encode=['status'=>-99,'result'=>'Not Authorized','errorCode'=>'Access Not Allowed'];
        } else {
            $to_encode=['status'=>-1,'result'=>'error','errorCode'=>'Error while retrieving review information'];
        }
    }

    echo json_encode($to_encode);
    exit;
}

elseif (isset($_GET['getMalpracticeSummary'])) {
    header('Content-Type: application/json');
    $raw = file_get_contents("php://input");
    $json = json_decode($raw, true);
    $to_encode = [];
    try {
        if (!is_array($json)) {
            throw new Exception('Invalid JSON');
        }
        $sessionId = $json['sessionId'];
        if (!$sessionId) {
        http_response_code(400);
        echo json_encode(["error" => "interviewSessionId is required"]);
        exit;
    }
    // echo $sessionId;
    // exit;
    $sql = "
        SELECT mv.malpracticeValue, COUNT(*) as count
        FROM mergedVideos mv
        JOIN AnswerTranscription at ON mv.mergeId = at.mergeId
        WHERE mv.interviewSessionId = ? AND ansText is not NULL
        GROUP BY mv.malpracticeValue
    ";

    $stmt = $databaseConnection->prepare($sql);
    $stmt->bind_param("s", $sessionId);
    $stmt->execute();
    $result = $stmt->get_result();

    $counts = [
        "GENUINE" => 0,
        "SUSPICIOUS" => 0,
        "MALPRACTICE" => 0
    ];

    while ($row = $result->fetch_assoc()) {
        $value = strtoupper($row["malpracticeValue"]);
        if (array_key_exists($value, $counts)) {
            $counts[$value] = (int)$row["count"];
        }
    }
    // echo $counts;
    $to_encode=['status'=>1,'result'=>$counts];

    }catch(Exception $e) {
        if($e->getMessage()==='unAuthorized'){
            $to_encode=['status'=>-99,'result'=>'Not Authorized','errorCode'=>'Access Not Allowed'];
        } else {
            $to_encode=['status'=>-1,'result'=>'error','errorCode'=>'Error while retrieving review information'];
        }
    }

    echo json_encode($to_encode);
    exit;
}

elseif (isset($_GET['getBestPeer'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    if (isset($json)) {
        try {
            $subjectId = isset($json['subjectId']) ? intval($json['subjectId']) : 0;
            $topicIds = isset($json['topicIds']) && is_array($json['topicIds']) ? $json['topicIds'] : [];

            $topicOrderCase = "";
            if (!empty($topicIds)) {
                $orderCases = [];
                foreach ($topicIds as $index => $id) {
                    $id = intval($id); // Ensure it's an integer
                    $orderCases[] = "WHEN $id THEN " . ($index + 1);
                }
                $topicOrderCase = "CASE q.topic_id " . implode(" ", $orderCases) . " ELSE 999 END,";
            }


            $peer_sql = "
                SELECT er.expert_review_suggestion,
                       er.overallRating,
                       er.id,
                       q.id as questionId,
                        q.topic_id,
                       er.feedbackVideoURL as expertOutputVideoURL,
                       m.youtubeId as feedbackVideoURL,
                       m.mergeId AS expertMergeId,
                       m.uploadStatus as expertUploadStatus,
                       er.feedbackGivenBy,
                       fsq.review_status,
                       er.interviewId,
                       er.candidateId,
                       iqt.questionId AS tranQuestionId,
                       fs.favourite_subject,
                        t.name AS topic_name,
                       iqt.attemptStatus,
                       ansT.ansText,
                       CASE 
                           WHEN iqt.attemptStatus IN ('Respond1', 'Idk1') THEN q.idk1
                           WHEN iqt.attemptStatus IN ('Respond2', 'Idk2') THEN q.idk2
                           ELSE q.questionText
                       END AS questionText,
                       SUBSTRING(SEC_TO_TIME(q.thinkingTime * 60), 1, 8) AS expectedThinkingTime,
                       q.shortExpectedAns,
                htt.howToThink as htt
                FROM expert_review er
                INNER JOIN feedback_status_question fsq ON fsq.feedbackRequestId = er.feedback_request_id AND fsq.questionId = er.questionId 
                LEFT OUTER JOIN mergedVideos m ON m.interviewId = er.interviewid AND m.questionId = er.questionId 
                LEFT JOIN questions q ON q.id = er.questionId
                LEFT JOIN howToThink htt ON htt.questionId = q.id
                LEFT JOIN interview_questions_transection iqt ON iqt.interviewId = m.interviewId AND m.questionId = iqt.questionId
                LEFT JOIN AnswerTranscription ansT ON ansT.mergeId = m.mergeId
                INNER JOIN favourite_subject fs ON fs.id = q.subjectId LEFT JOIN topic t ON t.id = q.topic_id
                LEFT JOIN expert_review_observation_feedback erof ON erof.interviewId = m.interviewId AND erof.questionId = m.questionId
                WHERE q.subjectId = '$subjectId'
                  AND er.review_type LIKE('question')
                  AND er.overallRating REGEXP '^[0-9]+(\\.[0-9]+)?$'
                  AND CAST(er.overallRating AS DECIMAL(10,2)) >= 5
                  AND htt.howToThink is not null
                GROUP BY er.questionId
                ORDER BY
                (erof.candidateThoughtProcess IS NOT NULL) DESC,
                $topicOrderCase CAST(er.overallRating AS DECIMAL(10,2)) DESC
                LIMIT 10
            ";
            // echo $peer_sql;


            $peer_querys = mysqli_query($databaseConnection, $peer_sql);

            $results = [];

            while ($row = mysqli_fetch_assoc($peer_querys)) {
                $row['questionHtml'] = nl2br($row['questionText']);
                $row['shortExpectedAnsHtml'] = nl2br($row['shortExpectedAns']);

                // Feedback
                $peer_feedback_sql = "SELECT * FROM expert_review_observation_feedback 
                                      WHERE interviewId = " . $row['interviewId'] . " 
                                      AND questionId = " . $row['questionId'];
                $peer_feedback_query = mysqli_query($databaseConnection, $peer_feedback_sql);

                if (mysqli_num_rows($peer_feedback_query) > 0) {
                    $row['feedback_data'] = mysqli_fetch_all($peer_feedback_query, MYSQLI_ASSOC);
                    $row['feedback_exists'] = 2;
                }

                // Percentile
                $percentileQuery = mysqli_query($databaseConnection, "
                    SELECT 
                        q.id AS questionId,
                        ks.key_skill AS skillName,
                        oa.observation_name AS oaname,
                        ov.observation_values AS skillScore,
                        ks.id AS key_skill_id,
                        t.name as topicName,
                        CASE
                            WHEN ov.observation_values = 'Technical Issue: Video not available' THEN 'NA'
                            ELSE ROUND((
                                SELECT COUNT(*)
                                FROM expert_review_observation_details AS inner_erod
                                INNER JOIN observation_area AS inner_oa ON inner_oa.id = inner_erod.observationAreaId
                                LEFT OUTER JOIN observation_values AS inner_ov ON inner_ov.id = inner_erod.observationValueId
                                WHERE inner_oa.observation_name = oa.observation_name 
                                  AND inner_ov.observation_values < ov.observation_values
                            ) / NULLIF((
                                SELECT COUNT(*)
                                FROM expert_review_observation_details AS inner_erod
                                INNER JOIN observation_area AS inner_oa ON inner_oa.id = inner_erod.observationAreaId
                                LEFT OUTER JOIN observation_values AS inner_ov ON inner_ov.id = inner_erod.observationValueId
                                WHERE inner_oa.observation_name = oa.observation_name
                            ), 0) * 100, 2)
                        END AS percentile
                    FROM expert_review_observation_details AS erod
                    INNER JOIN observation_area AS oa ON oa.id = erod.observationAreaId
                    INNER JOIN expert_review AS er ON er.id = erod.expertReviewId
                    INNER JOIN key_skill AS ks ON ks.id = oa.key_skill
                    LEFT OUTER JOIN observation_values AS ov ON ov.id = erod.observationValueId
                    LEFT JOIN questions q ON q.id = er.questionId
                    LEFT JOIN topic t ON t.id = q.topic_id
                    WHERE ks.key_skill NOT IN ('Pronunciation', 'Vocabulary', 'Fluency', 'Sentence Mastery')
                      AND er.questionid = " . $row['questionId'] . "
                      AND q.subjectId != 178
                      AND ks.status = 'Yes'
                    GROUP BY questionId
                ");

                $percentileData = mysqli_fetch_assoc($percentileQuery);
                if ($percentileData && isset($percentileData['percentile'])) {
                    $row['percentile'] = $percentileData['percentile'];
                    $row['topicName'] = $percentileData['topicName'];
                }

                $results[] = $row;
            }

            $to_encode = $results;

        } catch (Exception $e) {
            if ($e->getMessage() == "unAuthorized") {
                $to_encode = [
                    'status' => -99,
                    'result' => "Not Authorized",
                    'errorCode' => "Access Not Allowed"
                ];
            } else {
                $to_encode = [
                    'status' => -1,
                    'result' => "error",
                    'errorCode' => "Error while retrieving Review information"
                ];
            }
        }
    } else {
        $to_encode = [
            'status' => -1,
            'result' => "error",
            'errorCode' => "Error while retrieving review information."
        ];
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['getBestPeerTopics'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    if (isset($json)) {
        try {
            $subjectId = isset($json['subjectId']) ? intval($json['subjectId']) : 0;
            $userId = isset($json['userId']) ? intval($json['userId']) : 4;

            // $peer_querys = mysqli_query($databaseConnection, "SELECT DISTINCT t.id AS topicId, t.name AS topicName
            //     FROM (
            //         SELECT DISTINCT TRIM(SUBSTRING_INDEX(SUBSTRING_INDEX(scps.topics, ',', numbers.n), ',', -1)) AS topicId
            //         FROM scps_transaction scps
            //         JOIN (
            //             SELECT 1 AS n UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5
            //             UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9 UNION SELECT 10
            //             UNION SELECT 11 UNION SELECT 12 UNION SELECT 13 UNION SELECT 14 UNION SELECT 15
            //         ) numbers ON CHAR_LENGTH(scps.topics) - CHAR_LENGTH(REPLACE(scps.topics, ',', '')) >= numbers.n - 1
            //         WHERE scps.subject = '$subjectId'
            //         AND scps.topics IS NOT NULL 
            //         AND scps.topics != ''
            //     ) AS topic_ids
            //     JOIN topic t ON t.id = topic_ids.topicId
            //     ORDER BY t.id;");


            $peer_sql = "SELECT 
                    t.id AS topicId,
                    t.name AS topicName,
                    CASE
                        WHEN EXISTS (
                            SELECT 1
                            FROM questions q1
                            JOIN interview_questions_transection iqt1 ON iqt1.questionId = q1.id
                            JOIN interviewSchedule isch1 ON isch1.interviewId = iqt1.interviewId
                            WHERE q1.topic_id = t.id
                            AND isch1.candidate_id = $userId
                        ) THEN 'green'
                        WHEN EXISTS (
                            SELECT 1
                            FROM questions q2
                            JOIN interview_questions_transection iqt2 ON iqt2.questionId = q2.id
                            WHERE q2.topic_id = t.id
                        ) THEN 'black'
                        ELSE 'gray'
                    END AS status
                FROM (
                    SELECT DISTINCT TRIM(SUBSTRING_INDEX(SUBSTRING_INDEX(scps.topics, ',', numbers.n), ',', -1)) AS topicId
                    FROM scps_transaction scps
                    JOIN (
                        SELECT 1 AS n UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5
                        UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9 UNION SELECT 10
                        UNION SELECT 11 UNION SELECT 12 UNION SELECT 13 UNION SELECT 14 UNION SELECT 15
                    ) numbers ON CHAR_LENGTH(scps.topics) - CHAR_LENGTH(REPLACE(scps.topics, ',', '')) >= numbers.n - 1
                    WHERE scps.subject = '$subjectId'
                    AND scps.topics IS NOT NULL 
                    AND scps.topics != ''
                ) AS topic_ids
                JOIN topic t ON t.id = topic_ids.topicId
                ORDER BY
                    CASE
                        WHEN EXISTS (
                            SELECT 1
                            FROM questions q1
                            JOIN interview_questions_transection iqt1 ON iqt1.questionId = q1.id
                            JOIN interviewSchedule isch1 ON isch1.interviewId = iqt1.interviewId
                            WHERE q1.topic_id = t.id
                            AND isch1.candidate_id = $userId
                        ) THEN 1
                        WHEN EXISTS (
                            SELECT 1
                            FROM questions q2
                            JOIN interview_questions_transection iqt2 ON iqt2.questionId = q2.id
                            WHERE q2.topic_id = t.id
                        ) THEN 2
                        ELSE 3
                    END,
                    t.id;";

            // echo $peer_sql;

            $peer_querys = mysqli_query($databaseConnection, $peer_sql);

            $results = mysqli_fetch_all($peer_querys, MYSQLI_ASSOC);

            $to_encode = $results;

        } catch (Exception $e) {
            if ($e->getMessage() == "unAuthorized") {
                $to_encode = [
                    'status' => -99,
                    'result' => "Not Authorized",
                    'errorCode' => "Access Not Allowed"
                ];
            } else {
                $to_encode = [
                    'status' => -1,
                    'result' => "error",
                    'errorCode' => "Error while retrieving Review information"
                ];
            }
        }
    } else {
        $to_encode = [
            'status' => -1,
            'result' => "error",
            'errorCode' => "Error while retrieving review information."
        ];
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['getCandidateVideoInfo'])) {
    //Shrikant added : 18/3/2024
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    $interviewId = $json['interviewId'];
    $interviewSessionId = $json['interviewSessionId'];
    if (isset($json)) {
        $data = "SELECT
        fr.candidateId as candidateId,
        iqt.interviewId as interviewId,
        q.id as questionId,
      (
          SELECT id
          FROM AnswerTranscription AS ans
          JOIN mergedVideos AS mv ON ans.mergeId = mv.mergeId
          WHERE mv.interviewId = iqt.interviewId AND mv.questionId = q.id
          LIMIT 1
        ) AS answerId,
        iqt.Sequence as Sequence,
        iqt.sectionName as sectionName,
        fs.favourite_subject as subject,
        iqt.attemptStatus as AttemptStatus,
        t.name as topicName,
        er.overallRating as overall_score,
        GROUP_CONCAT(DISTINCT 
          CONCAT(ks.key_skill, ': ', ov.observation_values) 
          ORDER BY ks.key_skill ASC SEPARATOR ', ') as key_skill,
        q.questionText as questionText,
       qt.whiteboardText,
        (
          SELECT ansText
          FROM AnswerTranscription AS ans
          JOIN mergedVideos AS mv ON ans.mergeId = mv.mergeId
          WHERE mv.interviewId = iqt.interviewId AND mv.questionId = q.id
          LIMIT 1
        ) AS answerText
      FROM
        interview_questions_transection iqt 
      JOIN questions q ON q.id = iqt.questionId
      LEFT JOIN expert_review er ON er.questionId = q.id AND er.interviewId = iqt.interviewId
      LEFT JOIN favourite_subject fs ON fs.id = q.subjectId
      LEFT JOIN expert_review_observation_details as erod ON erod.expertReviewId = er.id
      LEFT JOIN observation_area as oa ON oa.id = erod.observationAreaId
      LEFT JOIN observation_values as ov ON ov.id = erod.observationValueId
      LEFT JOIN key_skill as ks ON ks.id = oa.key_skill
      LEFT JOIN feedback_request as fr on fr.interviewId=iqt.interviewId
      LEFT JOIN mergedVideos as m on m.interviewId=er.interviewId
      LEFT JOIN  questions_transection as qt on qt.questionId=q.id
      LEFT JOIN  preInterview as pr on pr.userId=fr.candidateId
      LEFT JOIN topic as t on t.id=q.topic_id
      WHERE
        er.interviewId=' " . $interviewId . " ' and iqt.sectionName !='ThankYou'
      GROUP BY
        q.id, iqt.Sequence, iqt.sectionName, fs.favourite_subject, iqt.attemptStatus
      ORDER BY
        iqt.Sequence;";


        $query = mysqli_query($databaseConnection, $data);
        $values = array();
        if (mysqli_num_rows($query) > 0) {
            while ($row = mysqli_fetch_assoc($query)) {
                $values[] = $row;
            }
        }
        $to_encode = $values;
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while retrieving video information."
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['covertToGuidanceVideo'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $expertReviewId = $json['expertReviewId'];
        $questionId = $json['questionId'];
        $expertOutputVideoURL = $json['expertOutputVideoURL'];
        $imagesNumber = $json['imagesNumber'];
        $videoNumber = $json['videoNumber'];
        $expertId = substr($expertOutputVideoURL, 7, (strpos($expertOutputVideoURL, "_", 7) - 7));

        $getGuidanceData = mysqli_query($databaseConnection, "select m.*, er.vidLength as videoLength from mergedVideos m inner join expert_review er on er.feedbackVideoURL = m.outputVideoURL where m.outputVideoURL = '" . $expertOutputVideoURL . "'");
        $guidanceResult = mysqli_fetch_assoc($getGuidanceData);

        $guidanceVideoQuery = "select * from questions_transection where questionId = '" . $questionId . "' and delegationType = 'guidanceVideo' ";
        $guidanceVideoResult = mysqli_query($databaseConnection, $guidanceVideoQuery);
        if (mysqli_num_rows($guidanceVideoResult)) {
            $guidanceQry = "UPDATE questions_transection SET expertId = '" . $expertId . "', uploadStatus = '2', vimeoId = '" . $guidanceResult['youtubeId'] . "', vidLength = '" . $guidanceResult['videoLength'] . "', noOfImages='" . $imagesNumber . "', noOfVideos = '" . $videoNumber . "' WHERE questionId = '" . $questionId . "' and delegationType = 'guidanceVideo'";
            $guidanceRes = mysqli_query($databaseConnection, $guidanceQry);
        } else {
            $guidanceQry = "INSERT INTO questions_transection(expertId, questionId, delegationType, uploadStatus, vimeoId, vidLength, noOfImages, noOfVideos) VALUES ('" . $expertId . "', '" . $questionId . "', 'guidanceVideo', '2', '" . $guidanceResult['youtubeId'] . "', '" . $guidanceResult['videoLength'] . "','" . $imagesNumber . "','" . $videoNumber . "')";
            $guidanceRes = mysqli_query($databaseConnection, $guidanceQry);
        }
        if ($guidanceRes === true) {
            $updateExpertReview = "update expert_review set feedbackVideoURL = NULL, vidLength = NULL, uploadStatus = NULL where id = '$expertReviewId'";
            $updateExpertReviewRes = mysqli_query($databaseConnection, $updateExpertReview);

            $updateQuestion = "update questions set expertAdvice = '" . $guidanceResult['youtubeId'] . "' where id = '" . $questionId . "'";
            $updateQuestionRes = mysqli_query($databaseConnection, $updateQuestion);

            if ($updateExpertReviewRes && $updateQuestionRes) {
                $to_encode = array(
                    'result' => "success",
                    'status' => 1
                );
            } else {
                $to_encode = array(
                    'result' => "error",
                    'status' => 0,
                    'errorCode' => "in Error while updating info."
                );
            }
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "in Error while updating information."
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while updating information.",
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getInterviewsForReview'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    $sql = "";
    if (isset($json)) {
        $candidateId = $json['candidateId'];
        $interviewId = $json['interviewId'];
        $interviewSessionId = $json['interviewSessionId'];
        $sql = "select q.questionText , m.* from questions q INNER JOIN mergedVideos m on q.youtubeId = m.questionVideoId and q.interviewId = m.interviewId and m.interviewId='" . $interviewId . "' and m.candidateId ='" . $candidateId . "'";

        $query = mysqli_query($databaseConnection, $sql);
        $values = mysqli_fetch_all($query, MYSQLI_ASSOC);
        $to_encode = $values;
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'sql' => $sql,
            'errorCode' => "out Error whire retrieving review information.",
            'sql' => $data
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['getInterviewsForEreview'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    $sql = "";
    if (isset($json)) {
        $candidateId = $json['candidateId'];
        $interviewId = $json['interviewId'];
        $interviewSessionId = $json['interviewSessionId'];
        $feedbackRequestId = $json['feedbackRequestId'];
        $expertId = $json['expertId'];
        $currentUserType = $json['currentUserType'];
        $values = array();
        $youtubeIdCount = array();

        if ($currentUserType === 'admin') {
            $sql = "select q.questionText, q.shortExpectedAns, q.quesDiagram, q.mbr_id, q.instruction, q.source, q.subjectId, q.isFollowUp, q.expertAdvice, m.*, fsq.expertId as feedbackProvidedBy, fs.favourite_subject as subjectName from questions q inner join interview_questions_transection iqt on iqt.questionId = q.id INNER JOIN mergedVideos m on q.id = m.questionId and iqt.interviewId = m.interviewId inner join feedback_request fr on fr.interviewSessionId = m.interviewSessionId inner join feedback_status_question fsq on fsq.feedbackRequestId = fr.id and fsq.questionId = m.questionId left outer join favourite_subject fs on fs.id = q.subjectId where m.interviewId = '" . $interviewId . "' and m.candidateId ='" . $candidateId . "' and m.interviewSessionId = '" . $interviewSessionId . "'";
        } else {
            $sql = "select q.questionText, q.shortExpectedAns, q.quesDiagram, q.mbr_id, q.instruction, q.source, q.subjectId, q.isFollowUp, q.expertAdvice, m.*, fsq.expertId as feedbackProvidedBy, fs.favourite_subject as subjectName from questions q inner join interview_questions_transection iqt on iqt.questionId = q.id INNER JOIN mergedVideos m on q.id = m.questionId and iqt.interviewId = m.interviewId inner join feedback_request fr on fr.interviewSessionId = m.interviewSessionId inner join feedback_status_question fsq on fsq.feedbackRequestId = fr.id and fsq.questionId = m.questionId left outer join favourite_subject fs on fs.id = q.subjectId where m.interviewId = '" . $interviewId . "' and m.candidateId ='" . $candidateId . "' and m.interviewSessionId = '" . $interviewSessionId . "' and fsq.review_status!=9 and fsq.review_status!=10 and (find_in_set(q.subjectId, (select areaOfExpertiseId from panel where id = '" . $expertId . "')) and (fsq.expertId is null or fsq.expertId = '" . $expertId . "') or fsq.expertId = '" . $expertId . "')";
            // echo $sql;
            $expertQuery = mysqli_query($databaseConnection, "select * from panel where id = '" . $expertId . "'");
            $expertDetails = mysqli_fetch_assoc($expertQuery);
        }

        $final_review_query = mysqli_query($databaseConnection, "select * from expert_review where interviewId=" . $interviewId . " and candidateId =" . $candidateId . " and review_type like 'Final Score' and feedback_request_id=" . $feedbackRequestId);
        $final_review_id = 0;

        if (mysqli_num_rows($final_review_query) > 0) {
            $final_review = mysqli_fetch_assoc($final_review_query);
            $final_review_id = $final_review['id'];
        }

        $query = mysqli_query($databaseConnection, $sql);
        while ($row = mysqli_fetch_assoc($query)) {
            $expert_review_query = mysqli_query($databaseConnection, "select er.*, m.youtubeId as feedbackVimeoId from expert_review er left outer join mergedVideos m on m.outputVideoURL = er.feedbackVideoURL where er.interviewId=" . $interviewId . " and er.candidateId =" . $candidateId . " and er.questionVideoId like '" . $row['questionVideoId'] . "' and er.questionId = '" . $row['questionId'] . "' and er.feedback_request_id=" . $feedbackRequestId);
            if (mysqli_num_rows($expert_review_query) > 0) {
                $expert_review = mysqli_fetch_assoc($expert_review_query);
                $expert_review_id = $expert_review['id'];
                $isTextReviewExist = $expert_review['review_param_valueId'] == NULL ? false : true;
                $feedbackVideoURL = $expert_review['feedbackVideoURL'];
                $feedbackVimeoId = $expert_review['feedbackVimeoId'];
            } else {
                $expert_review_id = 0;
                $feedbackVideoURL = null;
                $isTextReviewExist = false;
                $feedbackVimeoId = null;
            }
            $wbtext_query = mysqli_query($databaseConnection, "select wd.text from whiteboard w,whiteboard_details wd where w.interviewSessionId = '" . $interviewSessionId . "' and wd.whiteBoardId=w.whiteboardId and w.interviewId='" . $interviewId . "' and w.candidateId ='" . $candidateId . "' and w.questionVideoId='" . $row['questionVideoId'] . "' and w.questionId = '" . $row['questionId'] . "' order by wd.id desc limit 0,1");
            $wbdetails = mysqli_fetch_assoc($wbtext_query);
            if ($row['youtubeId'] == null) {
                $row['youtubeId'] = '314664775';
            }

            if ($row['source'] != null) {
                $aspCompaniesQuery = mysqli_query($databaseConnection, "SELECT q.source, group_concat(ac.name SEPARATOR ',') AS questionSource FROM questions q, aspiration_company ac WHERE FIND_IN_SET(ac.id, q.source) and q.id = '" . $row['questionId'] . "'");
                $aspCompaniesResult = mysqli_fetch_array($aspCompaniesQuery, MYSQLI_ASSOC);
                $row['questionSource'] = $aspCompaniesResult['questionSource'];
            } else {
                $row['questionSource'] = null;
            }

            if ($currentUserType === 'admin') {
                $row['isVideoApproved'] = 'Y';
            } else {
                $row['isVideoApproved'] = $expertDetails['isVideoApproved'];
            }

            $row['questionHtml'] = nl2br($row['questionText']);
            $row['shortExpectedAnsHtml'] = nl2br($row['shortExpectedAns']);
            $row['whiteboard_text'] = nl2br(htmlspecialchars($wbdetails['text']));
            $row['feedbackGivenBy'] = $row['feedbackProvidedBy'];
            $row['expert_review_id'] = $expert_review_id;
            $row['feedbackVideoURL'] = $feedbackVideoURL;
            $row['feedbackVimeoId'] = $feedbackVimeoId;
            $row['final_review_id'] = $final_review_id;
            $row['isTextReviewExist'] = $isTextReviewExist;

            array_push($values, $row);
        }

        foreach ($values as $key => $item) {

            if (isset($item['youtubeId'])) {
                $youtubeId = $item['youtubeId'];
                if (isset($youtubeIdCount[$youtubeId])) {
                    $youtubeIdCount[$youtubeId]++;
                    if ($youtubeIdCount[$youtubeId] === 2) {
                        // Append a random 9-digit number to the youtubeId
                        $randomYouTubeId = rand(100000000, 999999999);
                        $values[$key]['youtubeId'] = strval($randomYouTubeId);
                    }
                } else {
                    $youtubeIdCount[$youtubeId] = 1;
                }
            }
        }


        $getInterviewQuery = "select m.candidateId,u.firstName,m.interviewId,i.name FROM mergedVideos m INNER JOIN users u ON m.candidateId = u.id INNER JOIN interview i ON m.interviewId = i.id AND m.interviewId =  '" . $interviewId . "' AND m.candidateId =  '" . $candidateId . "' AND m.interviewSessionId =  '" . $interviewSessionId . "' GROUP BY u.id";
        $getInterviewResult = mysqli_query($databaseConnection, $getInterviewQuery);
        $interviewDetails = mysqli_fetch_assoc($getInterviewResult);
        array_push($values, $interviewDetails);

        // sibin aug 31 2022 for giving review for issue type malpractice also updating the observation details expertReviewId
        // $updateQuerymalpractice = mysqli_query($databaseConnection, "update expert_review_observation_details erod inner join expert_review er on erod.feedback_request_id=er.feedback_request_id set erod.expertReviewId = er.id where er.questionId = erod.questionId ");


        $to_encode = $values;
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving review information.",
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getProfessionalDetails'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['candidateId'];
        $mentorshipData = array();

        $data = "select p.*, u.firstName as candidateName, s.stream, c.collegeName, u.isMentee, ml.sessionStartDate, ml.hoursSpendPerWeek, ml.nextFollowUpDate, ml.remarks, ml.removeSubjects, ml.removeProgSubjects, ml.removeLifeSkillsSubjects, ml.assignedMentorsId, ml.planDuration, ml.sessionCompleted from professionaldetails p inner join stream s on p.specialization = s.id inner join users u on u.id = p.candidateId inner join colleges c on p.college = c.id left outer join menteelist ml on ml.candidateId = p.candidateId where p.candidateId='" . $candidateId . "' limit 1";
        $query = mysqli_query($databaseConnection, $data);

        if (mysqli_num_rows($query) > 0) {
            $mentorshipData = mysqli_fetch_array($query, MYSQLI_ASSOC);

            $progSkillQuery = mysqli_query($databaseConnection, "SELECT pd.fav_programming_skill, group_concat(fps.fav_prog_skill SEPARATOR ', ') AS fav_programming_skill_name FROM professionaldetails pd, fav_prog_skill fps WHERE FIND_IN_SET(fps.id, pd.fav_programming_skill) and candidateId = '" . $mentorshipData['candidateId'] . "'");
            $progSkillResult = mysqli_fetch_array($progSkillQuery, MYSQLI_ASSOC);
            $mentorshipData['fav_programming_skill_name'] = $progSkillResult['fav_programming_skill_name'];
            if (strpos($mentorshipData['fav_programming_skill_name'], "Others") !== false) {
                $mentorshipData['fav_programming_skill_name'] = str_replace("Others", $mentorshipData['other_prog_skills'], $mentorshipData['fav_programming_skill_name']);
            }

            $favSubjectsQuery = mysqli_query($databaseConnection, "SELECT pd.fav_subjects, group_concat(fs.favourite_subject SEPARATOR ', ') AS fav_subjects_name FROM professionaldetails pd, favourite_subject fs WHERE FIND_IN_SET(fs.id, pd.fav_subjects) and candidateId = '" . $mentorshipData['candidateId'] . "'");
            $favSubjectsResult = mysqli_fetch_array($favSubjectsQuery, MYSQLI_ASSOC);
            $mentorshipData['fav_subjects_name'] = $favSubjectsResult['fav_subjects_name'];
            if (strpos($mentorshipData['fav_subjects_name'], "Others") !== false) {
                $mentorshipData['fav_subjects_name'] = str_replace("Others", $mentorshipData['other_subjects'], $mentorshipData['fav_subjects_name']);
            }

            $aspCompaniesQuery = mysqli_query($databaseConnection, "SELECT pd.asp_companies, group_concat(ac.name SEPARATOR ', ') AS asp_companies_name FROM professionaldetails pd, aspiration_company ac WHERE FIND_IN_SET(ac.id, pd.asp_companies) and candidateId = '" . $mentorshipData['candidateId'] . "'");
            $aspCompaniesResult = mysqli_fetch_array($aspCompaniesQuery, MYSQLI_ASSOC);
            $mentorshipData['asp_companies_name'] = $aspCompaniesResult['asp_companies_name'];
            if (strpos($mentorshipData['asp_companies_name'], "Others") !== false) {
                $mentorshipData['asp_companies_name'] = str_replace("Others", $mentorshipData['other_companies'], $mentorshipData['asp_companies_name']);
            }

            $favDomainQuery = mysqli_query($databaseConnection, "SELECT pd.fav_domain, group_concat(fd.name SEPARATOR ', ') AS fav_domain_name FROM professionaldetails pd, favourite_domain fd WHERE FIND_IN_SET(fd.id, pd.fav_domain) and candidateId = '" . $mentorshipData['candidateId'] . "'");
            $favDomainResult = mysqli_fetch_array($favDomainQuery, MYSQLI_ASSOC);
            $mentorshipData['fav_domain_name'] = $favDomainResult['fav_domain_name'];
            if (strpos($mentorshipData['fav_domain_name'], "Others") !== false) {
                $mentorshipData['fav_domain_name'] = str_replace("Others", $mentorshipData['other_domain'], $mentorshipData['fav_domain_name']);
            }

            $languagesQuery = mysqli_query($databaseConnection, "SELECT pd.languages, group_concat(l.name SEPARATOR ', ') AS languages_name FROM professionaldetails pd, language l WHERE FIND_IN_SET(l.id, pd.languages) and candidateId = '" . $mentorshipData['candidateId'] . "'");
            $languagesResult = mysqli_fetch_array($languagesQuery, MYSQLI_ASSOC);
            $mentorshipData['languages_name'] = $languagesResult['languages_name'];

            $to_encode = $mentorshipData;
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "in Error while retrieving candidate information."
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while retrieving candidate information.",
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getInterviews'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $panelId = $json['panelId'];
        /*Custom Changes By Anil 30-09-2018*/
        //Changes By Saurabh 30-09-2018
        /*$companyData = "select id,companyId from panel where id = '" . $panelId . "'";
        $companyQuery = mysqli_query($databaseConnection, $companyData);
        $companyDetails = mysqli_fetch_assoc($companyQuery);*/
        //Changes By Saurabh 30-09-2018
        $data = "select * from `interview` where panelId='" . $panelId . "' and deleted_at is null  and isActive='Y'";
        /*Custom Changes By Anil 30-09-2018*/
        $query = mysqli_query($databaseConnection, $data);
        if (mysqli_num_rows($query) >= 1) {
            $values = array();
            $values = mysqli_fetch_all($query, MYSQLI_ASSOC);
            //array_push($values, $companyDetails['companyId']);
            $to_encode = $values;
        } else {
            $to_encode = array(
                'result' => "info",
                'status' => 0,
                'errorCode' => "No courses avaialble."
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while retrieving panel information."
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getInterviewsName'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $data = "select id, name, productId from `interview` where deleted_at is null and isActive='Y' order by name";
        $query = mysqli_query($databaseConnection, $data);
        if (mysqli_num_rows($query) >= 1) {
            $values = array();
            $values = mysqli_fetch_all($query, MYSQLI_ASSOC);
            $to_encode = $values;
        } else {
            $to_encode = array(
                'result' => "info",
                'status' => 0,
                'errorCode' => "No courses avaialble."
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while retrieving panel information."
        );
    }
    echo json_encode($to_encode);
}
// node-api
elseif (isset($_GET['getUserInfoAdmin'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $data = "select * from `users` where id='" . $userId . "'";
        $query = mysqli_query($databaseConnection, $data);
        if (mysqli_num_rows($query) >= 1) {
            $values = array();
            $professionaldetails = "select a.*, b.s_value from professionaldetails a left outer join scodes b on b.userId = a.candidateId and b.s_is_availed = 'Y' where a.candidateId='" . $userId . "' ";
            $professionaldetailsquery = mysqli_query($databaseConnection, $professionaldetails);
            if ($professionaldetailsquery) {
                $row = mysqli_fetch_assoc($query);
                $p_row = mysqli_fetch_assoc($professionaldetailsquery);
                $row['s_value'] = $p_row['s_value'];
                $row['qualification'] = $p_row['qualification'];
                $row['specialization'] = $p_row['specialization'];
                $row['college'] = $p_row['college'];
                $row['year'] = $p_row['year'];
                
                // ADD THIS: Fetch contactType from JobMailList if user type is college
                if ($row['usertype'] == 'college') {
                    $contactTypeQuery = "SELECT contactType FROM JobMailList WHERE emailId = '" . mysqli_real_escape_string($databaseConnection, $row['emailId']) . "' LIMIT 1";
                    $contactTypeResult = mysqli_query($databaseConnection, $contactTypeQuery);
                    if ($contactTypeResult && mysqli_num_rows($contactTypeResult) > 0) {
                        $contactRow = mysqli_fetch_assoc($contactTypeResult);
                        $row['contactType'] = $contactRow['contactType'];
                    } else {
                        $row['contactType'] = ''; // Default empty if not found
                    }
                }
                
                $values = $row;
                $to_encode = $values;
            } else {
                $to_encode = array(
                    'result' => "info",
                    'status' => 1,
                    'errorCode' => "Error while searching education details." . $professionaldetails
                );
            }
            //$values = mysqli_fetch_array($query, MYSQLI_ASSOC);
            /*Changes By Anil 23-09-2018*/
        } else {
            $to_encode = array(
                'result' => "info",
                'status' => 0,
                'errorCode' => "No users available."
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while retrieving panel information."
        );
    }

    echo json_encode($to_encode);
}
 elseif (isset($_GET['getUserInfo'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        // $userId = getDecrypt($json['token'])->userId;
        $candidateId = $json['candidateId'];
        $userId = $candidateId;
        $data = "select id,emailId,firstName,lastName,mobileNumber,userName,smsOtp,gender from `users` where id='" . $userId . "'";
        $query = mysqli_query($databaseConnection, $data);
        if (mysqli_num_rows($query) >= 1) {
            $values = array();
            $values = mysqli_fetch_all($query, MYSQLI_ASSOC);
            $to_encode = $values;
        } else {
            $to_encode = array(
                'result' => "info",
                'status' => 0,
                'errorCode' => "No users avaialble."
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error whire retrieving panel information."
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['createCategory'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $name = $json['name'];
        $description = $json['description'];
        $isActive = 'Y';
        $usersQuery = mysqli_query($databaseConnection, "INSERT INTO `categories` (`name`, `description`, `isActive`) VALUES ('$name', '$description', '$isActive');");
        if ($usersQuery) {
            $userId = mysqli_insert_id($databaseConnection);
            $to_encode = array(
                'result' => "Success",
                'message' => "Category Created.",
                'status' => 1
            );
        } else {
            $to_encode = array(
                'result' => "error",
                'errorCode' => "Category Creation failed.",
                'status' => 0
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Category Creation failed.",
            'status' => 0
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['signInGRouteCheckUser'])) {
    $uname = $_POST['email'];
    $data = "SELECT * FROM `users` WHERE emailId='" . $uname . "'";
    $query = mysqli_query($databaseConnection, $data);
    if (mysqli_num_rows($query) == 0) {
        $to_encode = array(
            'result' => "success",
            'message' => "User does not exists",
            'status' => "new"
        );
    } else {
        $row = mysqli_fetch_assoc($query);
        if (!empty($row['deleted_at'])) {
            $to_encode = array(
                'result' => "error",
                'message' => "User is deleted or does not exist on this platform",
                'status' => "deleted"
            );
        } else {
        $to_encode = array(
            'result' => "success",
            'message' => "User exists",
            'status' => "exists"
        );
        }
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['signInGRoute'])) {
    $client = new Google_Client(['client_id' => '578938807070-k6ubhrllnq2eeem794op6ff0o7h7s3t4.apps.googleusercontent.com']);  // Specify the CLIENT_ID of the app that accesses the backend
    $to_encode = array(
        'result' => "error",
        'errorCode' => "Invalid user details.",
        'query' => ""
    );
    $json = $client->verifyIdToken($_POST['idtoken']);

    if ($json) {
        $userid = $json['sub'];
        $uname = $json['email'];
        $data = "SELECT * FROM `users` WHERE emailId='" . $uname . "'";
        $query = mysqli_query($databaseConnection, $data);
        if (mysqli_num_rows($query) == 0) {
            $smsOtp = '1421';
            $password = password_hash(randomPassword(), PASSWORD_BCRYPT, ["cost" => 12]);
            $firstName = $json['given_name'];
            $lastName = $json['family_name'];
            $mobileNumber = 999999999;
            $email = $uname;
            $verificationLink = md5(rand(0, 1000));
            $verificationStatus = "Y";
            $isActive = "Y";
            $firstName = addslashes($firstName);
            $isAccepted_T_C = 'Yes';

            $insQuery = "INSERT INTO `users` (`userName`, `password`, `firstName`, `lastName`, `mobileNumber`, `emailId`, `active`, `smsOtp`, `verificationLink`, `verificationStatus`,`createdOn`,`isAccepted_T_C`) VALUES ('$uname', '$password', '$firstName', '$lastName', '$mobileNumber', '$email', '$isActive', '$smsOtp', '$verificationLink', '$verificationStatus', ROUND(UNIX_TIMESTAMP()*1000),'$isAccepted_T_C')";
            $usersQuery = mysqli_query($databaseConnection, $insQuery);
            if ($usersQuery) {
                $query1 = mysqli_query($databaseConnection, $data);
                if (mysqli_num_rows($query1) >= 1) {
                    $row = mysqli_fetch_assoc($query1);
                }
            }
        } else {
            $row = mysqli_fetch_assoc($query);
        }
        if ($row) {
            $email = $row['emailId'];
            $name = $row['firstName'];
            $mobile = $row['mobileNumber'];
            $roleId = $row['userRole'];
            $userId = $row['id'];
            $panelId = $row['panelId'];
            $userType = $row['usertype'];

            if (!empty($row['deleted_at'])) {
                $to_encode = array(
                    'result' => "error",
                    'message' => "User is deleted or does not exist on this platform",
                    'status' => "4"
                );
            } elseif ($row['verificationStatus'] == 'Y' && $row['active'] == 'Y' && $row['deleted_at'] == NULL) {
                if (isset($_SERVER['REMOTE_ADDR']))
                    $ipaddress = $_SERVER['REMOTE_ADDR'];
                else
                    $ipaddress = 'UNKNOWN';
                $to_encode = array(
                    'result' => "success",
                    'message' => "User Authenticated",
                    'status' => "1",
                    'email' => $email,
                    'name' => $name,
                    'mobile' => $mobile,
                    'userId' => $userId,
                    'roleId' => $roleId,
                    'panelId' => $panelId,
                    'usertype' => $userType,
                    'jwtToken' => getEncrypt('{
                        "email":"' . $email . '",
                        "name":"' . $name . '",
                        "mobile":"' . $mobile . '",
                        "userId":"' . $userId . '",
                        "usertype":"' . $userType . '",
                        "IP":"' . $ipaddress . '",
                        "timeStamp":"' . date("Y-m-d H:i:s") . '"
                    }')

                    //'companyId' => $companyId
                );
            } elseif ($row['verificationStatus'] == 'N' && $row['active'] == 'N') {
                if (isset($_SERVER['REMOTE_ADDR']))
                    $ipaddress = $_SERVER['REMOTE_ADDR'];
                else
                    $ipaddress = 'UNKNOWN';
                $to_encode = array(
                    'result' => "success",
                    'message' => "User Authenticated",
                    'status' => "5",
                    'onboarding' => "1",
                    'email' => $email,
                    'name' => $name,
                    'mobile' => $mobile,
                    'userId' => $userId,
                    'roleId' => $roleId,
                    'panelId' => $panelId,
                    'usertype' => $userType,
                    'jwtToken' => getEncrypt('{
                        "email":"' . $email . '",
                        "name":"' . $name . '",
                        "mobile":"' . $mobile . '",
                        "userId":"' . $userId . '",
                        "usertype":"' . $userType . '",
                        "IP":"' . $ipaddress . '",
                        "timeStamp":"' . date("Y-m-d H:i:s") . '"
                    }')
                );
            } elseif ($row['verificationStatus'] == 'N' && $row['active'] == 'Y') {
                $smsOtp = '1421';
                $updateQuery = "UPDATE `users` 
                    SET
                    `smsOtp` = '1421',
                    `verificationLink` = 'GOOGLE',
                    `verificationStatus` = 'Y'
                    WHERE
                    `id` = $userId";

                $usersQuery = mysqli_query($databaseConnection, $updateQuery);

                if ($usersQuery) {
                    // Update was successful
                    $query2 = mysqli_query($databaseConnection, $data);
                    if (mysqli_num_rows($query2) >= 1) {
                        if (isset($_SERVER['REMOTE_ADDR']))
                            $ipaddress = $_SERVER['REMOTE_ADDR'];
                        else
                            $ipaddress = 'UNKNOWN';
                        $to_encode = array(
                            'result' => "success",
                            'message' => "User Authenticated",
                            'status' => "1",
                            'verifyByGoogle' => "1",
                            'email' => $email,
                            'name' => $name,
                            'mobile' => $mobile,
                            'userId' => $userId,
                            'roleId' => $roleId,
                            'panelId' => $panelId,
                            'usertype' => $userType,
                            'jwtToken' => getEncrypt('{
                                "email":"' . $email . '",
                                "name":"' . $name . '",
                                "mobile":"' . $mobile . '",
                                "userId":"' . $userId . '",
                                "usertype":"' . $userType . '",
                                "IP":"' . $ipaddress . '",
                                "timeStamp":"' . date("Y-m-d H:i:s") . '"
                            }')
                        );
                    }
                } else {
                    // Handle the case where the update query fails
                    echo "Update failed: " . mysqli_error($databaseConnection);
                }

            }
        }
    } else {
        // Invalid ID token
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Invalid user details.",
            'query' => ""
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['signIn'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $password = $json['password'];
        $email = $json['emailId'];
        $User = explode(".", $email, 2);
        $Id = $User[0];
        $emailAdmin = $User[1];
        if ($emailAdmin == 'admin@goprac.com' && is_numeric($Id)) {
            $admin = "SELECT * FROM `users` WHERE emailId='id.admin@goprac.com' ";
            $adminQuery = mysqli_query($databaseConnection, $admin);
            if (mysqli_num_rows($adminQuery) >= 1) {
                $adminRow = mysqli_fetch_assoc($adminQuery);
                $adminHash = $adminRow['password'];
                if (password_verify($password, $adminHash)) {
                    $dataUser = "SELECT * FROM `users` WHERE id='" . $Id . "' ";
                    $Userquery = mysqli_query($databaseConnection, $dataUser);
                    if (mysqli_num_rows($Userquery) >= 1) {
                        $userRow = mysqli_fetch_assoc($Userquery);
                        if (!empty($userRow['deleted_at'])) {
                            $to_encode = array(
                                'result' => "error",
                                'message' => "User is deleted or does not exist on this platform",
                                'status' => "4"
                            );
                        } else {
                        $email = $userRow['emailId'];
                        $name = $userRow['firstName'];
                        $mobile = $userRow['mobileNumber'];
                        $roleId = $userRow['userRole'];
                        $userId = $userRow['id'];
                        $panelId = $userRow['panelId'];
                        $userType = $userRow['usertype'];
                        if (isset($_SERVER['REMOTE_ADDR']))
                            $ipaddress = $_SERVER['REMOTE_ADDR'];
                        else
                            $ipaddress = 'UNKNOWN';
                        $to_encode = array(
                            'result' => "success",
                            'message' => "User Authenticated",
                            'status' => "1",
                            'email' => $email,
                            'name' => $name,
                            'mobile' => $mobile,
                            'userId' => $userId,
                            'roleId' => $roleId,
                            'panelId' => $panelId,
                            'usertype' => $userType,
                            'jwtToken' => getEncrypt('{"email":"' . $email . '",
                                    "name":"' . $name . '",
                                    "mobile":"' . $mobile . '",
                                    "userId":"' . $userId . '",
                                    "usertype":"' . $userType . '",
                                    "IP":"' . $ipaddress . '",
                                    "timeStamp":"' . date("Y-m-d H:i:s") . '"
                                }')
                            // "roleId":"'.$roleId.'",
                            // "panelId":"'.$panelId.'",
                            //'companyId' => $companyId
                        );
                        }
                    } else {
                        $to_encode = array(
                            'result' => "error",
                            'errorCode' => "user Id Not Exit.",
                            'query' => $dataUser
                        );
                    }
                } else {
                    $to_encode = array(
                        'result' => "error",
                        'errorCode' => "Invalid Admin Password.",
                        'query' => $data
                    );
                }
            } else {
                $to_encode = array(
                    'result' => "error",
                    'errorCode' => "Admin Not Exist.",
                    'query' => $admin
                );
            }
        } else {
            $data = "SELECT * FROM `users` WHERE emailId='" . $email . "' ";
            $query = mysqli_query($databaseConnection, $data);
            if (mysqli_num_rows($query) >= 1) {
                $row = mysqli_fetch_assoc($query);
                $hash = $row['password'];
                if (password_verify($password, $hash)) {
                    $email = $row['emailId'];
                    $name = $row['firstName'];
                    $mobile = $row['mobileNumber'];
                    $roleId = $row['userRole'];
                    $userId = $row['id'];
                    $panelId = $row['panelId'];
                    $userType = $row['usertype'];
                    if (!empty($row['deleted_at'])) {
                        $to_encode = array(
                            'result' => "error",
                            'message' => "User is deleted or does not exist on this platform",
                            'status' => "4"
                        );
                    } elseif ($row['verificationStatus'] == 'Y' && $row['active'] == 'Y' && $row['deleted_at'] == NULL) {
                        if (isset($_SERVER['REMOTE_ADDR']))
                            $ipaddress = $_SERVER['REMOTE_ADDR'];
                        else
                            $ipaddress = 'UNKNOWN';
                        $to_encode = array(
                            'result' => "success",
                            'message' => "User Authenticated",
                            'status' => "1",
                            'email' => $email,
                            'name' => $name,
                            'mobile' => $mobile,
                            'userId' => $userId,
                            'roleId' => $roleId,
                            'panelId' => $panelId,
                            'usertype' => $userType,
                            'jwtToken' => getEncrypt('{
                                "email":"' . $email . '",
                                "name":"' . $name . '",
                                "mobile":"' . $mobile . '",
                                "userId":"' . $userId . '",
                                "usertype":"' . $userType . '",
                                "IP":"' . $ipaddress . '",
                                "timeStamp":"' . date("Y-m-d H:i:s") . '"
                            }')
                            //'companyId' => $companyId
                        );
                    } elseif ($row['verificationStatus'] == 'N') {
                        // } elseif ($row['verificationStatus'] == 'S') {
                        $to_encode = array(
                            'result' => "info",
                            'message' => "User account not verified",
                            'status' => "2",
                            'email' => $email,
                        );
                    } else {
                        $to_encode = array(
                            'result' => "error",
                            'message' => "Invalid user details or User account not active",
                            // 'status' => "3",
                            // 'email' => $email,
                        );
                    }
                } else {
                    $to_encode = array(
                        'result' => "error",
                        'errorCode' => "Invalid User password.",
                        'query' => $data
                    );
                }
            } else {
                $to_encode = array(
                    'result' => "error",
                    'errorCode' => "Invalid User Email.",
                    'query' => $data
                );
            }
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Invalid user details."
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['signInOtp'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $smsOtp = $json['smsOtp'];
        $mobileNumber = $json['mobileNumber'];
        $data = "select * from `users` where mobileNumber='" . $mobileNumber . "' and smsOtp='" . $smsOtp . "'";
        $query = mysqli_query($databaseConnection, $data);
        if (mysqli_num_rows($query) >= 1) {
            $row = mysqli_fetch_assoc($query);
            if (!empty($row['deleted_at'])) {
                $to_encode = array(
                    'result' => "error",
                    'message' => "User is deleted or does not exist on this platform",
                    'status' => "4"
                );
            } else {
                $email = $row['emailId'];
                $name = $row['firstName'];
                $mobile = $row['mobileNumber'];
                $userId = $row['id'];
                $to_encode = array(
                    'result' => "success",
                    'message' => "User Authenticated",
                    'status' => "1",
                    'email' => $email,
                    'name' => $name,
                    'mobile' => $mobile,
                    'userId' => $userId
                );
            }
        } else {
            $to_encode = array(
                'result' => "error",
                'errorCode' => "Invalid user details."
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Invalid user details."
        );
    }
    echo json_encode($to_encode);


} elseif (isset($_GET['signUp'])) {
    // @sourabh
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $uname = $json['emailId'];
        $smsOtp = '1421';
        $password = password_hash($json['password'], PASSWORD_BCRYPT, ["cost" => 12]);
        $firstName = $json['firstName'];
        $lastName = '';
        $email = $json['emailId'];
        $source = $json['source'];
        $companySource = $json['companySource'] === null ? 'NULL' : $json['companySource'];
        $verificationLink = md5(rand(0, 1000));
        $verificationStatus = "N";
        $isActive = "Y";
        $firstName = addslashes($firstName);
        $isAccepted_T_C = 'Yes';
        $isMentee = ($source == "/mentorship-form") ? "Y" : "N";
        $usertype = ($source == "/expert-form") ? "expert" : "student";

        if ($firstName != '' && $email != '' && $password != '') {
            if (isset($json['id_token']) and isset($json['loginRoute']) and $json['loginRoute'] == 'GOOGLE') {
                $client = new Google_Client(['client_id' => '578938807070-k6ubhrllnq2eeem794op6ff0o7h7s3t4.apps.googleusercontent.com']);  // Specify the CLIENT_ID of the app that accesses the backend
                $jsonGoogle = $client->verifyIdToken($json['id_token']);

                if ($jsonGoogle) {
                    $password = password_hash(randomPassword(), PASSWORD_BCRYPT, ["cost" => 12]);
                    $verificationLink = "GOOGLE";
                    $verificationStatus = "Y";
                }
            }
            $data = "select * from `users` where emailId='" . $email . "'";
            $query = mysqli_query($databaseConnection, $data);
            if (mysqli_num_rows($query) >= 1) {
                $row = mysqli_fetch_assoc($query);
                $verifStatus = $row['verificationStatus'];

                if ($verifStatus !== 'Y') {
                    $to_encode = array(
                        'result' => "info",
                        'response' => 'Profile Already Exists Please Verify your account!!',
                        'status' => 3,
                        'email' => $row['emailId']
                    );

                } else {

                    $to_encode = array(
                        'result' => "error",
                        'response' => 'Profile Already Exists !!',
                        'status' => 0
                    );
                }
            } else {
                $sqlQuery = "INSERT INTO `users` (`userName`, `password`, `firstName`, `lastName`, `emailId`, `active`, `smsOtp`, `verificationLink`, `verificationStatus`,`createdOn`,`isAccepted_T_C`, `isMentee`, `usertype`, `profile_updated`,`source`) VALUES ('$uname', '$password', '$firstName', '$lastName', '$email', '$isActive', '$smsOtp', '$verificationLink', '$verificationStatus', ROUND(UNIX_TIMESTAMP()*1000),'$isAccepted_T_C', '$isMentee', '$usertype','N',$companySource)";
                $usersQuery = mysqli_query($databaseConnection, $sqlQuery);
                if ($usersQuery) {
                    $userId = mysqli_insert_id($databaseConnection);
                    $subs = "select id from `users` where emailId='" . $email . "'";
                    $subsQuery = mysqli_query($databaseConnection, $subs);
                    $subResult = mysqli_fetch_assoc($subsQuery);
                    $amount = 0;
                    $duration = '15 days';
                    $date = date("Y-m-d");
                    $endDate = date('Y-m-d', strtotime($date . ' + 15 days'));
                    $product = array();
                    $pQuery = "Select productId from interview where categoryType='8' group by productId";
                    $pResult = mysqli_query($databaseConnection, $pQuery);
                    while ($row = mysqli_fetch_assoc($pResult)) {
                        $product[] = $row['productId'];
                    }
                    $productId = implode(',', $product);
                    $Subscription = "INSERT INTO `subscription` (`candidateId`, `amount`,`duration`,`startDate`,`endDate`,`productId`,`mockInterviewAllowed`, `communicationInterviewAllowed`, `behaviouralInterviewAllowed`, `problemsolvingInterviewAllowed`, `codingInterviewAllowed`,`freeTrialAllowed`) VALUES ('" . $subResult['id'] . "', '$amount', '$duration', NOW(),NOW() +  INTERVAL 15 DAY, '$productId','0','0','0','0','0','2')";
                    $Query = mysqli_query($databaseConnection, $Subscription);

                    $pd = "INSERT INTO `professionaldetails` (`candidateId`) VALUES ('" . $subResult['id'] . "')";
                    $pd_query = mysqli_query($databaseConnection, $pd);

                    /*added by saurabh 28-May-2021  
                    to create expert account if sign up through link expert-form*/
                    if ($usertype === 'expert') {
                        $panelquery = "INSERT INTO `panel` (`name`, `oraganisation`, `emailId`, `phonenumber`, `panelTitle`,`expertStatus`,`publishStatus`,`communicationSkill`) select u.firstName, c.collegeName, u.emailId, u.mobileNumber, u.firstName, '0' as expertStatus, '0' as publishStatus,pd.communicationSkillRate from users u inner join professionaldetails pd on pd.candidateId = u.id inner join colleges c on c.id = pd.college WHERE u.id=" . $userId;
                        mysqli_query($databaseConnection, $panelquery);
                        $expertId = mysqli_insert_id($databaseConnection);
                        $panelResult = mysqli_query($databaseConnection, "update users SET panelId='" . $expertId . "' WHERE id=" . $userId);

                        $panelsTransectionInsert = "INSERT INTO `panels_transection`(`panelId`) VALUES ('" . $expertId . "')";
                        $panelsTransection_result = mysqli_query($databaseConnection, $panelsTransectionInsert);
                    }
                    $to_encode = array(
                        'result' => "Success",
                        'userId' => $userId,
                        'response' => 'User Created Successfully.',
                        'status' => 1
                    );

                    if ($verificationLink != 'GOOGLE') {
                        $source = ($source == "/expert-form") ? $source . '?login=1' : $source;
                        $verifyLink = $emailApiHost . "/verification?id=" . $verificationLink . "&email=" . $email . "&source=" . $source;
                        accountCreationEmail($firstName, $email, $verifyLink);
                    }
                } else {
                    $error = date('[l, d M Y h:i:s A] :') . ' Unable to sign up, candidate details - Email id : ' . $email . ', Mobile Number : ' . $mobileNumber . ', Name : ' . $firstName;
                    if ($server == 'live') {
                        error_log($error . "\n", 3, "../../../home/ubuntu/error.log");
                    }
                    $mailSubject = $emailApiHost . ' - Issue while signed up';
                    sendRecordingErrorEmail($error, $emailApiHost, $mailSubject);
                    $to_encode = array(
                        'result' => "error",
                        'errorCode' => "User Creation failed.",
                        'query' => $sqlQuery,
                        'status' => -1
                    );
                }
            }
        } else {
            $to_encode = array(
                'result' => "error",
                'errorCode' => "Please enter the details",
                'status' => -2
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "User Creation failed.",
            'status' => -1
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['isProfileUpdated'])) {
    // @ sourabh - new signup
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {

        $id = $json['id'];

        $data = "select * from `users` where id='" . $id . "'";
        $query = mysqli_query($databaseConnection, $data);


        if (mysqli_num_rows($query) >= 1) {
            $row = mysqli_fetch_assoc($query);
            $candidateId = $row['id'];
            $profile_updated = $row['profile_updated'];
            $data = array(
                'profile_updated' => $profile_updated,
            );

            $to_encode = array(
                'result' => "success",
                'data' => $data,
                'status' => 1
            );
        } else {
            $to_encode = array(
                'result' => "error",
                'errorCode' => "User not found",
                'status' => -3
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "User Creation failed.",
            'status' => -1
        );
    }

    echo json_encode($to_encode);
}
elseif (isset($_GET['getProfessionalDetailsOnSignUp'])) {
    // @ sourabh - new signup
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {

        $id = $json['id'];

        $data = "select * from `users` where id='" . $id . "'";
        $query = mysqli_query($databaseConnection, $data);
        if (mysqli_num_rows($query) >= 1) {
            $row = mysqli_fetch_assoc($query);
            $candidateId = $row['id'];
            $profile_updated = $row['profile_updated'];
            // echo $candidateId;
            // exit();

            // $scheduleField = mysqli_query($databaseConnection, "select id,emailId,preInterviewId, pd_update_at from interviewSchedule where emailId in (select emailId from users where id = " . $candidateId . ")");

            $scheduleField = mysqli_query($databaseConnection, "SELECT *
                    FROM interviewSchedule
                    WHERE emailId IN (
                        SELECT emailId
                        FROM users
                        WHERE id = " . $candidateId . "
                    )
                    ORDER BY id DESC limit 1
                ");


            if (mysqli_num_rows($scheduleField) >= 1) {
                $scheduleFieldResult = mysqli_fetch_all($scheduleField, MYSQLI_ASSOC);
                if ($scheduleFieldResult[0]['id'] != null) {
                    // updating professionaldetails from interviewSchedule table
                    // print_r($scheduleFieldResult[0]['id']);


                    $respMessage;

                    $data = "select * from `professionaldetails` where candidateId='" . $candidateId . "'";
                    $query = mysqli_query($databaseConnection, $data);
                    if (mysqli_num_rows($query) >= 1) {
                        $pdUpdateAtFieldResult = mysqli_fetch_all($query, MYSQLI_ASSOC);

                        // print_r($pdUpdateAtFieldResult[0]);
                        // exit();

                        $datepd = new DateTime($pdUpdateAtFieldResult[0]['updateAt']);
                        $dateis = new DateTime($scheduleFieldResult[0]['recruiterScheduleDate']);

                        // print_r($dateis);
                        //$scheduleFieldResult[0]['recruiterScheduleDate'] == null || 

                        if (
                            $pdUpdateAtFieldResult[0]['updateAt'] == null || $scheduleFieldResult[0]['submissionFlag'] == "NA" ||
                            $scheduleFieldResult[0]['submissionFlag'] == "WA" || ($scheduleFieldResult[0]['recruiterScheduleDate'] != null && ($datepd < $dateis))
                        ) {

                            // var_dump($datepd);
                            // var_dump($dateis);

                            $updateProfessionaldetails_sql = "UPDATE professionaldetails pd
                                JOIN users u ON u.id = pd.candidateId
                                SET ";

                            // Mapping array to map field names in $scheduleFieldResult to column names in the table
                            $fieldMapping = array(
                                'workExperience' => 'workExperience',
                                'jobType' => 'jobType',
                                'currentCompany' => 'currentCompany',
                                'currentProcess' => 'currentProcess',
                                'processType' => 'processType',
                                'clientType' => 'clientType',
                                'salary' => 'salary',
                                'expectedSalary' => 'expectedSalary',
                                'noticePeriod' => 'noticePeriod',
                                'processPreference' => 'processPreference',
                                'shift' => 'shift',
                                'workLocationPreference' => 'workLocationPreference',
                                'timeToCall' => 'timeToCall',
                                'preferedJobType' => 'preferedJobType',
                                'currentLocation' => 'currentLocation',
                                'preferredWorkLocation' => 'preferredWorkLocation',
                                'languages' => 'languages',
                                'joiningTimeline' => 'joiningTimeline',
                                'preferredrole' => 'preferredRole',
                                'joinstatus' => 'joinstatus',
                                'resume' => 'resume',
                                'employmentStatus' => 'employmentStatus',
                                'skillValues' => 'skills'
                            );

                            foreach ($fieldMapping as $scheduleField => $dbColumn) {
                                // Check if the field is not empty before including it in the update statement
                                if (isset($scheduleFieldResult[0][$scheduleField]) && !empty($scheduleFieldResult[0][$scheduleField])) {
                                    $updateProfessionaldetails_sql .= "pd.$dbColumn = '" . $scheduleFieldResult[0][$scheduleField] . "',";
                                }
                            }

                            $updateProfessionaldetails_sql .= "pd.updateAt = NOW()
                                WHERE u.id = " . $id;

                            $updateProfessionaldetails = mysqli_query($databaseConnection, $updateProfessionaldetails_sql);

                            $respMessage = $updateProfessionaldetails ? 'updated' : 'update error';

                            if (!empty($scheduleFieldResult[0]['mobileNumber'])) {
                                $updateMobile_sql = "UPDATE users SET mobileNumber = '" . $scheduleFieldResult[0]['mobileNumber'] . "' WHERE id='" . $id . "'";
                                $updateMobile = mysqli_query($databaseConnection, $updateMobile_sql);
                                // if ($updateMobile) {
                                //     $respMessage = 'Mobile number updated';
                                // } else {
                                //     $respMessage = 'Error updating mobile number';
                                // }
                            }


                        } else {
                            $respMessage = 'already updated';
                        }


                    } else {
                        $insertProfessionaldetails_sql = "INSERT INTO professionaldetails (
                            candidateId, workExperience, jobType, currentCompany, currentProcess, processType,
                            clientType, salary, expectedSalary, noticePeriod, processPreference, shift,
                            workLocationPreference, timeToCall, preferedJobType, currentLocation,
                            preferredWorkLocation, languages, joiningTimeline,
                            preferredRole, joinstatus, resume, skills, updateAt
                        ) VALUES (
                            " . $id . ",
                            '" . $scheduleFieldResult[0]['workExperience'] . "',
                            '" . $scheduleFieldResult[0]['jobType'] . "',
                            '" . $scheduleFieldResult[0]['currentCompany'] . "',
                            '" . $scheduleFieldResult[0]['currentProcess'] . "',
                            '" . $scheduleFieldResult[0]['processType'] . "',
                            '" . $scheduleFieldResult[0]['clientType'] . "',
                            '" . $scheduleFieldResult[0]['currentSalary'] . "',
                            '" . $scheduleFieldResult[0]['expectedSalary'] . "',
                            '" . $scheduleFieldResult[0]['noticePeriod'] . "',
                            '" . $scheduleFieldResult[0]['processPreference'] . "',
                            '" . $scheduleFieldResult[0]['shift'] . "',
                            '" . $scheduleFieldResult[0]['workLocationPreference'] . "',
                            '" . $scheduleFieldResult[0]['timeToCall'] . "',
                            '" . $scheduleFieldResult[0]['preferedJobType'] . "',
                            '" . $scheduleFieldResult[0]['currentLocation'] . "',
                            '" . $scheduleFieldResult[0]['preferredWorkLocation'] . "',
                            '" . $scheduleFieldResult[0]['languages'] . "',
                            '" . $scheduleFieldResult[0]['joiningTimeline'] . "',
                            '" . $scheduleFieldResult[0]['preferredrole'] . "',
                            '" . $scheduleFieldResult[0]['joinstatus'] . "',
                            '" . $scheduleFieldResult[0]['resume'] . "',
                            '" . $scheduleFieldResult[0]['skillValues'] . "',
                            NOW()
                        )";


                        // skills, certifications
                        // '" . $scheduleFieldResult[0]['skillValues'] . "',
                        // '" . $scheduleFieldResult[0]['certiValues'] . "',

                        $insertProfessionaldetails = mysqli_query($databaseConnection, $insertProfessionaldetails_sql);

                        $respMessage = $insertProfessionaldetails ? 'inserted' : 'insert error';

                        if (!empty($scheduleFieldResult[0]['mobileNumber'])) {
                            $updateMobile_sql = "UPDATE users SET mobileNumber = '" . $scheduleFieldResult[0]['mobileNumber'] . "' WHERE id='" . $id . "'";
                            $updateMobile = mysqli_query($databaseConnection, $updateMobile_sql);
                            // if ($updateMobile) {
                            //     $respMessage = 'Mobile number updated';
                            // } else {
                            //     $respMessage = 'Error updating mobile number';
                            // }
                        }


                    }

                    $resultRowArray;

                    $data2 = "SELECT professionaldetails.*, users.mobileNumber FROM professionaldetails JOIN users on professionaldetails.candidateId = users.id WHERE candidateId='" . $candidateId . "'";

                    // echo $data2;
                    // exit();
                    $query2 = mysqli_query($databaseConnection, $data2);

                    if (mysqli_num_rows($query2) >= 1) {
                        $resultRowArray = mysqli_fetch_assoc($query2);
                    } else {
                        $resultRowArray = null;
                    }
                    if (isset($resultRowArray['currentLocation']) && $resultRowArray['currentLocation'] !== "") {
                        $data3 = "SELECT cityName FROM locations WHERE id='" . $resultRowArray['currentLocation'] . "'";

                        $query3 = mysqli_query($databaseConnection, $data3);

                        if (mysqli_num_rows($query3) >= 1) {
                            $resultRowArray3 = mysqli_fetch_assoc($query3);  // Corrected $query2 to $query3
                            $resultRowArray['currentLocationCityName'] = $resultRowArray3['cityName'];
                        } else {
                            $resultRowArray['currentLocationCityName'] = null;
                        }
                    } else {
                        $resultRowArray['currentLocationCityName'] = null;
                    }

                    if (isset($resultRowArray['skills']) && $resultRowArray['skills'] !== "") {
                        // Prepare the SQL query
                        // "select *, favourite_subject.favourite_subject as name from favourite_subject where active='Y' "
                        $data4 = "SELECT id, favourite_subject.favourite_subject as name FROM favourite_subject WHERE active='Y' and id IN(" . $resultRowArray['skills'] . ")";

                        // echo $data4;

                        // Execute the query
                        $query4 = mysqli_query($databaseConnection, $data4);

                        if (mysqli_num_rows($query4) >= 1) {
                            $resultRowArray4 = [];

                            while ($row = mysqli_fetch_assoc($query4)) {
                                $resultRowArray4[] = $row;
                            }
                            $resultRowArray['skillList'] = $resultRowArray4;
                        } else {

                            $resultRowArray['skillList'] = null;
                        }

                    } else {
                        $resultRowArray['skillList'] = null;
                    }


                    // print_r($resultRowArray);
                    // exit();


                    $to_encode = array(
                        'result' => "success",
                        'data' => $resultRowArray,
                        'message' => $respMessage,
                        'status' => 1
                    );


                }
            } else {
                $resultRowArray;
                //$data2 = "SELECT professionaldetails.*, users.mobileNumber , users.gender, colleges.collegeName FROM professionaldetails JOIN users on professionaldetails.candidateId = users.id  LEFT JOIN colleges ON professionaldetails.college = colleges.id WHERE candidateId='" . $candidateId . "'";
                $data2 = "SELECT professionaldetails.*, users.mobileNumber FROM professionaldetails INNER JOIN users on professionaldetails.candidateId = users.id WHERE candidateId='" . $candidateId . "'";

                $query2 = mysqli_query($databaseConnection, $data2);

                if (mysqli_num_rows($query2) >= 1) {
                    $resultRowArray = mysqli_fetch_assoc($query2);
                } else {
                    $resultRowArray = null;
                }

                if (isset($resultRowArray['skills']) && $resultRowArray['skills'] !== "") {

                    $data4 = "SELECT id, favourite_subject.favourite_subject as name FROM favourite_subject WHERE active='Y' and id IN(" . $resultRowArray['skills'] . ")";

                    $query4 = mysqli_query($databaseConnection, $data4);

                    if (mysqli_num_rows($query4) >= 1) {
                        $resultRowArray4 = [];

                        while ($row = mysqli_fetch_assoc($query4)) {
                            $resultRowArray4[] = $row;
                        }
                        $resultRowArray['skillList'] = $resultRowArray4;
                    } else {

                        $resultRowArray['skillList'] = null;
                    }

                } else {
                    $resultRowArray['skillList'] = null;
                }

                $to_encode = array(
                    'data' => $resultRowArray,
                    'result' => "success",
                    'message' => "is not forund",
                    'status' => 1
                );
            }


        } else {
            $to_encode = array(
                'result' => "error",
                'errorCode' => "User not found",
                'status' => -3
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "User Creation failed.",
            'status' => -1
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['aboutYouSection'])) {
    // @ sourabh - new signup
    // & dec 2023 - not used
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {

        $user_id = $json['userId'];

        if (is_array($json['goal'])) {
            $goal = implode(',', $json['goal']);
        } else {
            $goal = $json['goal'];
        }

        if ($user_id != '' && $goal != '') {

            $data = "select * from `users` where id='" . $user_id . "'";
            $query = mysqli_query($databaseConnection, $data);
            if (mysqli_num_rows($query) >= 1) {
                $row = mysqli_fetch_assoc($query);
                $candidateId = $row['id'];

                $data = "select * from `professionaldetails` where candidateId='" . $candidateId . "'";
                $query = mysqli_query($databaseConnection, $data);
                if (mysqli_num_rows($query) >= 1) {
                    $row = mysqli_fetch_assoc($query);
                    // $id = $row['id'];

                    $pdSql = "UPDATE `professionaldetails` SET `goal`='$goal' WHERE `candidateId`='$candidateId'";
                    $pdQuery = mysqli_query($databaseConnection, $pdSql);

                    if (!$pdQuery) {
                        // Handle query error
                        $to_encode = array(
                            'result' => "error",
                            'error' => "Error in professional details query: " . mysqli_error($databaseConnection),
                            'status' => -4
                        );
                    } else {
                        $to_encode = array(
                            'result' => "success",
                            'status' => 1
                        );
                    }
                } else {
                    $pdSql = "INSERT INTO `professionaldetails` (`candidateId`, `goal`) VALUES ('$candidateId', '$goal')";
                    $pdQuery = mysqli_query($databaseConnection, $pdSql);

                    if (!$pdQuery) {
                        // Handle query error
                        $to_encode = array(
                            'result' => "error",
                            'error' => "Error in professional details query: " . mysqli_error($databaseConnection),
                            'status' => -4
                        );
                    } else {
                        $to_encode = array(
                            'result' => "success",
                            'status' => 1
                        );
                    }

                }
            } else {
                $to_encode = array(
                    'result' => "error",
                    'errorCode' => "User not found",
                    'status' => -3
                );
            }
        } else {
            $to_encode = array(
                'result' => "error",
                'errorCode' => "Please enter the details",
                'status' => -2
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "User Creation failed.",
            'status' => -1
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['personalDetailsSection'])) {
    // @ sourabh - new signup
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {

        $user_id = $json['userId'];
        $mobileNumber = $json['mobileNumber'];

        $workExperience = $json['workExperience'] ?? "NULL";
        $salary = $json['salary'] ?? "NULL";
        $expectedSalary = $json['expectedSalary'] ?? "NULL";
        $roleId = $json['roleId'] ?? "NULL";
        $subjectId = $json['subjectId'] ?? "NULL";
        $skills = $json['skills'] ?? "NULL";


        if ($skills == "NULL" || $skills == '' || empty($json['skills'])) {

            $to_encode = array(
                'result' => "error",
                'errorCode' => "Please Select Skills",
                'status' => -4
            );



        } else {

            if ($mobileNumber != '' && $user_id != '') {

                $data = "select * from `users` where id='" . $user_id . "'";
                $query = mysqli_query($databaseConnection, $data);
                if (mysqli_num_rows($query) >= 1) {
                    $row = mysqli_fetch_assoc($query);
                    $candidateId = $row['id'];


                    $updateUserSql = "UPDATE `users` SET `mobileNumber`='$mobileNumber' WHERE `id`='$user_id'";
                    $updateUserQuery = mysqli_query($databaseConnection, $updateUserSql);


                    if (!$updateUserQuery) {
                        // Handle query error
                        $to_encode = array(
                            'result' => "error",
                            'error' => "Error users query: " . mysqli_error($databaseConnection),
                            'status' => -5
                        );
                    } else {
                        $data = "select * from `professionaldetails` where candidateId='" . $candidateId . "'";
                        $query = mysqli_query($databaseConnection, $data);
                        if (mysqli_num_rows($query) >= 1) {
                            $row = mysqli_fetch_assoc($query);
                            // $id = $row['id'];

                            //                             `salary`='$salary',
                            // `expectedSalary`='$expectedSalary',
                            $pdSql = "UPDATE `professionaldetails` SET `workExperience`='$workExperience',
                            `roleId`='$roleId',
                            `subjectId`='$subjectId',
                            skills = '$skills'
                            WHERE `candidateId`='$candidateId'";
                            // echo $pdSql;
                            $pdQuery = mysqli_query($databaseConnection, $pdSql);

                            if (!$pdQuery) {
                                // Handle query error
                                $to_encode = array(
                                    'result' => "error",
                                    'error' => "Error in professional details query: " . mysqli_error($databaseConnection),
                                    'status' => -4
                                );
                            } else {
                                $to_encode = array(
                                    'result' => "success",
                                    'status' => 1
                                );
                            }
                        } else {
                            $pdSql = "INSERT INTO `professionaldetails` (`candidateId`, `workExperience`,`roleId`,`subjectId`,`skills`) VALUES ('$candidateId', '$workExperience','$roleId','$subjectId','$skills')";
                            $pdQuery = mysqli_query($databaseConnection, $pdSql);

                            if (!$pdQuery) {
                                $to_encode = array(
                                    'result' => "error",
                                    'error' => "Error in professional details query: " . mysqli_error($databaseConnection),
                                    'status' => -4
                                );
                            } else {
                                $to_encode = array(
                                    'result' => "success",
                                    'status' => 1
                                );
                            }

                        }
                    }

                    //


                    //"13,21,422,424,435,440,471,604,716,726,1014,1063,1099,1102"


                    // Fetch existing skills for the user from candidate_skills using both candidateId and emailId
                    $existingSkillsQuery = "
                        SELECT skillId, candidateId 
                        FROM candidate_skills 
                        WHERE candidateId = $user_id
                        OR emailId = (SELECT emailId FROM users WHERE id = $user_id);
                    ";

                    $existingSkillsResult = mysqli_query($databaseConnection, $existingSkillsQuery);
                    $existingSkills = [];
                    while ($row = mysqli_fetch_assoc($existingSkillsResult)) {
                        $existingSkills[] = $row['skillId']; // Collect existing skill IDs
                    }

                    // Process the incoming skill IDs
                    $skillsArray = explode(',', $skills);
                    $skillsArray = array_map('intval', $skillsArray); // Convert IDs to integers
                    $skillsList = implode(',', $skillsArray);

                    // Query to fetch skill names and IDs
                    $query = "SELECT id, favourite_subject AS name FROM favourite_subject WHERE id IN ($skillsList)";
                    $result = mysqli_query($databaseConnection, $query);

                    // Initialize array to store skills
                    $newSkillsArray = [];

                    if ($result && mysqli_num_rows($result) > 0) {
                        while ($row = mysqli_fetch_assoc($result)) {
                            $newSkillsArray[] = $row; // Store each skill
                        }
                    }

                    // var_dump($newSkillsArray);
                    // exit();

                    // Process skills: Insert new, Delete old, Do nothing for matching ones
                    foreach ($newSkillsArray as $skill) {
                        $skillId = $skill['id'];
                        $skillName = mysqli_real_escape_string($databaseConnection, $skill['name']);
                        $yoe = 0;
                        $projectDetails = ''; // Set project details here if needed

                        // Check if the skill is already in the existing skills array
                        if (!in_array($skillId, $existingSkills)) {
                            // Insert new skill if not already present
                            $insertQuery = "
                                INSERT INTO candidate_skills (candidateId, skillId, name, yoe, projectDetails, emailId)
                                VALUES ($user_id, $skillId, '$skillName', '$yoe', " . ($projectDetails !== null ? "'$projectDetails'" : "NULL") . ", 
                                (SELECT emailId FROM users WHERE id = $user_id))
                            ";

                            // echo $insertQuery;

                            // Execute insert query
                            $insertQueryResult = mysqli_query($databaseConnection, $insertQuery);

                            if (!$insertQueryResult) {
                                $to_encode = array(
                                    'result' => "error",
                                    'error' => "Error inserting skill: " . mysqli_error($databaseConnection),
                                    'status' => -6
                                );
                            }
                        }
                    }

                    // Update skills that exist in both existingSkills and newSkillsArray
                    foreach ($newSkillsArray as $skill) {
                        $skillId = $skill['id'];

                        if (in_array($skillId, $existingSkills)) {
                            // Check if the skill exists in candidate_skills but has no candidateId set
                            $updateQuery = "
                                UPDATE candidate_skills 
                                SET candidateId = IF(candidateId IS NULL, $user_id, candidateId)
                                WHERE skillId = $skillId 
                                AND (candidateId IS NULL OR candidateId != $user_id)
                                AND emailId = (SELECT emailId FROM users WHERE id = $user_id);
                            ";

                            $updateQueryResult = mysqli_query($databaseConnection, $updateQuery);

                            if (!$updateQueryResult) {
                                $to_encode = array(
                                    'result' => "error",
                                    'error' => "Error updating skill: " . mysqli_error($databaseConnection),
                                    'status' => -8
                                );
                            }
                        }
                    }

                    // Delete skills that are no longer in the $newSkillsArray but are in the existingSkills
                    foreach ($existingSkills as $existingSkillId) {
                        if (!in_array($existingSkillId, $skillsArray)) {
                            // Delete skill if it exists in existingSkills but not in the new skills list
                            $deleteQuery = "
                                DELETE FROM candidate_skills
                                WHERE candidateId = $user_id AND skillId = $existingSkillId
                            ";

                            $deleteQueryResult = mysqli_query($databaseConnection, $deleteQuery);

                            if (!$deleteQueryResult) {
                                $to_encode = array(
                                    'result' => "error",
                                    'error' => "Error deleting skill: " . mysqli_error($databaseConnection),
                                    'status' => -7
                                );
                            }
                        }
                    }



                    //

                    $updateUserSql = "UPDATE `users` SET profile_updated='Y' WHERE id='$user_id'";
                    $updateUserQuery = mysqli_query($databaseConnection, $updateUserSql);

                    if ($updateUserQuery) {
                        $to_encode = array(
                            'result' => "Success",
                            'response' => 'User profile updated Successfully.',
                            'status' => 1
                        );
                    }

                } else {
                    $to_encode = array(
                        'result' => "error",
                        'errorCode' => "User not found",
                        'status' => -3
                    );
                }
            } else {
                $to_encode = array(
                    'result' => "error",
                    'errorCode' => "Please enter the details",
                    'status' => -2
                );
            }

        }



    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "User Creation failed.",
            'status' => -1
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['educationalSection'])) {
    // @ sourabh - new signup
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {

        $user_id = $json['userId'];
        $year = $json['year'];

        $college = $json['college'] ?? "NULL";
        $otherCollege = $json['otherCollege'] ?? "NULL";
        $stream = $json['stream'] ?? "NULL";
        $cgpa = isset($json['cgpa']) && $json['cgpa'] !== '' ? $json['cgpa'] : 0;

        $otherCollege = mysqli_real_escape_string($databaseConnection, $otherCollege);


        if ($year != '' && $user_id != '') {

            $data = "select * from `users` where id='" . $user_id . "'";
            $query = mysqli_query($databaseConnection, $data);
            if (mysqli_num_rows($query) >= 1) {
                $row = mysqli_fetch_assoc($query);
                $candidateId = $row['id'];


                $data = "select * from `professionaldetails` where candidateId='" . $candidateId . "'";
                $query = mysqli_query($databaseConnection, $data);
                if (mysqli_num_rows($query) >= 1) {
                    $row = mysqli_fetch_assoc($query);
                    $id = $row['id'];

                    $pdSql = "UPDATE `professionaldetails` SET `college`='$college',`otherCollege`='$otherCollege', `qualification`='$stream', `year`='$year', `cgpa`='$cgpa' WHERE `candidateId`='$candidateId'";
                    $pdQuery = mysqli_query($databaseConnection, $pdSql);

                    if (!$pdQuery) {
                        // Handle query error
                        $to_encode = array(
                            'result' => "error",
                            'error' => "Error in professional details query: " . mysqli_error($databaseConnection),
                            'status' => -4
                        );
                    } else {
                        $to_encode = array(
                            'result' => "success",
                            'status' => 1
                        );
                    }
                }

            } else {
                $to_encode = array(
                    'result' => "error",
                    'errorCode' => "User not found",
                    'status' => -3
                );
            }
        } else {
            $to_encode = array(
                'result' => "error",
                'errorCode' => "Please enter the details",
                'status' => -2
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "User Creation failed.",
            'status' => -1
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['professionalSection'])) {
    // @ sourabh - new signup
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {


        $user_id = $json['userId'];

        // $currentCompany = $json['currentCompany'] ?? "NULL";
        $skills = $json['skills'] !== "NULL" ? (is_array($json['skills']) ? implode(';', $json['skills']) : $json['skills']) : "NULL";
        $workExperience = $json['workExperience'] ?? "NULL";
        $salary = $json['salary'] ?? "NULL";
        $areaOfInterest = $json['areaOfInterest'] !== "NULL" ? (is_array($json['areaOfInterest']) ? implode(',', $json['areaOfInterest']) : $json['areaOfInterest']) : "NULL";

        if ($user_id) {
            $data = "select * from `users` where id='" . $user_id . "'";
            $query = mysqli_query($databaseConnection, $data);
            if (mysqli_num_rows($query) >= 1) {
                $row = mysqli_fetch_assoc($query);
                $candidateId = $row['id'];

                $data = "select * from `professionaldetails` where candidateId='" . $candidateId . "'";
                $query = mysqli_query($databaseConnection, $data);
                if (mysqli_num_rows($query) >= 1) {
                    $row = mysqli_fetch_assoc($query);
                    $id = $row['id'];

                    $pdSql = "UPDATE `professionaldetails` SET `workExperience`='$workExperience', `salary`='$salary', `preferredRole`='$areaOfInterest', `skills`='$skills' WHERE `candidateId`='$candidateId'";
                    $pdQuery = mysqli_query($databaseConnection, $pdSql);

                    if (!$pdQuery) {
                        // Handle query error
                        $to_encode = array(
                            'result' => "error",
                            'error' => "Error in professional details query: " . mysqli_error($databaseConnection),
                            'status' => -4
                        );
                    } else {
                        $updateUserSql = "UPDATE `users` SET profile_updated='Y' WHERE id='$user_id'";
                        $updateUserQuery = mysqli_query($databaseConnection, $updateUserSql);

                        if ($updateUserQuery) {
                            $to_encode = array(
                                'result' => "Success",
                                'response' => 'User profile updated Successfully.',
                                'status' => 1
                            );
                        }

                    }
                }
            } else {
                $to_encode = array(
                    'result' => "error",
                    'errorCode' => "User not found",
                    'status' => -3
                );
            }
        } else {
            $to_encode = array(
                'result' => "error",
                'errorCode' => "Please enter the details",
                'status' => -2
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "User profile update failed.",
            'status' => -1
        );
    }

    echo json_encode($to_encode);
}
// for vendor users signup and login
elseif (isset($_GET['getvendorLogUser'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $uname = $json['emailId'];
        $smsOtp = '1421';
        $password = password_hash($json['password'], PASSWORD_BCRYPT, ["cost" => 12]);
        $firstName = $json['firstName'];
        $lastName = '';
        $mobileNumber = $json['mobileNumber'];
        $email = $json['emailId'];
        $source = NUll;
        $verificationLink = md5(rand(0, 1000));
        $verificationStatus = "Y";
        $isActive = "Y";
        $firstName = addslashes($firstName);
        // $college = $json['college'];
        // $otherCollege = $json['otherCollege'];
        // $specialization = $json['specialization'];
        // $year = $json['year'];
        // $cgpa = $json['cgpa'];
        // $gender = $json['gender'];
        $isAccepted_T_C = 'Yes';
        $isMentee = "N";
        $usertype = 'student';
        $vId = $json['vId'];
        $preId = $json['preId'];

        $vendorPreInterviewExists = "select id,vendorId from `preInterview` where id =" . $preId . " and vendorId = " . $vId . "";
        $vendorPreInterviewExistsResult = mysqli_query($databaseConnection, $vendorPreInterviewExists);

        // job form details to be hidden for this interview
        // $hideJobForm = mysqli_query($databaseConnection,"update preInterview set workExperience='N',currentLocation='N',preferredWorkLocation='N',Language='N',jobType='N',currentCompany='N',currentProcess='N',processType='N',clientType='N',currentSalary='N',expectedSalary='N',noticePeriod='N',processPreference='N',shift='N',workLocationPreference='N',timeToCall='N',declaration='N',preferedJobType='N',joiningTimeline='N' where id = " . $preId . "");

        if (mysqli_num_rows($vendorPreInterviewExistsResult) >= 1) {

            $vendorcorporateId = "select corporateId from `vendors` where id =" . $vId . "";
            $vendorcorporateIdResult = mysqli_query($databaseConnection, $vendorcorporateId);
            if ($vendorcorporateIdResult) {
                $cIdResult = mysqli_fetch_assoc($vendorcorporateIdResult);
                $cId = $cIdResult['corporateId'];
            }

            if ($email != '' && $password != '') {

                $data = "select * from `users` where emailId='" . $email . "'";
                $query = mysqli_query($databaseConnection, $data);
                if (mysqli_num_rows($query) >= 1) {
                    $databaseResult = mysqli_fetch_assoc($query);
                    $databaseId = $databaseResult['dataSource'];
                    // check if it exists or not
                    $checkval = explode(',', $databaseId);
                    if (in_array($cId, $checkval)) {
                        // do nothing
                    } else {
                        if ($databaseId != '' && $databaseId != NULL) {
                            $newDatabaseValue = $databaseId . "," . $cId;
                        } else {
                            $newDatabaseValue = $cId;
                        }
                        $updateuserDatabase = "update `users` set dataSource = '" . $newDatabaseValue . "' where id =" . $databaseResult['id'] . "";
                        $updateuserDatabaseResult = mysqli_query($databaseConnection, $updateuserDatabase);
                    }

                    $to_encode = array(
                        'result' => "error",
                        'response' => 'Profile Already Exists !!',
                        'status' => 0
                    );
                } else {
                    try {
                        mysqli_autocommit($databaseConnection, FALSE);
                        $sqlQuery = "INSERT INTO `users` (`userName`, `password`, `firstName`, `lastName`, `mobileNumber`, `emailId`, `active`, `smsOtp`, `verificationLink`, `verificationStatus`,`createdOn`,`isAccepted_T_C`, `isMentee`, `usertype`,`gender`,`dataSource`) VALUES ('$uname', '$password', '$firstName', '$lastName', '$mobileNumber', '$email', '$isActive', '$smsOtp', '$verificationLink', '$verificationStatus', ROUND(UNIX_TIMESTAMP()*1000),'$isAccepted_T_C', '$isMentee', '$usertype', NULL,'$cId')";
                        $usersQuery = mysqli_query($databaseConnection, $sqlQuery);
                        if ($usersQuery == false) {
                            throw new Exception(" Error while inserting in users !! ");
                        }
                        if ($usersQuery) {
                            $userId = mysqli_insert_id($databaseConnection);
                            $collegeSql = "INSERT INTO `professionaldetails` (`candidateId`, `college`,`otherCollege`,`specialization`, `year`, `cgpa`) VALUES ('$userId', '188','Others(vendor Login)', NULL, NULL, NULL);";
                            $collegeQuery = mysqli_query($databaseConnection, $collegeSql);
                            if ($collegeQuery == false) {
                                throw new Exception(" Error while inserting in professional details !! ");
                            }
                            $subs = "select id from `users` where emailId='" . $email . "'";
                            $subsQuery = mysqli_query($databaseConnection, $subs);
                            $subResult = mysqli_fetch_assoc($subsQuery);
                            $amount = 0;
                            $duration = '15 days';
                            $date = date("Y-m-d");
                            $endDate = date('Y-m-d', strtotime($date . ' + 15 days'));
                            $product = array();
                            $pQuery = "Select productId from interview where categoryType='8' group by productId";
                            $pResult = mysqli_query($databaseConnection, $pQuery);
                            while ($row = mysqli_fetch_assoc($pResult)) {
                                $product[] = $row['productId'];
                            }
                            $productId = implode(',', $product);

                            $Subscription = "INSERT INTO `subscription` (`candidateId`, `amount`,`duration`,`startDate`,`endDate`,`productId`,`mockInterviewAllowed`, `communicationInterviewAllowed`, `behaviouralInterviewAllowed`, `problemsolvingInterviewAllowed`, `codingInterviewAllowed`,`freeTrialAllowed`) VALUES ('" . $subResult['id'] . "', '$amount', '$duration', NOW(),NOW() +  INTERVAL 15 DAY, '$productId','0','0','0','0','0','2')";
                            $Query = mysqli_query($databaseConnection, $Subscription);
                            if ($Query == false) {
                                throw new Exception(" Error while insertion in subscription !! ");
                            }

                        } else {
                            $error = date('[l, d M Y h:i:s A] :') . ' Unable to sign up, candidate details - Email id : ' . $email . ', Mobile Number : ' . $mobileNumber . ', Name : ' . $firstName;
                            if ($server == 'live') {
                                error_log($error . "\n", 3, "../../../home/ubuntu/error.log");
                            }
                            $mailSubject = $emailApiHost . ' - Issue while signed up';
                            sendRecordingErrorEmail($error, $emailApiHost, $mailSubject);
                            $to_encode = array(
                                'result' => "error",
                                'errorCode' => "User Creation failed.",
                                'query' => $sqlQuery,
                                'status' => -1
                            );
                        }
                        mysqli_commit($databaseConnection);
                    } catch (Exception $e) {
                        mysqli_rollback($databaseConnection);
                        echo 'Message: ' . $e->getMessage();
                        $to_encode = array(
                            'result' => "error",
                            'errorCode' => $e->getMessage(),
                            'status' => -3
                        );
                    }
                }

                mysqli_autocommit($databaseConnection, TRUE);

                // $sqlQuery112 = "update preinterview set vendorId=102 where id=212";
                // $usersQuery112 = mysqli_query($databaseConnection, $sqlQuery112);

                //  login the user afer account creation
                $dataUser = "SELECT * FROM `users` WHERE emailId='" . $email . "' ";
                $queryUser = mysqli_query($databaseConnection, $dataUser);
                if (mysqli_num_rows($queryUser) >= 1) {
                    $row = mysqli_fetch_assoc($queryUser);
                    $hash = $row['password'];
                    // if (password_verify("dEfaultPwd@123", $hash)) {
                    $email = $row['emailId'];
                    $name = $row['firstName'];
                    $mobile = $row['mobileNumber'];
                    $roleId = $row['userRole'];
                    $userId = $row['id'];
                    $userType = $row['usertype'];
                    if ($row['verificationStatus'] == 'Y' && $row['active'] == 'Y' && $row['deleted_at'] == NULL) {
                        if (isset($_SERVER['REMOTE_ADDR']))
                            $ipaddress = $_SERVER['REMOTE_ADDR'];
                        else
                            $ipaddress = 'UNKNOWN';
                        $to_encode = array(
                            'result' => "success",
                            'message' => "User Authenticated",
                            'status' => "1",
                            'email' => $email,
                            'name' => $name,
                            'mobile' => $mobile,
                            'userId' => $userId,
                            'roleId' => $roleId,
                            'panelId' => 0,
                            'usertype' => $userType,
                            'jwtToken' => getEncrypt('{
                                 "email":"' . $email . '",
                                 "name":"' . $name . '",
                                 "mobile":"' . $mobile . '",
                                 "userId":"' . $userId . '",
                                 "usertype":"' . $userType . '",
                                 "IP":"' . $ipaddress . '",
                                 "timeStamp":"' . date("Y-m-d H:i:s") . '"
                             }')
                        );
                    }
                    // }
                }

                // 
            } else {
                $to_encode = array(
                    'result' => "error",
                    'errorCode' => "Invalid EmailId !!",
                    'status' => -3
                );
            }
        } else {
            $to_encode = array(
                'result' => "error",
                'errorCode' => "Interview not for this vendor !!",
                'status' => -2
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "JSON decode failed.",
            'status' => -1
        );
    }

    echo json_encode($to_encode);
}
// api for fetching job results for vendor
elseif (isset($_GET['fetchJobResults'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $vendorId = $json['vId'];
        $jobId = trim($json['preId'], '\'"');
        $aptitudeScore = '';

        $data = "select * from `vendors` where id='" . $vendorId . "'";
        $query = mysqli_query($databaseConnection, $data);

        if (mysqli_num_rows($query) >= 1) {

            $vendorPreInterviewExists = "select id,vendorId from `preInterview` where id in  (" . $jobId . ")";
            $vendorPreInterviewExistsResult = mysqli_query($databaseConnection, $vendorPreInterviewExists);

            $vendorJobId = array();
            $nonVendorJobId = array();
            if (mysqli_num_rows($vendorPreInterviewExistsResult) >= 1) {
                while ($rowJobId = mysqli_fetch_array($vendorPreInterviewExistsResult, MYSQLI_ASSOC)) {
                    if ($rowJobId['vendorId'] == $vendorId) {
                        array_push($vendorJobId, $rowJobId['id']);
                    } else {
                        array_push($nonVendorJobId, $rowJobId['id']);
                    }
                }


                if (!empty($vendorJobId)) {

                    if (!empty($nonVendorJobId)) {
                        $dataMessage = 'You are not authorised to see the details of JobId ' . implode(", ", $nonVendorJobId);
                        $values['dataMessage'] = $dataMessage;
                    }

                    $alldata = array();

                    $jobInterviewDetails = mysqli_query($databaseConnection, "select i.id as interviewId,fr.id as feedbackRequestId,u.firstName,u.emailId,case when fr.review_status=2 then 'Assessment Completed' when fr.review_status=1 then 'Assessment In-progress' when fr.review_status=-4 then 'Assessment Rejected' when fr.review_status=0 then 'Assessment Open' when fr.review_status=-2 then 'Internal Review' end as AssessmentStatus from interview i inner join feedback_request fr on fr.interviewid=i.id inner join users u on u.id=fr.candidateId where i.preInterviewId in (" . implode(", ", $vendorJobId) . ")");

                    if (mysqli_num_rows($jobInterviewDetails) >= 1) {
                        while ($row = mysqli_fetch_array($jobInterviewDetails, MYSQLI_ASSOC)) {

                            $returnedValue = subjectWiseScore($databaseConnection, $row['interviewId'], $row['feedbackRequestId']);

                            for ($i = 0; $i < sizeof($returnedValue[1]); $i++) {
                                $returnedValue[1][$i]['Score'] = $returnedValue[1][$i]['skillScore'];
                                unset($returnedValue[1][$i]['skillScore'], $returnedValue[1][$i]['subjectId']);
                            }

                            if ($returnedValue[0] == -997) {
                                $row['InterviewScore'] = 'Tech Issue Rejected';
                                $aptitudeScore = -997;
                                $row['subjectScore'] = $returnedValue[1];
                            } else if ($returnedValue[0] == -996) {
                                $row['InterviewScore'] = 'Stepper Rejected';
                                $aptitudeScore = -996;
                                $row['subjectScore'] = $returnedValue[1];
                            } else if ($returnedValue[0] == -998) {
                                $row['InterviewScore'] = 'Partially Assessed';
                                $aptitudeScore = -998;
                                $row['subjectScore'] = $returnedValue[1];
                            } else if ($returnedValue[0] != null) {
                                $row['InterviewScore'] = $returnedValue[0];
                                $aptitudeScore = $returnedValue[0];
                                $row['subjectScore'] = $returnedValue[1];
                            } else if ($returnedValue[0] == 0) {
                                $row['InterviewScore'] = 0;
                                $aptitudeScore = 0;
                                $row['subjectScore'] = [];
                                // $row['AssessmentStatus'] = 'Assessment Rejected';
                            } else {
                                $row['InterviewScore'] = 0;
                                $aptitudeScore = 0;
                                $row['subjectScore'] = [];
                            }

                            $reviewedExpertDetails = mysqli_query($databaseConnection, "select name,companiesWorked from panel where id in (select expertId from feedback_status_question where feedbackRequestId = '" . $row['feedbackRequestId'] . "') and id != 62 ");

                            if (mysqli_num_rows($reviewedExpertDetails) > 0) {
                                $reviewedExpertDetailsResult = mysqli_fetch_all($reviewedExpertDetails, MYSQLI_ASSOC);
                                for ($i = 0; $i < count($reviewedExpertDetailsResult); $i++) {
                                    $reviewedExpertDetailsResult[$i]['companiesWorked'] = explode(",", $reviewedExpertDetailsResult[$i]['companiesWorked'])[0];
                                }
                                $row['feedbackReviewedExpertDetails'] = $reviewedExpertDetailsResult;
                            } else {
                                $row['feedbackReviewedExpertDetails'] = [];
                            }


                            $employability_status_query = mysqli_query($databaseConnection, "SELECT ifs.value as `value` FROM ier_for_sector ifs LEFT OUTER JOIN interview i ON i.sector_id = ifs.sector_id LEFT OUTER JOIN sector s ON i.sector_id = s.id WHERE i.id = " . $row['interviewId'] . " AND score = (CASE WHEN " . $aptitudeScore . " < 0 THEN " . $aptitudeScore . " WHEN " . $aptitudeScore . " <= 4 THEN round(" . $aptitudeScore . ") WHEN " . $aptitudeScore . " >= 7  THEN round(" . $aptitudeScore . ") ELSE 6 END);");

                            if (mysqli_num_rows($employability_status_query) >= 1) {
                                $es_rows = mysqli_fetch_all($employability_status_query, MYSQLI_ASSOC);
                                if ($es_rows[0]['value'] == null) {
                                    $es_rows = [];
                                }
                            } else {
                                $es_rows = [];
                            }
                            $row['employailityStatus'] = $es_rows;


                            $key_skill_query = mysqli_query($databaseConnection, "SELECT oa.description, ks.key_skill as key_skill_name,ROUND(avg(ov.observation_values),1) as score FROM expert_review_observation_details as erod inner join observation_area as oa on oa.id = erod.observationAreaId inner join expert_review as er on er.id = erod.expertReviewId inner join feedback_request fr on fr.id = er.feedback_request_id left outer join mergedVideos m on m.interviewSessionId = fr.interviewSessionId and m.questionId = er.questionId inner join key_skill as ks on ks.id = oa.key_skill left outer join observation_values as ov on ov.id = erod.observationValueId left join questions q on q.id=m.questionId WHERE oa.observation_name !='Issue Type' and  er.feedback_request_id = " . $row['feedbackRequestId'] . " and er.subjectTag is null group by oa.key_skill order by er.id, ks.id, ov.observation_values desc");

                            $key_observations_query = mysqli_query($databaseConnection, "SELECT ov.observation_values,oa.description,CASE WHEN oa.observation_name != 'Others' THEN oa.observation_name ELSE erod.message END as observation_name,oa.observation_type,ks.key_skill as key_skill_name FROM expert_review_observation_details as erod inner join observation_area as oa on oa.id = erod.observationAreaId inner join expert_review as er on er.id = erod.expertReviewId inner join feedback_request fr on fr.id = er.feedback_request_id left outer join mergedVideos m on m.interviewSessionId = fr.interviewSessionId and m.questionId = er.questionId inner join key_skill as ks on ks.id = oa.key_skill left outer join observation_values as ov on ov.id = erod.observationValueId left join questions q on q.id=m.questionId WHERE ov.observation_values IS null and oa.observation_name !='Issue Type' and er.feedback_request_id = " . $row['feedbackRequestId'] . " and er.subjectTag is null group by oa.observation_name order by er.id, ks.id, ov.observation_values desc");


                            $e_rows_keyskill = mysqli_fetch_all($key_skill_query, MYSQLI_ASSOC);
                            $e_rows_observations = mysqli_fetch_all($key_observations_query, MYSQLI_ASSOC);

                            for ($x = 0; $x < count($e_rows_keyskill) - 1; $x++) {
                                $whatsGood = array();
                                $whatsNeedImprovment = array();

                                foreach ($e_rows_observations as $e_row_observations) {

                                    if ($e_rows_keyskill[$x]['key_skill_name'] == $e_row_observations['key_skill_name']) {
                                        // echo $e_row_observations['observation_name'];
                                        if ($e_row_observations['observation_type'] == 1) {
                                            array_push($whatsGood, $e_row_observations['observation_name']);
                                        } else if ($e_row_observations['observation_type'] == 0) {
                                            array_push($whatsNeedImprovment, $e_row_observations['observation_name']);
                                        }
                                    }

                                }
                                if (!empty($whatsGood)) {
                                    $e_rows_keyskill[$x]['whatsGood'] = $whatsGood;
                                } else {
                                    $e_rows_keyskill[$x]['whatsGood'] = [];
                                }
                                if (!empty($whatsNeedImprovment)) {
                                    $e_rows_keyskill[$x]['whatNeedsImprovment'] = $whatsNeedImprovment;
                                } else {
                                    $e_rows_keyskill[$x]['whatNeedsImprovment'] = [];
                                }
                            }

                            $row['skills'] = $e_rows_keyskill;
                            // $row['observationalSkills'] = $e_rows_observations;



                            unset($row['interviewId'], $row['feedbackRequestId']);
                            array_push($alldata, $row);
                        }
                    }
                    $values['data'] = $alldata;
                    $to_encode = $values;

                } else {

                    $to_encode = array(
                        'result' => "error",
                        'response' => 'You are not authorised to see this information !!',
                        'status' => 0
                    );

                }

            } else {

                $to_encode = array(
                    'result' => "error",
                    'response' => 'Wrong job details !!',
                    'status' => -3
                );

            }

        } else {

            $to_encode = array(
                'result' => "error",
                'response' => 'Incorrect Vendor Information !!',
                'status' => -2
            );

        }

    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Json Decode failed !!",
            'status' => -1
        );
    }

    echo json_encode($to_encode);
}
//this is used for signup of aspirants for a company
elseif (isset($_GET['signUpEvent'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $uname = $json['emailId'];
        $smsOtp = '1421';
        $password = password_hash($json['password'], PASSWORD_BCRYPT, ["cost" => 12]);
        $firstName = $json['firstName'];
        $lastName = '';
        $mobileNumber = $json['mobileNumber'];
        $email = $json['emailId'];
        $source = $json['source'];
        $verificationLink = md5(rand(0, 1000));
        $verificationStatus = "N";
        $isActive = "Y";
        $firstName = addslashes($firstName);
        $userSource = $json['userSource'];
        $college = $json['college'];
        $otherCollege = $json['otherCollege'];
        $specialization = $json['specialization'];
        $year = $json['year'];
        $isAccepted_T_C = 'Yes';
        $data = "select * from `users` where emailId='" . $email . "'";
        $query = mysqli_query($databaseConnection, $data);
        if (mysqli_num_rows($query) >= 1) {
            $to_encode = array(
                'result' => "error",
                'response' => 'Profile Already Exists !!',
                'status' => 0
            );
        } else {
            $sqlQuery = "INSERT INTO `users` (`userName`, `password`, `firstName`, `lastName`, `mobileNumber`, `emailId`, `active`, `smsOtp`, `verificationLink`, `verificationStatus`,`createdOn`,`isAccepted_T_C`) VALUES ('$uname', '$password', '$firstName', '$lastName', '$mobileNumber', '$email', '$isActive', '$smsOtp', '$verificationLink', '$verificationStatus', ROUND(UNIX_TIMESTAMP()*1000),'$isAccepted_T_C')";
            $usersQuery = mysqli_query($databaseConnection, $sqlQuery);
            if ($usersQuery) {
                $userId = mysqli_insert_id($databaseConnection);
                $collegeSql = "INSERT INTO `professionaldetails` (`candidateId`, `college`,`otherCollege`, `specialization`, `year`) VALUES ('$userId', '$college','" . addslashes($otherCollege) . "','$specialization', '$year');";
                $collegeQuery = mysqli_query($databaseConnection, $collegeSql);

                $subs = "select id from `users` where emailId='" . $email . "'";
                $subsQuery = mysqli_query($databaseConnection, $subs);
                $subResult = mysqli_fetch_assoc($subsQuery);
                $amount = 0;
                $duration = '15 days';
                $date = date("Y-m-d");
                $endDate = date('Y-m-d', strtotime($date . ' + 15 days'));
                $product = array();
                $pQuery = "Select productId from interview where categoryType='8' group by productId";
                $pResult = mysqli_query($databaseConnection, $pQuery);
                while ($row = mysqli_fetch_assoc($pResult)) {
                    $product[] = $row['productId'];
                }
                $productId = implode(',', $product);

                /* added by  03-07-2021 Narayan for checking college subscription and assign them to related college user */
                /* $checkCollegeSubscription = mysqli_query($databaseConnection, "Select * from college_subscription where collegeId='".$college."' and (streamId ='".$specialization."' OR streamId ='17') and yop='".$year."' limit 1");
                if(mysqli_num_rows($checkCollegeSubscription) >0){
                    while($row = mysqli_fetch_assoc($checkCollegeSubscription)){
                        $date1= strtotime($date);
                        $date2= strtotime($row['subscriptionEndDate']);
                        $diff = $date2 - $date1;
                       $dayDiff = round($diff / 86400);
                        $duration = $dayDiff.' days';
                        $Subscription = "INSERT INTO `subscription` (`candidateId`, `amount`,`duration`,`endDate`,`productId`,`mockInterviewAllowed`, `communicationInterviewAllowed`, `behaviouralInterviewAllowed`, `problemsolvingInterviewAllowed`, `codingInterviewAllowed`,`freeTrialAllowed`) VALUES ('".$subResult['id']."', '".$row['amount']."', '".$duration."', '".$row['subscriptionEndDate']."', '".$row['productId']."','".$row['mockInterviewAllowed']."','".$row['communicationInterviewAllowed']."','".$row['behaviouralInterviewAllowed']."','".$row['problemsolvingInterviewAllowed']."','".$row['codingInterviewAllowed']."','".$row['freeTrialAllowed']."')";
                        $Query = mysqli_query($databaseConnection, $Subscription);
                    }
                }else{*/
                $Subscription = "INSERT INTO `subscription` (`candidateId`, `amount`,`duration`,`startDate`,`endDate`,`productId`,`mockInterviewAllowed`, `communicationInterviewAllowed`, `behaviouralInterviewAllowed`, `problemsolvingInterviewAllowed`, `codingInterviewAllowed`,`freeTrialAllowed`) VALUES ('" . $subResult['id'] . "', '$amount', '$duration', NOW(),NOW() +  INTERVAL 15 DAY, '$productId','0','0','0','0','0','2')";
                $Query = mysqli_query($databaseConnection, $Subscription);
                /*}*/


                $getEventDetails = "select * from `event` where shortName='" . $userSource . "'";
                $getEventDetailsQuery = mysqli_query($databaseConnection, $getEventDetails);
                if (mysqli_num_rows($getEventDetailsQuery) >= 1) {
                    $row2 = mysqli_fetch_assoc($getEventDetailsQuery);
                    if ($row2['categoryType'] == 2) {
                        $updateSource = 'amc_' . $row2['id'];
                    } else {
                        $updateSource = 'rec_' . $row2['id'];
                    }
                    $data2 = "update users set source ='" . $updateSource . "' where id ='" . $userId . "'";
                    $query2 = mysqli_query($databaseConnection, $data2);
                    $to_encode = array(
                        'result' => "Success",
                        'response' => 'User Created Successfully.',
                        'status' => 1
                    );
                } else {
                    $getCollegeDetails = "select * from `colleges` where shortName='" . $userSource . "'";
                    $getCollegeDetailsQuery = mysqli_query($databaseConnection, $getCollegeDetails);
                    if (mysqli_num_rows($getCollegeDetailsQuery) >= 1) {
                        $row2 = mysqli_fetch_assoc($getCollegeDetailsQuery);
                        $updateSource = 'col_' . $row2['id'];
                        $data2 = "update users set source ='" . $updateSource . "' where id ='" . $userId . "'";
                        $query2 = mysqli_query($databaseConnection, $data2);
                        $to_encode = array(
                            'result' => "Success",
                            'response' => 'User Created Successfully.',
                            'status' => 1
                        );
                    } else {
                        $to_encode = array(
                            'result' => "error",
                            'errorCode' => "Source updation failed.",
                            'status' => 2
                        );
                    }
                }

                $verifyLink = $emailApiHost . "/verification?id=" . $verificationLink . "&email=" . $email . "&source=" . $source;
                accountCreationEmail($firstName, $email, $verifyLink);

                /*$data2 = "select * from `scodes` where emailId='" . $email . "' and companyId='".$row2['id']."'";
                $query2 = mysqli_query($databaseConnection, $data2);
                if(mysqli_num_rows($query2) >= 1){
                    $sqlQuery2 = "update scodes set userId = '$userId', s_is_availed='Y' where emailId ='$email';";
                    $usersIdQuery = mysqli_query($databaseConnection, $sqlQuery2);
                    $to_encode = array(
                        'result' => "Success",
                        'response' => 'User Created Successfully.',
                        'status' => 1
                    );
                    //$verifyLink = $emailApiHost."/verificationCompany?id=" . $verificationLink . "&email=" . $email;
                    $verifyLink = $emailApiHost."/verification?id=" . $verificationLink . "&email=" . $email . "&source=" . $source;
                    accountCreationEmail($firstName, $email, $verifyLink);
                } else {
                    $data3 = "select * from `scodes` where s_is_availed='N' and userId is NULL and emailId is NULL and companyId is NULL and source is NULL limit 0,1";
                    $query3 = mysqli_query($databaseConnection, $data3);
                    if(mysqli_num_rows($query3) >= 1){
                        $row = mysqli_fetch_assoc($query3);
                        $sqlQuery3 = "update scodes set userId = '$userId', s_is_availed='Y', emailId ='$email', companyId=".$row2['id'].", source=".$row2['id']." where s_value='".$row['s_value']."';";
                        $usersIdQuery = mysqli_query($databaseConnection, $sqlQuery3);
                        $to_encode = array(
                            'result' => "Success",
                            'response' => 'User Created Successfully.',
                            'status' => 1
                        );
                        //$verifyLink = $emailApiHost."/verificationCompany?id=" . $verificationLink . "&email=" . $email;
                        $verifyLink = $emailApiHost."/verification?id=" . $verificationLink . "&email=" . $email . "&source=" . $source;
                        accountCreationEmail($firstName, $email, $verifyLink);
                    } else{
                        $to_encode = array(
                            'result' => "error",
                            'errorCode' => "User Creation failed.",
                            'query' => $query3,
                            'status' => -1
                        );
                    }
                }*/
            } else {
                $error = date('[l, d M Y h:i:s A] :') . ' Unable to sign up, candidate details - Email id : ' . $email . ', Mobile Number : ' . $mobileNumber . ', Name : ' . $firstName;
                if ($server == 'live') {
                    error_log($error . "\n", 3, "../../../home/ubuntu/error.log");
                }
                $mailSubject = $emailApiHost . ' - Issue while signed up';
                sendRecordingErrorEmail($error, $emailApiHost, $mailSubject);
                $to_encode = array(
                    'result' => "error",
                    'errorCode' => "User Creation failed.",
                    'query' => $sqlQuery,
                    'status' => -1
                );
            }
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "User Creation failed.",
            'status' => -1
        );
    }
    echo json_encode($to_encode);
}
//the above code is used for signup of aspirants for a company
elseif (isset($_GET['resendVerification'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $email = $json['emailId'];
        $source = $json['source'];
        $data = "select * from `users` where emailId='" . $email . "'";
        $query = mysqli_query($databaseConnection, $data);
        $data2 = "select * from `scodes` where emailId='" . $email . "'";
        $query2 = mysqli_query($databaseConnection, $data2);
        if (mysqli_num_rows($query) >= 1) {
            $row = mysqli_fetch_assoc($query);
            $email = $row['emailId'];
            $firstName = $row['firstName'];
            $mobile = $row['mobileNumber'];
            $userId = $row['id'];
            //$verifyLink = "https://stage.goprac.com/verification?id=" . $row['verificationLink'] . "&email=" . $email;
            if (mysqli_num_rows($query2) == 0) {
                $verifyLink = $emailApiHost . "/verification?id=" . $row['verificationLink'] . "&email=" . $email . "&source=" . $source;
            } else {
                $verifyLink = $emailApiHost . "/verificationCompany?id=" . $row['verificationLink'] . "&email=" . $email;
            }
            $status = accountCreationEmail($firstName, $email, $verifyLink);
            if ($status == 1) {
                $to_encode = array(
                    'result' => "success",
                    'response' => 'Email sent successfully',
                    'status' => 1
                );
            } else {
                $to_encode = array(
                    'result' => "info",
                    'response' => 'Error while sending Email',
                    'status' => 2,
                    'error' => $status
                );
            }
        } else {
            $to_encode = array(
                'result' => "error",
                'errorCode' => "error while sending verification link",
                'status' => -1
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "error while sending verification link"
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['trackAssessmentWatch'])) {
    /* this method is added for tracking of user weather they gone through assessment or not  by Devanand 9-Nov-2021*/
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $interviewSessionId = $json['interviewSessionId'];
        $fbr_id = $json['fbr_id'];
        $viewAssessment_status = mysqli_query($databaseConnection, "update feedback_request
       set viewAssessment='Y' where id='" . $fbr_id . "' and interviewSessionId = '" . $interviewSessionId . "' ");
        if ($viewAssessment_status) {
            $to_encode = array(
                'result' => 'sucess',
                'status' => 1
            );

        } else {
            $to_encode = array(
                'result' => 'error',
                'status' => 0
            );
        }

    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "sms server connection failed",
            'status' => -1
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['updateUser'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        try {
            $userId = getDecrypt($json['userData'])->userId;
            $password = $json['password'];
            // $salt = getSaltKey();
            // $passwd = encryptPasswd($json['passwd'],$salt);
            // $confirmpasswd = $json['confirmpasswd'];
            $hash = password_hash($password, PASSWORD_BCRYPT, ["cost" => 12]);
            $smsOtp = $json['smsOtp'];
            // if (validateField($json['firstName'], 'name'))
            //     $firstName = $json['firstName'];
            // else
            //     throw new Exception("invalidField");

            // $gender = $json['gender'];

            // if (validateField($json['mobileNumber'], 'mobile'))
            //     $mobileNumber = $json['mobileNumber'];
            // else
            //     throw new Exception("invalidField");

            if (validateField($json['emailId'], 'email'))
                $email = $json['emailId'];
            else
                throw new Exception("invalidField");

            // $firstName = addslashes($firstName);
            $getUserEmail = "select * from users where emailId='" . $email . "' and id not in ('" . $userId . "');";
            $getUserEmailQuery = mysqli_query($databaseConnection, $getUserEmail);
            $userResult = mysqli_fetch_assoc($getUserEmailQuery);

            $getUserDetails = "select usertype,panelId from users where id  in ('" . $userId . "');";
            $getUserDetailsQuery = mysqli_query($databaseConnection, $getUserDetails);
            $UserDetailsResult = mysqli_fetch_assoc($getUserDetailsQuery);
            if (mysqli_num_rows($getUserEmailQuery) == 0) {
                if ($password != '') {
                    $data = "UPDATE users set emailId='" . $email . "',userName='" . $email . "',`password`='" . $hash . "',smsOtp='" . $smsOtp . "' where id='" . $userId . "'";
                    /* change by Narayan  05-08-2021 UPDATE Expert  email and phone  in panel Table */
                    if ($UserDetailsResult['usertype'] == 'expert') {
                        $updatePanel = mysqli_query($databaseConnection, "UPDATE panel set emailId='" . $email . "' where id= '" . $UserDetailsResult['panelId'] . "'");
                    }
                } else {
                    $data = "UPDATE users set emailId='" . $email . "',userName='" . $email . "',smsOtp='" . $smsOtp . "' where id='" . $userId . "'";
                    /* change by Narayan  05-08-2021 UPDATE Expert  email and phone  in panel Table */
                    if ($UserDetailsResult['usertype'] == 'expert') {
                        $updatePanel = mysqli_query($databaseConnection, "UPDATE panel set emailId='" . $email . "' where id= '" . $UserDetailsResult['panelId'] . "' ");
                    }
                }
                $query = mysqli_query($databaseConnection, $data);
                if ($query) {
                    $to_encode = array(
                        'result' => "Success",
                        'response' => 'Profile Updated Successful.',
                        'status' => "1"
                    );
                    // profileUpdatedEmail($firstName, $email);
                } else {
                    $to_encode = array(
                        'result' => "error",
                        'errorCode' => "User Creation failed.",
                        'status' => 0,
                        'sql' => $data
                    );
                }
            } else {
                $to_encode = array(
                    'result' => "error",
                    'errorCode' => "User Creation failed.",
                    'status' => -1
                );
            }
        } catch (Exception $e) {
            if ($e->getMessage() == "invalidField") {
                $to_encode = array(
                    'result' => $e->getMessage(),
                    'errorCode' => "field not valid",
                    'status' => "-99",
                );
            } else {
                $to_encode = array(
                    'result' => "error",
                    'errorCode' => "user Id does not exist.",
                    'status' => "-70",
                    'msg' => $e->getMessage(),
                );
            }
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "User Creation failed.",
            'status' => 0
        );
    }

    echo json_encode($to_encode);
}
elseif (isset($_GET['forgotPassword'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {

        $email = $json['emailId'];
        $source = $json['source'];
        $verificationLink = md5(rand(0, 1000));
        $verificationLinks = password_hash('".$verificationLink."', PASSWORD_BCRYPT, ["cost" => 12]);
        $data = "select * from `users` where emailId='" . $email . "' or mobileNumber='" . $email . "'";
        $query = mysqli_query($databaseConnection, $data);
        if (mysqli_num_rows($query) >= 1) {

            $row = mysqli_fetch_assoc($query);
            $email = $row['emailId'];
            $firstName = $row['firstName'];
            $mobile = $row['mobileNumber'];
            $sqlQuery = "UPDATE `users` SET `verificationLink` = '" . $verificationLink . "' WHERE `emailId`='" . $email . "' or `mobileNumber`='" . $mobile . "'";
            $usersQuery = mysqli_query($databaseConnection, $sqlQuery);
            if ($usersQuery) {
                $userId = mysqli_insert_id($databaseConnection);
                $to_encode = array(
                    'result' => "Success",
                    'response' => 'Email sent to registered Email ID.'
                );
                $verifyLink = $emailApiHost . "/reset?id=" . $verificationLink . "&email=" . $email . "&source=" . $source;
                forgotPasswordEmail($firstName, $email, $verifyLink);
                // sendSMS($smsOtp,$mobileNumber);
            } else {
                $to_encode = array(
                    'result' => "error",
                    'response' => 'Profile does not Exists !!'
                );
            }
        } else {
            $to_encode = array(
                'result' => "error",
                'response' => 'Profile does not Exists !!'
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "User Creation failed."
        );
    }

    echo json_encode($to_encode);
}
elseif (isset($_GET['forgotPasswordCompany'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {

        $email = $json['emailId'];
        $verificationLink = md5(rand(0, 1000));
        $verificationLinks = password_hash('".$verificationLink."', PASSWORD_BCRYPT, ["cost" => 12]);
        $data = "select * from `users` where emailId='" . $email . "' or mobileNumber='" . $email . "'";
        $query = mysqli_query($databaseConnection, $data);
        if (mysqli_num_rows($query) >= 1) {

            $row = mysqli_fetch_assoc($query);
            $email = $row['emailId'];
            $firstName = $row['firstName'];
            $mobile = $row['mobileNumber'];
            $sqlQuery = "UPDATE `users` SET `verificationLink` = '" . $verificationLink . "' WHERE `emailId`='" . $email . "' or `mobileNumber`='" . $mobile . "'";
            $usersQuery = mysqli_query($databaseConnection, $sqlQuery);
            if ($usersQuery) {
                $userId = mysqli_insert_id($databaseConnection);
                $to_encode = array(
                    'result' => "Success",
                    'response' => 'Email sent to registered Email ID.'
                );
                $verifyLink = $emailApiHost . "/resetCompany?id=" . $verificationLink . "&email=" . $email;
                forgotPasswordEmail($firstName, $email, $verifyLink);
            } else {
                $to_encode = array(
                    'result' => "error",
                    'response' => 'Profile does not Exists !!'
                );
            }
        } else {
            $to_encode = array(
                'result' => "error",
                'response' => 'Profile does not Exists !!'
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "User Creation failed."
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['generateOTP'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $mobileNumber = $json['mobileNumber'];
        $smsOTP = generateOTP();
        $otpQuery = mysqli_query($databaseConnection, "update users set smsOtp='$smsOTP' where mobilenumber='$mobileNumber';");
        if ($otpQuery) {
            sendSMS($smsOTP);
            $to_encode = array(
                'result' => "Success",
                'response' => 'OTP Generation Successfully.'
            );
        } else {
            $to_encode = array(
                'result' => "error",
                'errorCode' => "OTP Generation failed."
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "OTP Generation failed."
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['sendSMS'])) {
    $response = sendSMS(generateOTP(), "8050943538");
    $to_encode = array(
        'result' => "error",
        'errorCode' => $response
    );
    echo json_encode($to_encode);
} elseif (isset($_GET['sendEmail'])) {
    $response = sendEmail("vinot");
    $to_encode = array(
        'result' => "error",
        'errorCode' => $response
    );
    echo json_encode($to_encode);
}
//node-api
elseif (isset($_GET['verifyAccountByAdmin'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['candidateId'];
        $userType = $json['userType'];
        $query = '';
        if ($userType === 'admin') {
            $result = mysqli_query($databaseConnection, "UPDATE users SET verificationStatus='Y' where id='$candidateId'");
        }
        if ($result) {
            $to_encode = array(
                'result' => "Success",
                'response' => 'Email Verification Successful.',
                'status' => 1
            );
        } else {
            $to_encode = array(
                'result' => "error",
                'errorCode' => "Email Verification Failed.",
                'status' => 0,
                'query' => $query
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Email Verification Failed.",
            'status' => -1
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['verifyEmail'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $emailId = $json['emailId'];
        $verficationCode = $json['verificationCode'];
        $query = mysqli_query($databaseConnection, "select firstName,verificationLink from users where emailId='$emailId';");
        $row = mysqli_fetch_assoc($query);
        $systemVerificationCode = $row['verificationLink'];
        $name = $row['firstName'];
        if ($systemVerificationCode == $verficationCode) {
            $sqlQuery = "UPDATE `users` SET `verificationStatus`='Y' where `verificationLink` = '" . $verficationCode . "' and `emailId`='" . $emailId . "'";
            $usersQuery = mysqli_query($databaseConnection, $sqlQuery);
            if ($usersQuery) {
                $userId = mysqli_insert_id($databaseConnection);
                /*$companyData = "select s.emailId, s.companyId, c.shortName from scodes s inner join company c on s.companyId = c.id and emailId = '" . $emailId . "'";
                $companyQuery = mysqli_query($databaseConnection, $companyData);
                if(mysqli_num_rows($companyQuery) == 1){
                    $companyDetails = mysqli_fetch_assoc($companyQuery);
                    $companyShortName = $companyDetails['shortName'];
                } else{
                    $companyShortName = 'gpc';
                }*/
                //emailVerifiedEmail($name, $emailId);
                $to_encode = array(
                    'result' => "Success",
                    'response' => 'Email Verification Successful.'
                    //'companyShortName' => $companyShortName
                );
            }
        } else {
            $to_encode = array(
                'result' => "error",
                'errorCode' => "Email Verification code is invalid.",
                'systemVerificationCode' => $systemVerificationCode,
                'verficationCode' => $verficationCode,
                'emailId' => $emailId
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Email Verification failed."
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['verifyPassword'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $emailId = $json['emailId'];
        $verficationCode = $json['verificationCode'];
        $query = mysqli_query($databaseConnection, "select firstName,verificationLink from users where emailId='$emailId';");
        $row = mysqli_fetch_assoc($query);
        $systemVerificationCode = $row['verificationLink'];
        $name = $row['firstName'];
        if ($systemVerificationCode == $verficationCode) {
            // sendGenericEmail($name,$emailId,"Email Verified");
            $to_encode = array(
                'result' => "Success",
                'response' => 'Verification Successful.'
            );
        } else {
            $to_encode = array(
                'result' => "error",
                'errorCode' => "Verification code is invalid.",
                'systemVerificationCode' => $systemVerificationCode,
                'verficationCode' => $verficationCode,
                'emailId' => $emailId
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Verification failed."
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['resetPassword'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $emailId = $json['emailId'];
        $password = password_hash($json['password'], PASSWORD_BCRYPT, ["cost" => 12]);

        $data = "UPDATE `users` SET password='" . $password . "' where emailId='" . $emailId . "'";
        $usersQuery = mysqli_query($databaseConnection, $data);
        if ($usersQuery) {
            $userId = mysqli_insert_id($databaseConnection);
            /*$companyData = "select s.emailId, s.companyId, c.shortName from scodes s inner join company c on s.companyId = c.id and emailId = '" . $emailId . "'";
            $companyQuery = mysqli_query($databaseConnection, $companyData);
            if(mysqli_num_rows($companyQuery) == 1){
                $companyDetails = mysqli_fetch_assoc($companyQuery);
                $companyShortName = $companyDetails['shortName'];
            } else{
                $companyShortName = 'gpc';
            }*/
            $to_encode = array(
                'result' => "Success",
                'response' => 'Password updated successfully'
                //'companyShortName' => $companyShortName
            );
        } else {
            $to_encode = array(
                'result' => "error",
                'response' => 'Error while updating password !!'
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "User Creation failed."
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['getUserInterviewAttemptDetails'])) {
    /* added by Narayan 21-07-2021  for getting consolidated subscription  or unique attempt for interiew */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $user = getSubsciptionDetails($databaseConnection, $userId);
        $sql = "select m.interviewId,i.productId as interviewProductId, m.candidateId ,count(distinct m.interviewSessionId) as totalAttempt from mergedVideos m inner join interview i on i.id = m.interviewId where m.candidateId='" . $userId . "' and m.interviewSessionId is not null and m.created  BETWEEN '" . $user['startDate'] . "' AND '" . $user['endDate'] . "' group by m.interviewId order by m.interviewId desc";
        $interviewAttemptResult = mysqli_query($databaseConnection, $sql);

        if (mysqli_num_rows($interviewAttemptResult) >= 1) {
            $row = mysqli_fetch_all($interviewAttemptResult, MYSQLI_ASSOC);
            $row[0]['userDetails'] = $user;
            $row[0]['userId'] = $userId;
            $to_encode = $row;
        } else {
            $to_encode = array(
                'result' => "success",
                'response' => "No Interviews found",
                'status' => 0,
                'userId' => $userId,
                'query' => $sql

            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Error while retrieving interviewes.",
            'status' => -1
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getUserSubscriptionDetails'])) {
    /* 21-07-2021  for getting consolidated subscription where user not taken any interview */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        /*$sql = "SELECT sb.*,DATEDIFF(sb.endDate, CURDATE()) as subscriptionEndTime from subscription sb where sb.candidateId='" . $userId . "' ";
        $subscriptionDetails = mysqli_query($databaseConnection, $sql);*/
        //mysqli_num_rows($subscriptionDetails) > 0
        if ($userId) {
            $row = getSubsciptionDetailsAndAssessment($databaseConnection, $userId);
            //$row = mysqli_fetch_all($subscriptionDetails, MYSQLI_ASSOC);
            // $row[0]['mixUserSubscriptionDetails'] = 


            $assessmentQuery = "SELECT `freeTrialAssesmentAllowed` , `mockAssesmentAllowed` as '1', `communicationAssesmentAllowed` as '2', `behaviouralAssesmentAllowed` as '3', `problemsolvingAssesmentAllowed` as '4', `codingAssesmentAllowed` as '5' FROM `subscription` WHERE candidateId = '" . $userId . "'";
            array_push($row, mysqli_fetch_assoc(mysqli_query($databaseConnection, $assessmentQuery)));
            //To calculate the unique interview Count for user by Anuj (18-11-2021)
            $menuInterviews = array();
            $menuQuery = mysqli_query($databaseConnection, "select * from menu order by sequence");
            while ($menuResult = mysqli_fetch_array($menuQuery, MYSQLI_ASSOC)) {
                $uniqueCountQuery = "select count(distinct i.id) as productProgress,p.id as productId from mergedVideos m inner join interview i on m.interviewId =i.id inner join product p on i.productId = p.id inner join feedback_request fr on fr.candidateId = m.candidateId and fr.interviewSessionId = m.interviewSessionId inner join favourite_subject fs on i.subject_id = fs.id where m.candidateId='" . $userId . "' AND i.productId='" . $menuResult['id'] . "' and m.interviewSessionId is not null and fr.review_status in(2,1,0,-3,-4)";
                $uniqueCountQueryResult = mysqli_query($databaseConnection, $uniqueCountQuery);
                if (mysqli_num_rows($uniqueCountQueryResult) >= 1) {
                    $uniqueCountQueryValue = mysqli_fetch_array($uniqueCountQueryResult, MYSQLI_ASSOC);
                    $attempted['attempt'] = $uniqueCountQueryValue['productProgress'];
                    $attempted['p_Id'] = $uniqueCountQueryValue['productId'];
                } else {
                    $attempted['attempt'] = $uniqueCountQueryValue['productProgress'];
                    $attempted['p_Id'] = $menuResult['id'];
                }
                array_push($menuInterviews, $attempted);
                unset($interviews);
            }
            $row['attempted'] = $menuInterviews;
            $to_encode = $row;
        } else {
            $to_encode = array(
                'result' => "success",
                'response' => "No user Found",
                'status' => 0
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Error while retrieving User info.",
            'status' => -1
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getUserSubscriptionDetailAndAttempt'])) {
    /* added by Anuj 18-11-2021  for calculate the usersubscription and unique interview attempt */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $value = array();
        if ($userId) {
            $row = getSubsciptionDetails($databaseConnection, $userId);
            $menuInterviews = array();
            $menuQuery = mysqli_query($databaseConnection, "select * from menu order by sequence");
            while ($menuResult = mysqli_fetch_array($menuQuery, MYSQLI_ASSOC)) {
                $uniqueCountQuery = "SELECT count(distinct i.id) as productProgress,p.id as productId from mergedVideos m inner join interview i on m.interviewId =i.id inner join product p on i.productId = p.id where m.candidateId='" . $userId . "' AND i.productId='" . $menuResult['id'] . "' AND m.created between '" . $row['startDate'] . " 00:00:00' and '" . $row['endDate'] . " 23:59:59'  and m.interviewSessionId is not null";
                $uniqueCountQueryResult = mysqli_query($databaseConnection, $uniqueCountQuery);
                if (mysqli_num_rows($uniqueCountQueryResult) >= 1) {
                    $uniqueCountQueryValue = mysqli_fetch_array($uniqueCountQueryResult, MYSQLI_ASSOC);
                    $attempted['attempt'] = $uniqueCountQueryValue['productProgress'];
                    $attempted['p_Id'] = $uniqueCountQueryValue['productId'];
                } else {
                    $attempted['attempt'] = $uniqueCountQueryValue['productProgress'];
                    $attempted['p_Id'] = $menuResult['id'];
                }
                array_push($menuInterviews, $attempted);
                unset($interviews);
            }

            $totalAttempt = mysqli_query($databaseConnection, "SELECT count(distinct i.id) as productProgress,p.id as productId from mergedVideos m inner join interview i on m.interviewId =i.id inner join product p on i.productId = p.id where m.candidateId='" . $userId . "' AND m.created between '" . $row['startDate'] . " 00:00:00' and '" . $row['endDate'] . " 23:59:59' and m.interviewSessionId is not null");
            if (mysqli_num_rows($totalAttempt) >= 1) {
                $totalAttemptValue = mysqli_fetch_array($totalAttempt, MYSQLI_ASSOC);
                $attempted['attempt'] = $totalAttemptValue['productProgress'];
                $attempted['freeTrial'] = "freeTrial";
            } else {
                $attempted['attempt'] = $uniqueCountQueryValue['productProgress'];
                $attempted['p_Id'] = "freeTrial";
            }
            array_push($menuInterviews, $attempted);

            $row['attempted'] = $menuInterviews;

            $AttendedinterviewList = mysqli_query($databaseConnection, "select i.id, CASE WHEN ( (((count(m.questionId)) / (CASE WHEN i.categoryType = 9 THEN  (SELECT COUNT( CASE WHEN iqt.attemptStatus is not NULL THEN iqt.questionId ELSE NULL END) FROM interview_questions_transection iqt inner join questions qs on qs.id = iqt.questionId WHERE iqt.interviewId=m.interviewId and qs.deleted_at is null and iqt.deleted_at is null and iqt.deleted_at is null) ELSE (select count(iqt.questionId) from interview_questions_transection iqt inner join questions qs on qs.id = iqt.questionId where iqt.interviewId = m.interviewId and qs.deleted_at is null and iqt.deleted_at is null)-1 END ))*100)<75 ) then 'N' ELSE 'Y' END as isComplete from mergedVideos m inner join interview i on m.interviewId = i.id where m.candidateId='" . $userId . "' and m.interviewSessionId is not null group by m.interviewSessionId order by m.interviewSessionId desc");

            while ($attendedRow = mysqli_fetch_assoc($AttendedinterviewList)) {
                array_push($value, $attendedRow);
            }
            $row['attended'] = $value;

            $duplicateAttendedList = mysqli_query($databaseConnection, "SELECT interviewId as id,COUNT(interviewId) AS duplicate FROM (SELECT interviewId,interviewSessionId FROM mergedVideos WHERE candidateId = '" . $userId . "' AND created between '" . $row['startDate'] . " 00:00:00' and '" . $row['endDate'] . " 23:59:59' GROUP BY interviewSessionId) as x GROUP BY interviewId");
            $duplicateAttended = array();
            while ($duplicateRow = mysqli_fetch_assoc($duplicateAttendedList)) {
                array_push($duplicateAttended, $duplicateRow);
            }
            $row['duplicateAttended'] = $duplicateAttended;

            $to_encode = $row;
        } else {
            $to_encode = array(
                'result' => "success",
                'response' => "No user Found",
                'status' => 0
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Error while retrieving User info.",
            'status' => -1
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getAttendedInterviewesonHistoryPage'])) {
    /* this method is added for history page  interview Taken 18-oct-2021*/
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $values = array();
        $userId = getDecrypt($json['userData'])->userId;
        $sql1 = "select i.categoryType , m.interviewId, m.candidateId, m.questionVideoId,CASE WHEN i.categoryType = 9 THEN  (SELECT COUNT( CASE WHEN iqt.attemptStatus is not NULL THEN iqt.questionId ELSE NULL END) FROM interview_questions_transection iqt inner join questions qs on qs.id = iqt.questionId WHERE iqt.interviewId=m.interviewId and qs.deleted_at is null and iqt.deleted_at is null and iqt.deleted_at is null) ELSE (SELECT COUNT(iqt.questionId) FROM interview_questions_transection iqt inner join questions qs on qs.id = iqt.questionId WHERE iqt.interviewId=m.interviewId and qs.deleted_at is null and iqt.deleted_at is null and iqt.deleted_at is null)-1 END as QT, m.interviewSessionId,count(m.interviewSessionId) as QA from mergedVideos m  inner join interview i  on i.id = m.interviewId where m.candidateId='" . $userId . "' and m.interviewSessionId is not null group by m.interviewSessionId order by m.interviewSessionId desc";
        $interviewResult = mysqli_query($databaseConnection, $sql1);
        if (mysqli_num_rows($interviewResult) >= 1) {
            $keys = array();
            while ($row = mysqli_fetch_assoc($interviewResult)) {
                if (in_array($row['interviewId'], $keys)) {
                    $to_encode = $keys;
                } else {
                    array_push($keys, $row['interviewId']);
                }
                $sql2 = "select id,name,description from interview where id='" . $row['interviewId'] . "'";
                $to_encode = array(
                    'result' => $sql2,
                    'response' => "if flase",
                    'status' => 0
                );
                $resultData = mysqli_query($databaseConnection, $sql2);
                $result = mysqli_fetch_array($resultData, MYSQLI_ASSOC);

                $sql3 = "select id,review_status ,reasonOfRejection,  (select CASE WHEN reasonOfRejection ='technicalIssue' THEN 'NetworkRetake'  ELSE 'None' END AS NetworkRetake from feedback_request fr where fr.candidateId='" . $userId . "' and fr.interviewId='" . $row['interviewId'] . "' order by fr.interviewSessionId DESC limit 1) as NetworkIssue  from feedback_request where candidateId=" . $userId . " and interviewSessionId=" . $row['interviewSessionId'] . " and interviewId=" . $row['interviewId'];

                $feedbackData = mysqli_query($databaseConnection, $sql3);

                if (mysqli_num_rows($feedbackData) == 0) {
                    array_push($result, array(
                        'sessionId' => $row['interviewSessionId'],
                        'candidateId' => $row['candidateId'],
                        'QA' => $row['QA'],
                        'QT' => $row['QT'],
                        'fbr_status' => -1,
                        'NetworkIssue' => 'None',
                        'categoryType' => $row['categoryType']
                        // 'sql'=>$sql3
                    ));
                } else {
                    $feedback = mysqli_fetch_assoc($feedbackData);
                    array_push($result, array(
                        'sessionId' => $row['interviewSessionId'],
                        'candidateId' => $row['candidateId'],
                        'fbr_id' => $feedback['id'],
                        'fbr_status' => $feedback['review_status'],
                        'reasonOfRejection' => $feedback['reasonOfRejection'],
                        'NetworkIssue' => $feedback['NetworkIssue'],
                        'QA' => $row['QA'],
                        'QT' => $row['QT'],
                        'categoryType' => $row['categoryType']
                        // 'sql'=>$sql3
                    ));
                }
                array_push($values, $result);
            }
            $to_encode = $values;
        } else {
            $to_encode = array(
                'result' => "success",
                'response' => "No Interviews found",
                'status' => 0,
                'sql' => $sql1
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Error while retrieving interviewes.",
            'status' => -1
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['getAttendedInterviewes'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];

        $sql1 = "select interviewId, candidateId, questionVideoId, interviewSessionId from mergedVideos where candidateId='" . $userId . "' and interviewSessionId is not null group by interviewSessionId order by interviewSessionId desc";
        $interviewResult = mysqli_query($databaseConnection, $sql1);
        if (mysqli_num_rows($interviewResult) >= 1) {
            $values = array();
            $keys = array();


            while ($row = mysqli_fetch_assoc($interviewResult)) {
                if (in_array($row['interviewId'], $keys)) {
                    $to_encode = $keys;
                } else {
                    array_push($keys, $row['interviewId']);
                }
                $sql2 = "select * from interview where id='" . $row['interviewId'] . "'";
                $to_encode = array(
                    'result' => $sql2,
                    'response' => "if flase",
                    'status' => 0
                );
                $resultData = mysqli_query($databaseConnection, $sql2);
                $result = mysqli_fetch_array($resultData, MYSQLI_ASSOC);

                $sql3 = "select * from feedback_request where candidateId=" . $userId . " and interviewSessionId=" . $row['interviewSessionId'] . " and interviewId=" . $row['interviewId'];
                $feedbackData = mysqli_query($databaseConnection, $sql3);




                $QaQt = mysqli_query($databaseConnection, "select m.interviewId, m.candidateId, m.questionVideoId,i.categoryType,  CASE WHEN i.categoryType = 9 THEN  (SELECT COUNT( CASE WHEN iqt.attemptStatus is not NULL THEN iqt.questionId ELSE NULL END) FROM interview_questions_transection iqt inner join questions qs on qs.id = iqt.questionId WHERE iqt.interviewId=m.interviewId and qs.deleted_at is null and iqt.deleted_at is null and iqt.deleted_at is null) ELSE (SELECT COUNT(iqt.questionId) FROM interview_questions_transection iqt inner join questions qs on qs.id = iqt.questionId WHERE iqt.interviewId=m.interviewId and qs.deleted_at is null and iqt.deleted_at is null and iqt.deleted_at is null)-1 END  as QT, m.interviewSessionId,count(m.interviewSessionId) as QA from mergedVideos m inner join interview i on i.id = m.interviewId where m.candidateId='" . $row['candidateId'] . "' and interviewId ='" . $row['interviewId'] . "' and m.interviewSessionId is not null group by m.interviewSessionId order by m.interviewSessionId desc");
                $isActive = mysqli_query($databaseConnection, "select distinct(i.isActive) isActive,i.id as interviewIds from interview i inner join mergedVideos m on m.interviewId=i.id where m.interviewId='" . $row['interviewId'] . "' ");
                $qaqt = mysqli_fetch_assoc($QaQt);
                $isActives = mysqli_fetch_assoc($isActive);

                if (mysqli_num_rows($feedbackData) == 0) {
                    array_push($result, array(
                        'interviewId' => $isActives['interviewIds'],
                        'sessionId' => $row['interviewSessionId'],
                        'candidateId' => $row['candidateId'],
                        'fbr_status' => -1,
                        'isActive' => $isActives['isActive'],
                        'QT' => $qaqt['QT'],
                        'QA' => $qaqt['QA'],
                        'sql' => $sql3,

                    ));
                } else {
                    $feedback = mysqli_fetch_assoc($feedbackData);
                    array_push($result, array(
                        'sessionId' => $row['interviewSessionId'],
                        'candidateId' => $row['candidateId'],
                        'fbr_id' => $feedback['id'],
                        'fbr_status' => $feedback['review_status'],
                        'sql' => $sql3,
                        'isActive' => $isActives['isActive'],
                        'QT' => $qaqt['QT'],
                        'QA' => $qaqt['QA'],
                        'interviewId' => $isActives['interviewIds'],
                    ));
                }

                array_push($values, $result);
            }
            $to_encode = $values;
        } else {
            $to_encode = array(
                'result' => "success",
                'response' => "No Interviews found",
                'status' => 0,
                'sql' => $sql1
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Error while retrieving interviewes.",
            'status' => -1
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['getCompanyAttendedInterviewes'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $companyId = $json['companyId'];

        $sql1 = "select mv.interviewId, mv.candidateId, mv.questionVideoId, mv.interviewSessionId from mergedVideos mv LEFT OUTER JOIN interview i ON i.id = mv.interviewId where mv.candidateId='" . $userId . "' AND i.companyId = '" . $companyId . "' and mv.interviewSessionId is not null and i.productId = 1 group by mv.interviewSessionId order by mv.interviewSessionId desc";
        $interviewResult = mysqli_query($databaseConnection, $sql1);
        if (mysqli_num_rows($interviewResult) >= 1) {
            $values = array();
            $keys = array();


            while ($row = mysqli_fetch_assoc($interviewResult)) {
                if (in_array($row['interviewId'], $keys)) {
                    $to_encode = $keys;
                } else {
                    array_push($keys, $row['interviewId']);
                }
                $sql2 = "select * from interview where id='" . $row['interviewId'] . "'";
                $to_encode = array(
                    'result' => $sql2,
                    'response' => "if flase",
                    'status' => 0
                );
                $resultData = mysqli_query($databaseConnection, $sql2);
                $result = mysqli_fetch_array($resultData, MYSQLI_ASSOC);

                $sql3 = "select * from feedback_request where candidateId=" . $userId . " and interviewSessionId=" . $row['interviewSessionId'] . " and interviewId=" . $row['interviewId'];
                $feedbackData = mysqli_query($databaseConnection, $sql3);

                $QaQt = mysqli_query($databaseConnection, "select m.interviewId, m.candidateId, m.questionVideoId, CASE WHEN i.categoryType = 9 THEN  (SELECT COUNT( CASE WHEN iqt.attemptStatus is not NULL THEN iqt.questionId ELSE NULL END) FROM interview_questions_transection iqt inner join questions qs on qs.id = iqt.questionId WHERE iqt.interviewId=m.interviewId and qs.deleted_at is null and iqt.deleted_at is null and iqt.deleted_at is null) ELSE (SELECT COUNT(iqt.questionId) FROM interview_questions_transection iqt inner join questions qs on qs.id = iqt.questionId WHERE iqt.interviewId=m.interviewId and qs.deleted_at is null and iqt.deleted_at is null and iqt.deleted_at is null)-1 END as QT, m.interviewSessionId,count(m.interviewSessionId) as QA from mergedVideos m  inner join interview i on i.id = m.interviewId where m.candidateId='" . $row['candidateId'] . "' and interviewId ='" . $row['interviewId'] . "' and m.interviewSessionId is not null group by m.interviewSessionId order by m.interviewSessionId desc");
                $isActive = mysqli_query($databaseConnection, "select distinct(i.isActive) isActive,i.id as interviewIds from interview i inner join mergedVideos m on m.interviewId=i.id where m.interviewId='" . $row['interviewId'] . "' ");
                $qaqt = mysqli_fetch_assoc($QaQt);
                $isActives = mysqli_fetch_assoc($isActive);

                if (mysqli_num_rows($feedbackData) == 0) {
                    array_push($result, array(
                        'interviewId' => $isActives['interviewIds'],
                        'sessionId' => $row['interviewSessionId'],
                        'candidateId' => $row['candidateId'],
                        'fbr_status' => -1,
                        'isActive' => $isActives['isActive'],
                        'QT' => $qaqt['QT'],
                        'QA' => $qaqt['QA'],
                        'sql' => $sql3,

                    ));
                } else {
                    $feedback = mysqli_fetch_assoc($feedbackData);
                    array_push($result, array(
                        'sessionId' => $row['interviewSessionId'],
                        'candidateId' => $row['candidateId'],
                        'fbr_id' => $feedback['id'],
                        'fbr_status' => $feedback['review_status'],
                        'sql' => $sql3,
                        'isActive' => $isActives['isActive'],
                        'QT' => $qaqt['QT'],
                        'QA' => $qaqt['QA'],
                        'interviewId' => $isActives['interviewIds'],
                    ));
                }

                array_push($values, $result);
            }
            $to_encode = $values;
        } else {
            $to_encode = array(
                'result' => "success",
                'response' => "No Interviews found",
                'status' => 0,
                'sql' => $sql1
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Error while retrieving interviewes.",
            'status' => -1
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['getMenteeAttendedInterviews'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $result = array();

        $sql1 = "select i.id, i.name,fr.id as feedbackRequestId,i.productId as i_pid, pt.name as P_name, i.subject_id, fs.favourite_subject as subject_name, m.candidateId, m.interviewSessionId as sessionId, fr.review_status, CONCAT('/review?i=', i.id, '&c=', m.candidateId, '&s=', m.interviewSessionId) as url from mergedVideos m inner join interview i on i.id = m.interviewId inner join product pt on i.productId = pt.id inner join favourite_subject fs on fs.id = i.subject_id inner join panel p on p.id = i.panelId left outer join feedback_request fr on fr.interviewSessionId = m.interviewSessionId left outer join panel e on e.id = fr.delegationId where m.candidateId = '" . $userId . "' and fr.review_status = 2 group by m.interviewSessionId order by m.interviewSessionId ";
        $interviewResult = mysqli_query($databaseConnection, $sql1);

        if (mysqli_num_rows($interviewResult) >= 1) {
            //$values = mysqli_fetch_all($interviewResult, MYSQLI_ASSOC);
            while ($row = mysqli_fetch_array($interviewResult, MYSQLI_ASSOC)) {
                /*Get all expert who provide feedback for candidate in one interview or multiple  change by Narayan 6/1/2021*/
                $reviewedExpertDetails = mysqli_query($databaseConnection, "select * from panel where id in (select expertId from feedback_status_question where feedbackRequestId = '" . $row['feedbackRequestId'] . "')");
                if (mysqli_num_rows($reviewedExpertDetails) > 0) {
                    $reviewedExpertDetailsResult = mysqli_fetch_all($reviewedExpertDetails, MYSQLI_ASSOC);
                    $row['feedbackReviewedExpertDetails'] = $reviewedExpertDetailsResult;
                } else {
                    $row['feedbackReviewedExpertDetails'] = [];
                }
                $condition = "fbr.interviewSessionId = '" . $row['sessionId'] . "' and ";
                $feedbackReportData = getFeedbackReportForHomepage($databaseConnection, $condition);

                if (sizeof($feedbackReportData) == 1) {
                    foreach ($feedbackReportData[0] as $key => $value) {
                        $row[$key] = $value;
                    }
                } else {
                    $row['message'] = $feedbackReportData['message'];
                    $row['query'] = $feedbackReportData['interviewRatings'];
                }
                unset($feedbackReportData);
                $feedbackReportData = array();
                array_push($result, $row);
            }
            $to_encode = $result;
        } else {
            $to_encode = array(
                'result' => "success",
                'response' => "No Interviews found",
                'status' => 0
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Error while retrieving interviewes.",
            'status' => -1
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getEventTopperDetails'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $eventId = $json['eventId'];
        $alldata = array();
        $result = array();

        $sql = "select e.id as eventId, e.name as eventName, e.description as eventDescription, e.startTime, e.endTime, i.* from event e inner join interview i on i.id = e.interviewId where e.id='" . $eventId . "' and e.categoryType = '2' and e.deleted_at is NULL and e.endTime < now()";
        $interviewResult = mysqli_query($databaseConnection, $sql);

        if (mysqli_num_rows($interviewResult) >= 1) {
            //$values=mysqli_fetch_all($interviewResult, MYSQLI_ASSOC);
            $values = mysqli_fetch_assoc($interviewResult);
            $getRankList = "select ewl.*,m.candidateId,u.firstName as name, c.collegeName as college, s.stream, pd.year, m.interviewId from event_winner_list ewl inner join mergedVideos m on ewl.interviewSessionId = m.interviewSessionId inner join users u on u.id = m.candidateId inner join professionaldetails pd on pd.candidateId = u.id inner join colleges c on c.id = pd.college inner join stream s on pd.specialization = s.id where eventId = '" . $eventId . "' group by m.interviewSessionId order by ewl.rank limit 3";
            $getRankListResult = mysqli_query($databaseConnection, $getRankList);
            if (mysqli_num_rows($getRankListResult) >= 1) {
                //$result = mysqli_fetch_all($getRankListResult, MYSQLI_ASSOC);
                while ($result = mysqli_fetch_array($getRankListResult, MYSQLI_ASSOC)) {

                    $interviewRatings = "SELECT 
                              CASE
                                  WHEN fbr.review_status is NULL THEN 'Feedback not Requested'
                                  WHEN fbr.review_status = 2 THEN
                                    CASE
                                        WHEN erpd.observationValueId = 88 THEN 'Need to Improve'
                                        WHEN erpd.observationValueId = 89 THEN 'Good'
                                        WHEN erpd.observationValueId = 90 THEN 'Excellent'
                                    END
                                  WHEN fbr.review_status = 1 THEN 'Feedback in-progess'
                                  WHEN fbr.review_status = 0 THEN 'Feedback is Open'
                                  WHEN fbr.review_status = -2 THEN 'Video Verification'
                                  WHEN fbr.review_status = -3 THEN 'Feedback Verification'
                                  WHEN fbr.review_status = -4 THEN 'Feedback Rejected'
                        END as overallRating, er.expert_review_suggestion as finalFeedback

                        from mergedVideos m inner join interview i on m.interviewId=i.id left outer join feedback_request fbr on fbr.interviewSessionId=m.interviewSessionId inner join users u on u.id=m.candidateId left outer join expert_review er on fbr.id = er.feedback_request_id and er.review_type = 'Final Score' left outer join expert_review_observation_details erpd on erpd.id = er.review_param_valueId

                        where u.active='Y' and u.deleted_at is null and u.id='" . $result['candidateId'] . "' and m.interviewSessionId = '" . $result['interviewSessionId'] . "' group by m.interviewSessionId order by m.interviewSessionId desc";

                    $interviewRatingsQuery = mysqli_query($databaseConnection, $interviewRatings);
                    $interviewRatingsResult = mysqli_fetch_assoc($interviewRatingsQuery);
                    $result['overallRatings'] = $interviewRatingsResult['overallRating'];
                    //$result['finalFeedback'] = $interviewRatingsResult['finalFeedback'];

                    $expert_review_query = mysqli_query($databaseConnection, "SELECT p.id,erpd.observationValueId,pv.observation_values,p.observation_name,p.mandatory,p.key_skill,er.feedback_request_id,er.id as expert_review_id FROM `expert_review_observation_details` as erpd,observation_values as pv ,observation_area as p, expert_review as er WHERE erpd.expertReviewId=er.id and er.feedback_request_id=(select id from feedback_request where `interviewSessionId` = '" . $result['interviewSessionId'] . "') and erpd.observationValueId=pv.id and p.id in (23,10,7,3,2) and pv.observation_id=p.id order by pv.id");

                    if (mysqli_num_rows($expert_review_query) >= 1) {
                        $e_rows = mysqli_fetch_all($expert_review_query, MYSQLI_ASSOC);
                        foreach ($e_rows as $e_row) {
                            $key_skills[$e_row['id']]['id'] = $e_row['id'];
                            $key_skills[$e_row['id']]['observation_name'] = $e_row['observation_name'];

                            $key_skills[$e_row['id']]['observation_values'][] = $e_row['observation_values'];

                            $key_skills[$e_row['id']]['key_skill'] = $e_row['key_skill'];
                            $key_skills[$e_row['id']]['count'] = count($key_skills[$e_row['id']]['observation_values']);
                            $key_skills[$e_row['id']]['mandatory'] = $e_row['mandatory'];
                            $impression = get_impression_score($key_skills[$e_row['id']]['observation_values'], $key_skills[$e_row['id']]['observation_name']);
                            $key_skills[$e_row['id']]['impression'] = $impression['impression'];
                        }
                        if (array_key_exists(2, $key_skills))
                            $result['confidence'] = $key_skills[2]['impression'];
                        else
                            $result['confidence'] = NULL;
                        if (array_key_exists(3, $key_skills))
                            $result['communication'] = $key_skills[3]['impression'];
                        else
                            $result['communication'] = NULL;
                        if (array_key_exists(7, $key_skills))
                            $result['depthOfUnderstanding'] = $key_skills[7]['impression'];
                        else
                            $result['prog_Lang_Know'] = NULL;
                        if (array_key_exists(10, $key_skills))
                            $result['code_Eff'] = $key_skills[10]['impression'];
                        else
                            $result['code_Eff'] = NULL;
                        if (array_key_exists(23, $key_skills))
                            $result['basicConceptUnderstanding'] = $key_skills[23]['impression'];
                        else
                            $result['basicConceptUnderstanding'] = NULL;
                    } else {
                        $result['confidence'] = NULL;
                        $result['communication'] = NULL;
                        $result['depthOfUnderstanding'] = NULL;
                        $result['code_Eff'] = NULL;
                        $result['basicConceptUnderstanding'] = NULL;
                    }
                    array_push($alldata, $result);
                }
            } else {
                $values['status'] = 1;
            }
            $values['winnerList'] = $alldata;

            $to_encode = $values;
        } else {
            $to_encode = array(
                'result' => "success",
                'response' => "No Interviews found",
                'status' => 0,
                'sql' => $sql
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Error while retrieving interviewes.",
            'status' => -1
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getTopperDetails'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $interviewId = $json['interviewId'];
        $alldata = array();
        $result = array();

        $sql = "select * from event e where e.interviewId='" . $interviewId . "' and e.categoryType = '2' and e.deleted_at is NULL and e.endTime < now() ORDER BY id DESC";
        $interviewResult = mysqli_query($databaseConnection, $sql);

        if (mysqli_num_rows($interviewResult) >= 1) {
            //$values=mysqli_fetch_all($interviewResult, MYSQLI_ASSOC);
            $values = mysqli_fetch_assoc($interviewResult);
            $getRankList = "select ewl.*,m.candidateId,u.firstName as name, c.collegeName as college, s.stream, pd.year, m.interviewId from event_winner_list ewl inner join mergedVideos m on ewl.interviewSessionId = m.interviewSessionId inner join users u on u.id = m.candidateId inner join professionaldetails pd on pd.candidateId = u.id inner join colleges c on c.id = pd.college inner join stream s on pd.specialization = s.id where eventId = '" . $values['id'] . "' group by m.interviewSessionId order by ewl.rank limit 3";
            $getRankListResult = mysqli_query($databaseConnection, $getRankList);
            if (mysqli_num_rows($getRankListResult) >= 1) {
                //$result = mysqli_fetch_all($getRankListResult, MYSQLI_ASSOC);
                while ($result = mysqli_fetch_array($getRankListResult, MYSQLI_ASSOC)) {

                    $interviewRatings = "SELECT 
                              CASE
                                  WHEN fbr.review_status is NULL THEN 'Feedback not Requested'
                                  WHEN fbr.review_status = 2 THEN
                                    CASE
                                        WHEN erpd.observationValueId = 88 THEN 'Need to Improve'
                                        WHEN erpd.observationValueId = 89 THEN 'Good'
                                        WHEN erpd.observationValueId = 90 THEN 'Excellent'
                                    END
                                  WHEN fbr.review_status = 1 THEN 'Feedback in-progess'
                                  WHEN fbr.review_status = 0 THEN 'Feedback is Open'
                                  WHEN fbr.review_status = -2 THEN 'Video Verification'
                                  WHEN fbr.review_status = -3 THEN 'Feedback Verification'
                                  WHEN fbr.review_status = -4 THEN 'Feedback Rejected'
                        END as overallRating, er.expert_review_suggestion as finalFeedback

                        from mergedVideos m inner join interview i on m.interviewId=i.id left outer join feedback_request fbr on fbr.interviewSessionId=m.interviewSessionId inner join users u on u.id=m.candidateId left outer join expert_review er on fbr.id = er.feedback_request_id and er.review_type = 'Final Score' left outer join expert_review_observation_details erpd on erpd.id = er.review_param_valueId

                        where u.active='Y' and u.deleted_at is null and u.id='" . $result['candidateId'] . "' and m.interviewSessionId = '" . $result['interviewSessionId'] . "' group by m.interviewSessionId order by m.interviewSessionId desc";

                    $interviewRatingsQuery = mysqli_query($databaseConnection, $interviewRatings);
                    $interviewRatingsResult = mysqli_fetch_assoc($interviewRatingsQuery);
                    $result['overallRatings'] = $interviewRatingsResult['overallRating'];
                    //$result['finalFeedback'] = $interviewRatingsResult['finalFeedback'];

                    $expert_review_query = mysqli_query($databaseConnection, "SELECT p.id,erpd.observationValueId,pv.observation_values,p.observation_name,p.mandatory,p.key_skill,er.feedback_request_id,er.id as expert_review_id FROM `expert_review_observation_details` as erpd,observation_values as pv ,observation_area as p, expert_review as er WHERE erpd.expertReviewId=er.id and er.feedback_request_id=(select id from feedback_request where `interviewSessionId` = '" . $result['interviewSessionId'] . "') and erpd.observationValueId=pv.id and p.id in (23,10,7,3,2) and pv.observation_id=p.id order by pv.id");

                    if (mysqli_num_rows($expert_review_query) >= 1) {
                        $e_rows = mysqli_fetch_all($expert_review_query, MYSQLI_ASSOC);
                        foreach ($e_rows as $e_row) {
                            $key_skills[$e_row['id']]['id'] = $e_row['id'];
                            $key_skills[$e_row['id']]['observation_name'] = $e_row['observation_name'];

                            $key_skills[$e_row['id']]['observation_values'][] = $e_row['observation_values'];

                            $key_skills[$e_row['id']]['key_skill'] = $e_row['key_skill'];
                            $key_skills[$e_row['id']]['count'] = count($key_skills[$e_row['id']]['observation_values']);
                            $key_skills[$e_row['id']]['mandatory'] = $e_row['mandatory'];
                            $impression = get_impression_score($key_skills[$e_row['id']]['observation_values'], $key_skills[$e_row['id']]['observation_name']);
                            $key_skills[$e_row['id']]['impression'] = $impression['impression'];
                        }
                        if (array_key_exists(2, $key_skills))
                            $result['confidence'] = $key_skills[2]['impression'];
                        else
                            $result['confidence'] = NULL;
                        if (array_key_exists(3, $key_skills))
                            $result['communication'] = $key_skills[3]['impression'];
                        else
                            $result['communication'] = NULL;
                        if (array_key_exists(7, $key_skills))
                            $result['depthOfUnderstanding'] = $key_skills[7]['impression'];
                        else
                            $result['prog_Lang_Know'] = NULL;
                        if (array_key_exists(10, $key_skills))
                            $result['code_Eff'] = $key_skills[10]['impression'];
                        else
                            $result['code_Eff'] = NULL;
                        if (array_key_exists(23, $key_skills))
                            $result['basicConceptUnderstanding'] = $key_skills[23]['impression'];
                        else
                            $result['basicConceptUnderstanding'] = NULL;
                    } else {
                        $result['confidence'] = NULL;
                        $result['communication'] = NULL;
                        $result['depthOfUnderstanding'] = NULL;
                        $result['code_Eff'] = NULL;
                        $result['basicConceptUnderstanding'] = NULL;
                    }
                    array_push($alldata, $result);
                }
            } else {
                $values['status'] = 1;
            }
            $values['winnerList'] = $alldata;

            $to_encode = $values;
        } else {
            $to_encode = array(
                'result' => "success",
                'response' => "No Interviews found",
                'status' => 0,
                'sql' => $sql
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Error while retrieving interviewes.",
            'status' => -1
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getEventTotalAttendedInterviewes'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $interviewId = $json['interviewId'];
        $startTime = $json['startTime'];
        $endTime = $json['endTime'];

        $getAttendedInt = "select stream, count(stream) as totalCandidate from (select m.candidateId,u.firstName as name, c.collegeName as college, s.stream, pd.year, m.interviewId from mergedVideos m inner join users u on u.id = m.candidateId inner join professionaldetails pd on pd.candidateId = u.id inner join colleges c on c.id = pd.college inner join stream s on pd.specialization = s.id where m.interviewSessionId >= '" . $startTime . "' and m.interviewSessionId <= '" . $endTime . "' and interviewId = '" . $interviewId . "' group by m.interviewSessionId) as temp group by stream";
        $getAttendedIntResult = mysqli_query($databaseConnection, $getAttendedInt);
        if (mysqli_num_rows($getAttendedIntResult) >= 1) {
            $result = mysqli_fetch_all($getAttendedIntResult, MYSQLI_ASSOC);
            $to_encode = $result;
        } else {
            $to_encode = array(
                'result' => "success",
                'response' => "No Interviews found",
                'status' => 0,
                'sql' => $getAttendedInt
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Error while retrieving interviewes.",
            'status' => -1
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['contactus'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {

        $name = $json['name'];
        $email = $json['email'];
        $mobileNumber = $json['mobileNumber'];
        $message = $json['message'];
        $isResolved = 'N';
        $sql = "INSERT INTO `contactus` 
        (`name`, `email`, `mobileNumber`, `message`, `isResolved`) VALUES 
        ('$name', '$email', '$mobileNumber', '$message', '$isResolved');";
        $usersQuery = mysqli_query($databaseConnection, $sql);
        if ($usersQuery) {
            $userId = mysqli_insert_id($databaseConnection);

            sendContactusEmail($name, $email, $mobileNumber, $message);
            $to_encode = array(
                'result' => "Success",
                'message' => "Request submitted.",
                'status' => 1
            );
        } else {
            $to_encode = array(
                'result' => "error",
                'errorCode' => "request Creation failed.",
                'status' => -1,
                'query' => $sql
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "request submission failed."
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['becomeInterviewer'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {

        $name = $json['name'];
        $email = $json['email'];
        $mobileNumber = $json['mobileNumber'];
        $qualifiaction = $json['qualifiaction'];
        $college = $json['college'];
        $experience = $json['experience'];
        $skills = $json['skills'];
        $companies = $json['companies'];
        $baselocation = $json['baselocation'];
        $linkedinProfile = $json['linkedinProfile'];

        $query = "INSERT INTO become_interviewer(`name`,`email`,`mobileNumber`,`qualifiaction`,`college`,`experience`,`skills`,`companies`,`baselocation`,`linkedinProfile`) VALUES('$name','$email','$mobileNumber','$qualifiaction','$college','$experience','$skills','$companies','$baselocation','$linkedinProfile')";
        $becomeInterviewerQuery = mysqli_query($databaseConnection, $query);
        if ($becomeInterviewerQuery) {
            $Id = mysqli_insert_id($databaseConnection);

            sendInterviewerEmail($name, $email, $mobileNumber, $qualifiaction, $college, $experience, $skills, $companies, $baselocation, $linkedinProfile);
            $to_encode = array(
                'result' => "Success",
                'message' => "Request submitted.",
                'status' => 1
            );
        } else {
            $to_encode = array(
                'result' => "error",
                'message' => "data submission failed.",
                'status' => -1
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "request submission failed.",
            'status' => -1
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['writeMessageIntoLogFile'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['candidateId'];
        $currentPageURL = $json['currentPageURL'];
        $videoName = $json['videoName'];
        $errorLog = $json['errorLog'];
        $data = "select * from `users` where id='" . $candidateId . "'";
        $query = mysqli_query($databaseConnection, $data);
        if (mysqli_num_rows($query) >= 1) {
            $row = mysqli_fetch_assoc($query);
            $error = date('[l, d M Y h:i:s A] :') . ' Unable to publish Recording Video. Candidate Id : ' . $row['id'] . ', Name : ' . $row['firstName'] . ', Email Id : ' . $row['emailId'] . ', Mobile No : ' . $row['mobileNumber'] . ', Link : ' . $currentPageURL . ', Video Name : ' . $videoName . ', Error Log Message : ' . $errorLog;
            if ($server == 'live') {
                error_log($error . "\n", 3, "../../../home/ubuntu/error.log");
            }
            $mailSubject = $emailApiHost . ' - Issue while recording video';
            sendRecordingErrorEmail($error, $emailApiHost, $mailSubject);
            $to_encode = array(
                'result' => "success",
                'errorCode' => "error saved.",
                'status' => 1
            );
        } else {
            $to_encode = array(
                'result' => "error",
                'errorCode' => "error submission failed.",
                'status' => 0
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "error submission failed.",
            'status' => -1
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['writeResponseIntoLogFile'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['candidateId'];
        $currentPageURL = $json['currentPageURL'];
        $interviewId = $json['interviewId'];
        $status = $json['response'];
        $qId = $json['questionId'];

        $data = "select * from `users` where id='" . $candidateId . "'";
        $query = mysqli_query($databaseConnection, $data);
        if (mysqli_num_rows($query) >= 1) {
            $row = mysqli_fetch_assoc($query);
            $error = date('[l, d M Y h:i:s A] :') . ' Response of Candidate Id : ' . $row['id'] . ',InterviewId:' . $interviewId . ',Link : ' . $currentPageURL . ',questionId:' . $qId . ', Action : ' . $status;
            if ($server == 'live') {
                error_log($error . "\n", 3, "../../../home/ubuntu/interviewInfo.log");
            }
            $to_encode = array(
                'result' => "success",
                'errorCode' => "response saved.",
                'status' => 1
            );
        } else {
            $to_encode = array(
                'result' => "error",
                'errorCode' => "response submission failed.",
                'status' => 0
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "response submission failed.",
            'status' => -1
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['requestInterviewFeedback'])) {
    // This function is used for interview feedback
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    if (isset($json)) {
        $interviewId = $json['interviewId'];
        $candidateId = $json['candidateId'];
        $interviewSessionId = $json['interviewSessionId'];
        $userId = $json['userId'];
        $createdAt = $json['createdAt'];
        $isAccepted = $json['isAccepted'];
        $userType = $json['currentUserType'];
        $preInterviewId = $json['preInterviewId'];
        // $currentAssessmentType = array_key_exists('currentAssessmentType', $json) ? $json['currentAssessmentType']: 'goprac';
        $currentAssessmentType = $json['currentAssessmentType'];
        // echo $currentAssessmentType;
        $contactDetails = array();
        $contact = array();
        $checkReasonOfRejection = array_key_exists('reasonOfRejection', $json) ? $json['reasonOfRejection'] : 'incompleteAnswer';
        $checkSuggestion = array_key_exists('suggestion', $json) ? $json['suggestion'] : 'Testing';
        $fbr_status = array_key_exists('fbr_status', $json) ? $json['fbr_status'] : -4;

        if ($userId == null) {
            $userId = $json['candidateId'];
        }
        $userSubscriptionDetails = getSubsciptionDetailsOnAssessment($databaseConnection, $candidateId);
        $userQuery = "SELECT CONCAT(firstName, ' ', IFNULL(lastName, '')) AS candidateName, emailId AS candidateEmail, mobileNumber AS candidateMobileNumber FROM users WHERE id = " . $candidateId;
        $userQueryResult = mysqli_query($databaseConnection, $userQuery);
        $candidateDetails = $userQueryResult->fetch_assoc();

        // $interviewQuery = "SELECT concat('https://goprac.com/companyDetailsx?a=null&preId=',i.preInterviewId) as interviewLink,i.id AS interviewId, i.name AS interviewname,i.assessmenttype as currentAssessmentType,i.productId as productId,i.sector_id,i.companyId,i.description AS interviewDescription, " . " p.id AS panelId, p.name AS panelName, p.emailid AS panelEmail, p.phonenumber AS panelPhoneNumber " . " FROM interview AS i, panel AS p " . " WHERE p.id = i.panelId AND i.id = " . $interviewId;
        $interviewQuery = "SELECT concat('https://goprac.com/job?p=',i.preInterviewId) as interviewLink,i.id AS interviewId, i.name AS interviewname,i.assessmenttype as currentAssessmentType,i.productId as productId,i.sector_id,i.companyId,i.description AS interviewDescription, " . " p.id AS panelId, p.name AS panelName, p.emailid AS panelEmail, p.phonenumber AS panelPhoneNumber " . " FROM interview AS i, panel AS p " . " WHERE p.id = i.panelId AND i.id = " . $interviewId;
        $interviewQueryResult = mysqli_query($databaseConnection, $interviewQuery);
        $interviewDetails = $interviewQueryResult->fetch_assoc();


        if ($interviewDetails) {
            if ($userType == 'admin') {
                $query3 = "SELECT fr.*,p.name as delegatedName,p.emailId as delegatedEmailId from feedback_request fr left outer join panel p on fr.delegationId = p.id WHERE `interviewSessionId` = " . $interviewSessionId . " AND `candidateId` = " . $candidateId . " AND `interviewId` = " . $interviewId;

                $requestReviewSelectQryResult = mysqli_query($databaseConnection, $query3);

                if (mysqli_num_rows($requestReviewSelectQryResult) >= 1) {

                    $feedbackData = mysqli_fetch_assoc($requestReviewSelectQryResult);

                    $assessmentType = mysqli_query($databaseConnection, "SELECT i.assessmenttype FROM interview i INNER JOIN feedback_request fr ON fr.interviewId = i.id WHERE fr.id IN ('" . $feedbackData['id'] . "' ) ");

                    $assessmentWhere = "";
                    $assessmentJoin = "";
                    if (mysqli_num_rows($assessmentType) > 0) {
                        $assessmentTypeData = mysqli_fetch_all($assessmentType, MYSQLI_ASSOC)[0];

                        $assessmentJoin = " INNER JOIN questions q ON q.id = m.questionId INNER JOIN favourite_subject fs ON fs.id = q.subjectId";
                        if ($assessmentTypeData['assessmenttype'] == 'stepper') {
                            $assessmentWhere = " AND fs.id IN (178)";
                        }
                    }
                    if ($feedbackData['review_status'] == -2) {
                        if ($isAccepted == 'Y') {
                            $fbr_status = 0;
                            $query2 = "UPDATE feedback_request SET `review_status` = '0' WHERE `interviewSessionId` = " . $interviewSessionId . " AND `candidateId` = " . $candidateId . " AND `interviewId` = " . $interviewId;
                        } else {
                            $fbr_status = -4;
                            $query2 = "UPDATE feedback_request SET `review_status` = '-4', `rejectedBy`='$userId', `reasonOfRejection` = '" . $checkReasonOfRejection . "', `suggestion` = '" . addslashes($checkSuggestion) . "' WHERE `interviewSessionId` = " . $interviewSessionId . " AND `candidateId` = " . $candidateId . " AND `interviewId` = " . $interviewId;

                        }
                        $requestReviewUpdateQryResult = mysqli_query($databaseConnection, $query2);

                        if ($requestReviewUpdateQryResult) {

                            /* this is Added by Narayan to check rejected interview employability */
                            $NewEmployabilityReport = updateNewEmployability($databaseConnection, $interviewSessionId, $interviewId, $candidateId, $checkReasonOfRejection);



                            $date = new DateTime(date("Y-m-d"));
                            $date->modify('+7 day');
                            $fbDeliveryDATE = $date->format('Y-m-d');

                            if ($feedbackData['delegatedEmailId'] == NULL) {
                                $contact['contactEmail'] = $interviewDetails['panelEmail'];
                                $contact['contactName'] = $interviewDetails['panelName'];
                            } else {
                                $contact['contactEmail'] = $feedbackData['delegatedName'];
                                $contact['contactName'] = $feedbackData['delegatedEmailId'];
                            }

                            if ($fbr_status == 0) {
                                array_push($contactDetails, $contact);

                                // $fbrQuery = "INSERT INTO feedback_status_question(feedbackRequestId, questionId, review_status) select fr.id as feedbackRequestId, m.questionId, 0 as review_status from feedback_request fr inner join mergedVideos m on m.interviewSessionId = fr.interviewSessionId where fr.id = '" . $feedbackData['id'] . "' and m.questionId not in ( select questionId from feedback_status_question where feedbackRequestId ='" . $feedbackData['id'] . "' )";
                                // $setQuestionStatus = mysqli_query($databaseConnection, $fbrQuery);

                                //query is used to check speechAce status

                                $speechAceQuery = mysqli_query($databaseConnection, "select pr.speechAceJob,pr.id as preInterviewId from preInterview pr inner join interview i on i.preInterviewId=pr.id where i.id=" . $interviewId . "");

                                if (mysqli_num_rows($speechAceQuery) > 0) {

                                    $speechAceStatus = mysqli_fetch_assoc($speechAceQuery);

                                    if ($speechAceStatus['speechAceJob'] == 'Y') {

                                        $fbrQuery = "INSERT INTO feedback_status_question(feedbackRequestId, questionId, review_status) select fr.id as feedbackRequestId, m.questionId, 0 as review_status from feedback_request fr inner join mergedVideos m on m.interviewSessionId = fr.interviewSessionId " . $assessmentJoin . " where fr.id = '" . $feedbackData['id'] . "' " . $assessmentWhere . " and m.questionId not in ( select questionId from feedback_status_question where feedbackRequestId='" . $feedbackData['id'] . "' )";

                                        $setQuestionStatus = mysqli_query($databaseConnection, $fbrQuery);

                                        $updateFeedbackStatus = mysqli_query($databaseConnection, "UPDATE feedback_status_question fsq inner join questions q on q.id=fsq.questionId set review_status=9 where fsq.feedbackRequestId='" . $feedbackData['id'] . "' and fsq.review_status not in (1,2) and q.subjectId=178");

                                    } else {

                                        $fbrQuery = "INSERT INTO feedback_status_question(feedbackRequestId, questionId, review_status) select fr.id as feedbackRequestId, m.questionId, 0 as review_status from feedback_request fr inner join mergedVideos m on m.interviewSessionId = fr.interviewSessionId " . $assessmentJoin . " where fr.id = '" . $feedbackData['id'] . "' " . $assessmentWhere . " and m.questionId not in ( select questionId from feedback_status_question where feedbackRequestId='" . $feedbackData['id'] . "' )";

                                        $setQuestionStatus = mysqli_query($databaseConnection, $fbrQuery);

                                    }
                                }




                                // // sibin for checking any bad cluster questions not to be delegated 08 DEC 2022

                                if ($setQuestionStatus) {
                                    $fsqQuestions = array();

                                    $feedbackStatusQuestionsQuery = mysqli_query($databaseConnection, "select m.questionId,fs.id as subjectId,q.isFollowUp,null as questionTag from feedback_request fr inner join mergedVideos m on m.interviewSessionId = fr.interviewSessionId INNER JOIN questions q ON q.id = m.questionId INNER JOIN favourite_subject fs ON fs.id = q.subjectId where fr.id = '" . $feedbackData['id'] . "' and m.questionId not in ( select questionId from expert_review where feedback_request_id='" . $feedbackData['id'] . "')");
                                    // echo $feedbackStatusQuestionsQuery;

                                    $expertReviewQuestionsQuery = mysqli_query($databaseConnection, "SELECT er.questionId,fs.id as subjectId,q.isFollowUp,er.questionTag from expert_review er inner join questions q on q.id=er.questionid inner join favourite_subject fs on fs.id=q.subjectId where er.feedback_request_id='" . $feedbackData['id'] . "'");

                                    if (mysqli_num_rows($feedbackStatusQuestionsQuery) > 0) {
                                        while ($row = mysqli_fetch_assoc($feedbackStatusQuestionsQuery)) {
                                            $fsqQuestions[] = $row;
                                        }
                                    }
                                    if (mysqli_num_rows($expertReviewQuestionsQuery) > 0) {
                                        while ($row = mysqli_fetch_assoc($expertReviewQuestionsQuery)) {
                                            $fsqQuestions[] = $row;
                                        }
                                    }

                                    $assignClusterId = parentChildClusterId($fsqQuestions);
                                    $questionsWithClusterId = $assignClusterId[0];
                                    $totalParentQuestions = $assignClusterId[1];

                                    for ($i = 0; $i < $totalParentQuestions; $i++) {
                                        $questionsCluster = array();
                                        $val = $i;
                                        for ($k = 0; $k < sizeof($questionsWithClusterId); $k++) {
                                            if ($questionsWithClusterId[$k]['clusterID'] == $val) {
                                                array_push($questionsCluster, $questionsWithClusterId[$k]);
                                            }
                                        }

                                        checkClusterGoodBad($databaseConnection, $questionsCluster, $feedbackData['id'], $techIssueTolerance);
                                        unset($questionsCluster);
                                    }

                                    $sql1 = mysqli_query($databaseConnection, "SELECT review_status FROM feedback_status_question where feedbackRequestId='" . $feedbackData['id'] . "' group by review_status");

                                    $interviewExpire = mysqli_query($databaseConnection, "select case when pr.interviewExpireDate is not null then date_format(pr.interviewExpireDate,'%W,%d %M %h:%m %p') else date_format(DATE_ADD(now(), INTERVAL 3 DAY),'%W,%d %M %h:%m %p') end as interviewExpireDate from preInterview pr left join interview i on i.preInterviewId=pr.id Where i.id='" . $interviewId . "'");

                                    $interviewExpireResult = mysqli_fetch_assoc($interviewExpire);

                                    if (mysqli_num_rows($sql1) == 1) {
                                        $feedbackDataStatus = mysqli_fetch_assoc($sql1);
                                        if ($feedbackDataStatus['review_status'] == 2) {
                                            $sql2 = mysqli_query($databaseConnection, "SELECT questionTag FROM expert_review where feedback_request_id='" . $feedbackData['id'] . "' and questionTag !='skipped' group by questionTag");
                                            if (mysqli_num_rows($sql2) == 1) {
                                                $expertReviewStatus = mysqli_fetch_assoc($sql2);
                                                if ($expertReviewStatus['questionTag'] == 'technicalIssue') {
                                                    $updateFeedbackRequest = mysqli_query($databaseConnection, "update feedback_request set review_status=-4,reasonOfRejection='technicalIssue',isEmailSent='Y' Where id='" . $feedbackData['id'] . "'");
                                                    // mail for tech issue rejected 20 DEC 2022 
                                                    // email sending vijay 08 July 2023 
                                                    $RecruitingComapanyName = 'Support Team';
                                                    // Convert timestamp to date and time
                                                    // Convert milliseconds to seconds
                                                    $seconds = $interviewSessionId / 1000;

                                                    // Create a DateTime object
                                                    $datetime = new DateTime();
                                                    $datetime->setTimestamp($seconds);

                                                    // Separate date and time
                                                    $date = $datetime->format('Y-m-d');
                                                    $time = $datetime->format('h:i:s A');
                                                    // $date = date('Y-m-d', $interviewSessionId);
                                                    // $time = date('H:i:s', $interviewSessionId);
                                                    $templateQuery = "select subject,details from candidateEmailTemplate where status = 'Technical Issue' ";

                                                    $templateQueryResult = mysqli_query($databaseConnection, $templateQuery);
                                                    $msg = mysqli_fetch_assoc($templateQueryResult);
                                                    $placeholders = array('{interview name}', '{student name}', '{time}', '{date}', 'interviewLink', 'interviewLink', '{timedate}', '{interview}');
                                                    $values = array($interviewDetails['interviewname'], $candidateDetails['candidateName'], $time, $date, $interviewDetails['interviewLink'], $interviewDetails['interviewLink'], $interviewExpireResult['interviewExpireDate'], $RecruitingComapanyName);

                                                    $template = str_replace($placeholders, $values, $msg);
                                                    // email sending vijay 08 July 2023 
                                                    sendEmailToUser($candidateDetails['candidateEmail'], null, $template['subject'], $template['details']);
                                                    // for whatsapp messages
                                                    $watidata = array();
                                                    $url = $interviewDetails['interviewLink'];
                                                    $components = explode('/', $url);
                                                    $modifiedUrl = isset($components[3]) ? $components[3] : '';
                                                    $watidata["candidateName"] = $candidateDetails['candidateName'];
                                                    $watidata["companyname"] = $interviewDetails['interviewname'];
                                                    $watidata["scheduledTime"] = $time;
                                                    $watidata["scheduleDate"] = $date;
                                                    $watidata["interviewexpiredate"] = $interviewExpireResult['interviewExpireDate'];
                                                    //modify by shrikant : 18/1/2024
                                                    // $watidata["interviewLink"] = $modifiedUrl;
                                                    $watidata["interviewLink"] = $url;
                                                    $watidata["sender"] = $RecruitingComapanyName;
                                                    whatsAppMsg($databaseConnection, $candidateDetails['candidateMobileNumber'], $watidata, "Technical Issue");
                                                } else if ($expertReviewStatus['questionTag'] == 'nonSerious') {
                                                    $updateFeedbackRequest = mysqli_query($databaseConnection, "update feedback_request set review_status=2 Where id='" . $feedbackData['id'] . "'");
                                                    // mail for Non serious interview 23 JAN 2023
                                                    $message = "<p>Dear " . $candidateDetails['candidateName'] . ",</p>

                                                 <p>Thanks for practicing interviews on GoPrac.com. Your interview response to the interview named " . $interviewDetails['interviewname'] . " can't be reviewed by the expert. This is because, we feel that you have not taken this interview seriously.</p>
                                                 <p>In case you have any doubt , please call us +91-9731107508.</p>
                                                 <p> Thanks & Regards</p>
                                                 <p>GoPrac Team.</p>
                                                ";
                                                    sendEmailToUser($candidateDetails['candidateEmail'], null, 'Feedback Completed', $message);
                                                }
                                            } else {
                                                $issueCount = mysqli_query($databaseConnection, "SELECT count(case when questionTag='nonSerious' then 'nonSerious' end) as nonSeriousCount,count(case when questionTag='technicalIssue' then 'technicalIssue' end) as technicalIssueCount FROM expert_review where feedback_request_id='" . $feedbackData['id'] . "' and questionTag !='skipped'");

                                                if (mysqli_num_rows($issueCount) == 1) {
                                                    $issueCountData = mysqli_fetch_assoc($issueCount);

                                                    if ($issueCountData['technicalIssueCount'] > $issueCountData['nonSeriousCount']) {
                                                        $updateFeedbackRequest = mysqli_query($databaseConnection, "update feedback_request set review_status=-4,reasonOfRejection='technicalIssue',isEmailSent='Y' Where id='" . $feedbackData['id'] . "'");

                                                        // mail for tech issue rejected 20 DEC 2022 
                                                        // $message = "<p>Dear " . $candidateDetails['candidateName'] . ",</p>

                                                        //          <p>Thanks for taking  interview on GoPrac.com. Your interview response to the interview named " . $interviewDetails['interviewname'] . " can't be reviewed by the expert because, the quality of your video is poor.</p>
                                                        //          <p><b>Advice :</b> Your internet connection is not good. Please RE-TAKE the interview with good internet connection. Minimum internet bandwidth required to record your responses is 1 MBPS. In case you have any doubt , please call us +91-9731107508.</p>
                                                        //          <p> Thanks & Regards</p>
                                                        //          <p>GoPrac Team.</p>
                                                        //         ";
                                                        // mail for tech issue rejected 20 DEC 2022 
                                                        // email sending vijay 08 July 2023 
                                                        $RecruitingComapanyName = 'Support Team';
                                                        // Convert timestamp to date and time
                                                        $seconds = $interviewSessionId / 1000;

                                                        // Create a DateTime object
                                                        $datetime = new DateTime();
                                                        $datetime->setTimestamp($seconds);

                                                        // Separate date and time
                                                        $date = $datetime->format('l, F j, Y');
                                                        $time = $datetime->format('h:i A');
                                                        // $date = date('Y-m-d', $interviewSessionId);
                                                        // $time = date('H:i:s', $interviewSessionId);
                                                        $templateQuery = "select subject,details from candidateEmailTemplate where status = 'Technical Issue' ";

                                                        $templateQueryResult = mysqli_query($databaseConnection, $templateQuery);
                                                        $msg = mysqli_fetch_assoc($templateQueryResult);
                                                        $placeholders = array('{interview name}', '{student name}', '{time}', '{date}', 'interviewLink', 'interviewLink', '{timedate}', '{interview}');
                                                        $values = array($interviewDetails['interviewname'], $candidateDetails['candidateName'], $time, $date, $interviewDetails['interviewLink'], $interviewDetails['interviewLink'], $interviewExpireResult['interviewExpireDate'], $RecruitingComapanyName);
                                                        $template = str_replace($placeholders, $values, $msg);
                                                        // email sending vijay 08 July 2023 
                                                        sendEmailToUser($candidateDetails['candidateEmail'], null, $template['subject'], $template['details']);
                                                        // for whatsapp messages
                                                        $watidata = array();
                                                        $url = $interviewDetails['interviewLink'];
                                                        $components = explode('/', $url);
                                                        $modifiedUrl = isset($components[3]) ? $components[3] : '';
                                                        $watidata["candidateName"] = $candidateDetails['candidateName'];
                                                        $watidata["companyname"] = $interviewDetails['interviewname'];
                                                        $watidata["scheduledTime"] = $time;
                                                        $watidata["scheduleDate"] = $date;
                                                        $watidata["interviewexpiredate"] = $interviewExpireResult['interviewExpireDate'];
                                                        //modify by shrikant : 18/1/2024
                                                        // $watidata["interviewLink"] = $modifiedUrl;
                                                        $watidata["interviewLink"] = $url;
                                                        $watidata["sender"] = $RecruitingComapanyName;
                                                        whatsAppMsg($databaseConnection, $candidateDetails['candidateMobileNumber'], $watidata, "Technical Issue");
                                                    }
                                                    // else{
                                                    //     $updateFeedbackRequest = mysqli_query($databaseConnection, "update feedback_request set review_status=2 Where id='" . $feedbackData['id'] . "'");



                                                    // mail for Non serious interview 23 JAN 2023
                                                    //         $message = "<p>Dear " . $candidateDetails['candidateName'] . ",</p>

                                                    //                  <p>Thanks for practicing interviews on GoPrac.com. Your interview response to the interview named " . $interviewDetails['interviewname'] . " can't be reviewed by the expert. This is because, we feel that you have not taken this interview seriously.</p>
                                                    //                  <p>In case you have any doubt , please call us +91-9731107508.</p>
                                                    //                  <p> Thanks & Regards</p>
                                                    //                  <p>GoPrac Team.</p>
                                                    //                 ";
                                                    //    sendEmailToUser($candidateDetails['candidateEmail'], null, 'Feedback Completed', $message);
                                                    //         }
                                                }
                                            }
                                        }
                                    }


                                }

                                // // end

                                // if($assessmentTypeData['assessmenttype'] == 'stepper') {
                                //     $fbrQuery = "update feedback_status_question fsq inner join questions q on q.id=fsq.questionId inner join favourite_subject fs on q.subjectId=fs.id set review_status=9 where fs.id != 178 and fsq.expertId is null and feedbackRequestId='" . $feedbackData['id'] . "'";
                                //     $setQuestionStatus = mysqli_query($databaseConnection, $fbrQuery);
                                // }

                                $setPriorityResult = mysqli_query($databaseConnection, "update feedback_request fr inner join (select fr.id, fr.interviewSessionId, fr.interviewId, fr.candidateId, count(distinct case when q.priorityStatus ='1' then q.id else null end) as totalQuesPriority from feedback_request fr inner join feedback_status_question fsq on fsq.feedbackRequestId = fr.id inner join questions q on q.id = fsq.questionId where fr.review_status in (0,1) and fr.id = '" . $feedbackData['id'] . "' group by fr.id having (totalQuesPriority > 0 or '" . $userSubscriptionDetails['s_endDifference'] . "' >= 0)) temp on fr.id = temp.id set fr.priority = 1;");
                                /* added by Narayan 2/7/2021 for make question Flag high if it is not ready to use plus */
                                $setQuestionPriorityStatus = mysqli_query($databaseConnection, "UPDATE questions set priorityStatus='1' where id IN(select temp.id from (select q.id from feedback_request fr  inner join feedback_status_question fsq on fsq.feedbackRequestId= fr.id inner join questions q on fsq.questionId = q.id where fr.id = '" . $feedbackData['id'] . "'  and q.priorityStatus = 0 and fr.review_status in (0,1) and  (q.expertAdvice is null or q.youtubeId = '314664775' or q.eligibleStreamId IS  NULL or q.subjectId IS NULL or  q.conceptId IS  NULL or  q.key_skill_id IS NULL or  q.topic_id IS  NULL or  q.isWbRequired IS  NULL or q.questionLevel IS  NULL) and (q.peerResponseVideo is  null or q.mbr_id = '0')  having '" . $userSubscriptionDetails['s_endDifference'] . "' >= 0 ) as temp);");
                            } else {
                                if ($checkReasonOfRejection == 'technicalIssue') {
                                    $reasonOfRejection = 'Technical Issue';
                                } else if ($checkReasonOfRejection == 'studentIsIndulgedInMalpractice') {
                                    $reasonOfRejection = 'Student is Indulged in Malpractice';
                                } else if ($checkReasonOfRejection == 'incompleteInterview') {
                                    $reasonOfRejection = 'incomplete interview';
                                } else if ($checkReasonOfRejection == 'incompleteAnswer') {
                                    $reasonOfRejection = 'Incomplete Answer';
                                } else if ($checkReasonOfRejection == 'nonSeriousInterview') {
                                    $reasonOfRejection = 'Non Serious Interview';
                                } else if ($checkReasonOfRejection == 'assessmentOnHold') {
                                    $reasonOfRejection = 'Assessment on Hold';
                                } else if ($checkReasonOfRejection == 'limitedFreeAssessment') {
                                    $reasonOfRejection = 'Limited FREE Assessment';
                                } else if ($checkReasonOfRejection == 'fixedNoOfAssessment') {
                                    $reasonOfRejection = 'Completed the Max no of Assessments';
                                } else if ($checkReasonOfRejection == 'outOfProductScope') {
                                    $reasonOfRejection = 'Out of Product Scope';
                                } else if ($checkReasonOfRejection == 'yourPracticeDurationIsDue') {
                                    $reasonOfRejection = 'Your Practice Duration is Due';
                                } else if ($checkReasonOfRejection == 'anslessno') {
                                    $reasonOfRejection = 'Answered Less No. of Questions';
                                } else if ($checkReasonOfRejection == 'linkexpire') {
                                    $reasonOfRejection = 'Your Interview link is Expired';
                                } else if ($checkReasonOfRejection == 'notEligible') {
                                    $reasonOfRejection = 'Your Not Eligible for this Job';
                                } else if ($checkReasonOfRejection == 'duplicateAttempt') {
                                    $reasonOfRejection = 'Duplicate Attempt';
                                } else {
                                    $reasonOfRejection = 'unauthorized user';
                                }

                                $suggestion = $checkSuggestion;

                                if ($checkReasonOfRejection == 'nonSeriousInterview') {
                                    $message = "<p>Dear " . $candidateDetails['candidateName'] . ",</p>

                                                 <p>Thanks for practicing interviews on GoPrac.com. Your interview response to the interview named " . $interviewDetails['interviewname'] . " can't be reviewed by the expert. This is because, we feel that you have not taken this interview seriously.</p>
                                                 <p><b>Advice :</b> " . $suggestion . ". In case you have any doubt , please call us +91-9731107508.</p>
                                                 <p> Thanks & Regards</p>
                                                 <p>GoPrac Team.</p>
                                                ";
                                    sendEmailToUser($candidateDetails['candidateEmail'], null, 'Feedback Request Rejected', $message);
                                } else if ($checkReasonOfRejection == 'fixedNoOfAssessment') {
                                    $message = "<p>Dear " . $candidateDetails['candidateName'] . ",</p>
                                    
                                    <p>Thanks for practicing interviews on GoPrac.com. However, expert feedback of your interview response to the interview named " . $interviewDetails['interviewname'] . "  is not considered for Assessment because we have already provided you the maximum no of assessments subscribed by you. </p>
                                    <p><b>Advice :</b> " . $suggestion . ". In case you have any doubt , please call us +91-9731107508.</p>
                                    <p> Thanks & Regards</p>
                                    <p>GoPrac Team.</p>
                                   ";
                                    sendEmailToUser($candidateDetails['candidateEmail'], null, 'Feedback Request Rejected', $message);
                                } else if ($checkReasonOfRejection == 'assessmentOnHold') {
                                    $message = "<p>Dear " . $candidateDetails['candidateName'] . ",</p>
                                    
                                    
                                    <p>Thanks for attempting interview on GoPrac.com. However, expert feedback on your interview is on hold. </p>
                                    <p><b>Advice :</b> " . $suggestion . "</p>
                                    <p> Thanks & Regards <br/> GoPrac Team.</p>
                                   ";
                                    sendEmailToUser($candidateDetails['candidateEmail'], null, 'Feedback Request Rejected', $message);
                                } else if ($checkReasonOfRejection == 'limitedFreeAssessment') {
                                    $message = "<p>Dear " . $candidateDetails['candidateName'] . ",</p>

                                    <p>Thanks for practicing interviews on GoPrac.com. However, expert feedback of your interview response to the interview named " . $interviewDetails['interviewname'] . "  is on hold because Assessments are limited during FREE trial. </p>
                                    <p><b>Advice :</b> " . $suggestion . ". In case you have any doubt , please call us +91-9731107508.</p>
                                    <p> Thanks & Regards</p>
                                    <p>GoPrac Team.</p>
                                   ";
                                    //    sendEmailToUser($candidateDetails['candidateEmail'], null, 'Feedback Request Rejected', $message);
                                } else if ($checkReasonOfRejection == 'outOfProductScope') {
                                    $message = "<p>Dear " . $candidateDetails['candidateName'] . ",</p>

                                    <p>Thanks for practicing interviews on GoPrac.com. However, expert feedback of your interview response to the interview named " . $interviewDetails['interviewname'] . "   is not considered for Assessment because the interview given by you is NOT in the scope of your product.</p>
                                    <p><b>Advice :</b> " . $suggestion . ". In case you have any doubt , please call us +91-9731107508.</p>
                                    <p> Thanks & Regards</p>
                                    <p>GoPrac Team.</p>
                                   ";
                                    sendEmailToUser($candidateDetails['candidateEmail'], null, 'Feedback Request Rejected', $message);
                                } else if ($checkReasonOfRejection == 'yourPracticeDurationIsDue') {
                                    $message = "<p>Dear " . $candidateDetails['candidateName'] . ",</p>

                                    <p>Thanks for practicing interviews on GoPrac.com. However, expert feedback of your interview response to the interview named " . $interviewDetails['interviewname'] . "    is not considered for Assessment because your Practice Duration is Due.</p>
                                    <p><b>Advice :</b> " . $suggestion . ". In case you have any doubt , please call us +91-9731107508.</p>
                                    <p> Thanks & Regards</p>
                                    <p>GoPrac Team.</p>
                                   ";
                                    sendEmailToUser($candidateDetails['candidateEmail'], null, 'Feedback Request Rejected', $message);
                                } else if ($checkReasonOfRejection == 'anslessno') {
                                    $message = "<p>Dear " . $candidateDetails['candidateName'] . ",</p>

                                    <p>Thanks for practicing interviews on GoPrac.com. Your interview response to the interview named" . $interviewDetails['interviewname'] . " cannot be reviewed by the expert.This is because your answered less number of questions.</p>
                                    <p><b>Advice :</b> " . $suggestion . ". In case you have any doubt , please call us +91-9731107508.</p>
                                    <p> Thanks & Regards</p>
                                    <p>GoPrac Team.</p>
                                   ";
                                    sendEmailToUser($candidateDetails['candidateEmail'], null, 'Feedback Request Rejected', $message);
                                } else if ($checkReasonOfRejection == 'linkexpire') {
                                    $message = "<p>Dear " . $candidateDetails['candidateName'] . ",</p>

                                    <p>Thanks for practicing interviews on GoPrac.com. Your interview response to the interview named" . $interviewDetails['interviewname'] . " cannot be reviewed by the expert.This is because Your Interview link is Expired.</p>
                                    <p><b>Advice :</b> " . $suggestion . ". In case you have any doubt , please call us +91-9731107508.</p>
                                    <p> Thanks & Regards</p>
                                    <p>GoPrac Team.</p>
                                   ";
                                    sendEmailToUser($candidateDetails['candidateEmail'], null, 'Feedback Request Rejected', $message);
                                } else if ($checkReasonOfRejection == 'notEligible') {
                                    $message = "<p>Dear " . $candidateDetails['candidateName'] . ",</p>

                                    <p>Thanks for practicing interviews on GoPrac.com. Your interview response to the interview named" . $interviewDetails['interviewname'] . " cannot be reviewed by the expert.This is because Your Not Eligible for this Job.</p>
                                    <p><b>Advice :</b> " . $suggestion . ". In case you have any doubt , please call us +91-9731107508.</p>
                                    <p> Thanks & Regards</p>
                                    <p>GoPrac Team.</p>
                                   ";
                                    sendEmailToUser($candidateDetails['candidateEmail'], null, 'Feedback Request Rejected', $message);
                                } else {
                                    //    studentReviewWithFeedbackEmail($candidateDetails, $interviewDetails, $fbDeliveryDATE, $reasonOfRejection, $suggestion, $emailApiHost); //for student
                                }
                            }
                        }
                    }
                    if ($feedbackData['review_status'] == -4) {
                        if ($isAccepted == 'Y') {
                            $fbr_status = -2;
                            if ($currentAssessmentType == 'goprac' || $currentAssessmentType == 'stepper') {
                                $query4 = "UPDATE feedback_request set review_status = '-2' , createdBy ='" . $userId . "' , rejectedBy = NULL ,  ReasonOfRejection =NULL,suggestion=NULL where  interviewSessionId ='" . $interviewSessionId . "'  and interviewId ='" . $interviewId . "' and candidateId = '" . $candidateId . "' ";

                            } elseif ($currentAssessmentType == 'prac') {
                                $query4 = "UPDATE feedback_request set review_status = '-4' , createdBy ='" . $userId . "' , rejectedBy = '4' ,  ReasonOfRejection ='PracticeInterview',suggestion='For practice interview assessment is not Available.' 
                                 where  interviewSessionId ='" . $interviewSessionId . "'  and interviewId ='" . $interviewId . "' and candidateId = '" . $candidateId . "' ";
                            }

                            $requestReviewUpdateQryResult = mysqli_query($databaseConnection, $query4);
                        } else {
                            /* No need of This peice of Code */
                            $fbr_status = -4;
                            $query4 = "UPDATE feedback_request set review_status = '-4' , createdBy ='" . $userId . "' , rejectedBy ='" . $userId . "'  ,  ReasonOfRejection ='selfRejected',suggestion='Student has not requested expert feedback' where  interviewSessionId ='" . $interviewSessionId . "'  and interviewId ='" . $interviewId . "' and candidateId = '" . $candidateId . "' ";
                            $requestReviewUpdateQryResult = mysqli_query($databaseConnection, $query4);
                        }

                    }
                } else {
                    if ($currentAssessmentType == 'goprac' || $currentAssessmentType == 'stepper') {
                        if ($isAccepted == 'Y') {

                            $fbr_status = 0;
                            $query = "INSERT INTO feedback_request(`candidateId`,`interviewId`,`interviewSessionId`,`requestDate`,`review_status`,`createdBy`) VALUES('$candidateId','$interviewId','$interviewSessionId',NOW(),0,'$userId');";
                        } elseif ($currentAssessmentType == 'prac') {
                            $fbr_status = -4;
                            $query = "INSERT INTO feedback_request(`candidateId`, `interviewId`,`interviewSessionId`, `requestDate`, `review_status`, `createdBy`, `rejectedBy`, `reasonOfRejection`, `suggestion`) VALUES('$candidateId','$interviewId','$interviewSessionId',NOW(),-4,'$userId', '$userId','" . $checkReasonOfRejection . "','" . addslashes($checkSuggestion) . "');";


                        }

                    } else {

                        $checkReasonOfRejection = 'PracticeInterview';
                        $checkSuggestion = 'For practice interview assessment is not Available.';
                        $fbr_status = -4;
                        $query = "INSERT INTO feedback_request(`candidateId`, `interviewId`,`interviewSessionId`, `requestDate`, `review_status`, `createdBy`, `rejectedBy`, `reasonOfRejection`, `suggestion`) VALUES('$candidateId','$interviewId','$interviewSessionId',NOW(),-4,'$userId', '$userId','" . $checkReasonOfRejection . "','" . addslashes($checkSuggestion) . "');";

                    }

                    $requestReviewInsertQryResult = mysqli_query($databaseConnection, $query);
                    $feedback_request_id = mysqli_insert_id($databaseConnection);

                    if ($requestReviewInsertQryResult) {
                        $NewEmployabilityReport = updateNewEmployability($databaseConnection, $interviewSessionId, $interviewId, $candidateId, $checkReasonOfRejection);

                        $date = new DateTime(date("Y-m-d"));
                        $date->modify('+7 day');
                        $fbDeliveryDATE = $date->format('Y-m-d');

                        //if($feedbackData['delegatedEmailId'] == NULL) {
                        $contact['contactEmail'] = $interviewDetails['panelEmail'];
                        $contact['contactName'] = $interviewDetails['panelName'];
                        /*} else {
                            $contactEmail = $feedbackData['delegatedName'];
                            $contactName = $feedbackData['delegatedEmailId'];
                        }*/

                        if ($fbr_status == 0) {
                            array_push($contactDetails, $contact);
                            $assessmentType = mysqli_query($databaseConnection, "SELECT i.assessmenttype FROM interview i INNER JOIN feedback_request fr ON fr.interviewId = i.id WHERE fr.id IN ('" . $feedback_request_id . "' ) ");

                            $assessmentWhere = "";
                            $assessmentJoin = "";

                            if (mysqli_num_rows($assessmentType) > 0) {
                                $assessmentTypeData = mysqli_fetch_all($assessmentType, MYSQLI_ASSOC)[0];

                                $assessmentJoin = " INNER JOIN questions q ON q.id = m.questionId INNER JOIN favourite_subject fs ON fs.id = q.subjectId";
                                if ($assessmentTypeData['assessmenttype'] == 'stepper') {
                                    $assessmentWhere = " AND fs.id IN (178)";
                                }
                            }

                            $fbrQuery = "INSERT INTO feedback_status_question(feedbackRequestId, questionId, review_status) select fr.id as feedbackRequestId, m.questionId, 0 as review_status from feedback_request fr inner join mergedVideos m on m.interviewSessionId = fr.interviewSessionId " . $assessmentJoin . " where fr.id = '" . $feedback_request_id . "' " . $assessmentWhere . " and m.questionId not in ( select questionId from feedback_status_question where feedbackRequestId='" . $feedback_request_id . "' )";
                            $setQuestionStatus = mysqli_query($databaseConnection, $fbrQuery);



                            $setPriorityResult = mysqli_query($databaseConnection, "update feedback_request fr inner join (select fr.id, fr.interviewSessionId, fr.interviewId, fr.candidateId, count(distinct case when q.priorityStatus = '1' then q.id else null end) as totalQuesPriority from feedback_request fr inner join feedback_status_question fsq on fsq.feedbackRequestId = fr.id inner join questions q on q.id = fsq.questionId where fr.review_status in (0,1) and fr.id = '" . $feedback_request_id . "' group by fr.id having (totalQuesPriority > 0 or '" . $userSubscriptionDetails['s_endDifference'] . "' >= 0)) temp on fr.id = temp.id set fr.priority = 1;");
                            /* added by Narayan 2/7/2021 for make question priority high if it is not ready to use plus */
                            $setQuestionPriorityStatus = mysqli_query($databaseConnection, "UPDATE questions set priorityStatus='1' where id IN(select temp.* from (select q.id from feedback_request fr  inner join feedback_status_question fsq on fsq.feedbackRequestId= fr.id inner join questions q on fsq.questionId = q.id  where fr.id = '" . $feedback_request_id . "' and fr.review_status in (0,1) and q.priorityStatus = 0 and  (q.expertAdvice is null or q.youtubeId = '314664775' or q.eligibleStreamId IS  NULL or q.subjectId IS NULL or  q.conceptId IS  NULL or  q.key_skill_id IS NULL or  q.topic_id IS  NULL or  q.isWbRequired IS  NULL or q.questionLevel IS  NULL) and (q.peerResponseVideo is  null or q.mbr_id = '0') having '" . $userSubscriptionDetails['s_endDifference'] . "' >= 0 ) as temp)");
                        } else {
                            if ($checkReasonOfRejection == 'technicalIssue') {
                                $reasonOfRejection = 'Technical Issue';
                            } else if ($checkReasonOfRejection == 'studentIsIndulgedInMalpractice') {
                                $reasonOfRejection = 'Student is Indulged in Malpractice';
                            } else if ($checkReasonOfRejection == 'incompleteInterview') {
                                $reasonOfRejection = 'incomplete interview';
                            } else if ($checkReasonOfRejection == 'incompleteAnswer') {
                                $reasonOfRejection = 'Incomplete Answer';
                            } else if ($checkReasonOfRejection == 'nonSeriousInterview') {
                                $reasonOfRejection = 'Non Serious Interview';
                            } else if ($checkReasonOfRejection == 'assessmentOnHold') {
                                $reasonOfRejection = 'Assessment on Hold';
                            } else if ($checkReasonOfRejection == 'limitedFreeAssessment') {
                                $reasonOfRejection = 'Limited FREE Assessment';
                            } else if ($checkReasonOfRejection == 'fixedNoOfAssessment') {
                                $reasonOfRejection = 'Completed the Max no of Assessments';
                            } else if ($checkReasonOfRejection == 'outOfProductScope') {
                                $reasonOfRejection = 'Out of Product Scope';
                            } else if ($checkReasonOfRejection == 'yourPracticeDurationIsDue') {
                                $reasonOfRejection = 'Your Practice Duration is Due';
                            } else if ($checkReasonOfRejection == 'anslessno') {
                                $reasonOfRejection = 'Answered Less No. of Questions';
                            } else if ($checkReasonOfRejection == 'linkexpire') {
                                $reasonOfRejection = 'Your Interview link is Expired';
                            } else if ($checkReasonOfRejection == 'notEligible') {
                                $reasonOfRejection = 'Your Not Eligible for this Job';
                            } else if ($checkReasonOfRejection == 'duplicateAttempt') {
                                $reasonOfRejection = 'Duplicate Attempt';
                            } else {
                                $reasonOfRejection = 'unauthorized user';
                            }

                            $suggestion = $checkSuggestion;

                            if ($checkReasonOfRejection == 'nonSeriousInterview') {
                                $message = "<p>Dear " . $candidateDetails['candidateName'] . ",</p>

                                             <p>Thanks for practicing interviews on GoPrac.com. Your interview response to the interview named " . $interviewDetails['interviewname'] . " can't be reviewed by the expert. This is because, we feel that you have not taken this interview seriously.</p>
                                             <p><b>Advice :</b> " . $suggestion . ". In case you have any doubt , please call us +91-9731107508.</p>
                                             <p> Thanks & Regards <br/> GoPrac Team.</p>
                                            ";
                                sendEmailToUser($candidateDetails['candidateEmail'], null, 'Feedback Request Rejected', $message);
                            } else if ($checkReasonOfRejection == 'assessmentOnHold') {
                                $message = "<p>Dear " . $candidateDetails['candidateName'] . ",</p>
                                
                                <p>Thanks for attempting interview on GoPrac.com. However, expert feedback on your interview is on hold. </p>
                                <p><b>Advice :</b> " . $suggestion . "</p>
                                <p> Thanks & Regards <br/> GoPrac Team.</p>
                               ";
                                sendEmailToUser($candidateDetails['candidateEmail'], null, 'Feedback Request Rejected', $message);
                            } else if ($checkReasonOfRejection == 'fixedNoOfAssessment') {
                                $message = "<p>Dear " . $candidateDetails['candidateName'] . ",</p>
                                
                                <p>Thanks for practicing interviews on GoPrac.com. However, expert feedback of your interview response to the interview named " . $interviewDetails['interviewname'] . "  is not considered for Assessment because we have already provided you the maximum no of assessments subscribed by you.</p>
                                <p><b>Advice :</b> " . $suggestion . ". In case you have any doubt , please call us +91-9731107508.</p>
                                <p> Thanks & Regards</p>
                                <p>GoPrac Team.</p>
                               ";
                                sendEmailToUser($candidateDetails['candidateEmail'], null, 'Feedback Request Rejected', $message);
                            } else if ($checkReasonOfRejection == 'limitedFreeAssessment') {
                                $message = "<p>Dear " . $candidateDetails['candidateName'] . ",</p>

                                <p>Thanks for practicing interviews on GoPrac.com. However, expert feedback of your interview response to the interview named " . $interviewDetails['interviewname'] . " is on hold because Assessments are limited during FREE trial. </p>
                                <p><b>Advice :</b> " . $suggestion . ". In case you have any doubt , please call us +91-9731107508.</p>
                                <p> Thanks & Regards</p>
                                <p>GoPrac Team.</p>
                               ";
                                // sendEmailToUser($candidateDetails['candidateEmail'], null, 'Feedback Request Rejected', $message);
                            } else if ($checkReasonOfRejection == 'outOfProductScope') {
                                $message = "<p>Dear " . $candidateDetails['candidateName'] . ",</p>

                                <p>Thanks for practicing interviews on GoPrac.com. However, expert feedback of your interview response to the interview named " . $interviewDetails['interviewname'] . "   is not considered for Assessment because the interview given by you is NOT in the scope of your product.</p>
                                <p><b>Advice :</b> " . $suggestion . ". In case you have any doubt , please call us +91-9731107508.</p>
                                <p> Thanks & Regards</p>
                                <p>GoPrac Team.</p>
                               ";
                                sendEmailToUser($candidateDetails['candidateEmail'], null, 'Feedback Request Rejected', $message);
                            } else if ($checkReasonOfRejection == 'yourPracticeDurationIsDue') {
                                $message = "<p>Dear " . $candidateDetails['candidateName'] . ",</p>

                                <p>Thanks for practicing interviews on GoPrac.com. However, expert feedback of your interview response to the interview named " . $interviewDetails['interviewname'] . "    is not considered for Assessment because your Practice Duration is Due.</p>
                                <p><b>Advice :</b> " . $suggestion . ". In case you have any doubt , please call us +91-9731107508.</p>
                                <p> Thanks & Regards</p>
                                <p>GoPrac Team.</p>
                               ";
                                sendEmailToUser($candidateDetails['candidateEmail'], null, 'Feedback Request Rejected', $message);
                            } else if ($checkReasonOfRejection == 'anslessno') {
                                $message = "<p>Dear " . $candidateDetails['candidateName'] . ",</p>

                                <p>Thanks for practicing interviews on GoPrac.com. Your interview response to the interview named" . $interviewDetails['interviewname'] . " cannot be reviewed by the expert.This is because your answered less number of questions.</p>
                                <p><b>Advice :</b> " . $suggestion . ". In case you have any doubt , please call us +91-9731107508.</p>
                                <p> Thanks & Regards</p>
                                <p>GoPrac Team.</p>
                               ";
                                sendEmailToUser($candidateDetails['candidateEmail'], null, 'Feedback Request Rejected', $message);
                            } else if ($checkReasonOfRejection == 'linkexpire') {
                                $message = "<p>Dear " . $candidateDetails['candidateName'] . ",</p>

                                <p>Thanks for practicing interviews on GoPrac.com. Your interview response to the interview named" . $interviewDetails['interviewname'] . " cannot be reviewed by the expert.This is because Your Interview link is Expired.</p>
                                <p><b>Advice :</b> " . $suggestion . ". In case you have any doubt , please call us +91-9731107508.</p>
                                <p> Thanks & Regards</p>
                                <p>GoPrac Team.</p>
                               ";
                                sendEmailToUser($candidateDetails['candidateEmail'], null, 'Feedback Request Rejected', $message);
                            } else if ($checkReasonOfRejection == 'notEligible') {
                                $message = "<p>Dear " . $candidateDetails['candidateName'] . ",</p>

                                <p>Thanks for practicing interviews on GoPrac.com. Your interview response to the interview named" . $interviewDetails['interviewname'] . " cannot be reviewed by the expert.This is because Your Not Eligible for this Job.</p>
                                <p><b>Advice :</b> " . $suggestion . ". In case you have any doubt , please call us +91-9731107508.</p>
                                <p> Thanks & Regards</p>
                                <p>GoPrac Team.</p>
                               ";
                                sendEmailToUser($candidateDetails['candidateEmail'], null, 'Feedback Request Rejected', $message);
                            } else {
                                if ($checkReasonOfRejection != 'PracticeInterview') {
                                    // studentReviewWithFeedbackEmail($candidateDetails, $interviewDetails, $fbDeliveryDATE, $reasonOfRejection, $suggestion, $emailApiHost); //for student

                                }

                            }
                        }
                    }
                }
            } else {
                if ($isAccepted == 'Y') {
                    $fbr_status = -2;

                    if ($currentAssessmentType == 'goprac' || $currentAssessmentType == 'stepper') {

                        $query4 = "UPDATE feedback_request set review_status = '-2' , createdBy ='" . $userId . "' , rejectedBy = NULL ,  ReasonOfRejection =NULL,suggestion=NULL where  interviewSessionId ='" . $interviewSessionId . "'  and interviewId ='" . $interviewId . "' and candidateId = '" . $candidateId . "' ";

                    } elseif ($currentAssessmentType == 'prac') {
                        $query4 = "UPDATE feedback_request set review_status = '-4' , createdBy ='" . $userId . "' , rejectedBy = '4' ,  ReasonOfRejection ='PracticeInterview',suggestion='For practice interview assessment is not available.' 
                         where  interviewSessionId ='" . $interviewSessionId . "'  and interviewId ='" . $interviewId . "' and candidateId = '" . $candidateId . "' ";
                    }

                } else {
                    /* No need of This peice of Code */
                    $fbr_status = -4;
                    $query4 = "UPDATE feedback_request set review_status = '-4' , createdBy ='" . $userId . "' , rejectedBy ='" . $userId . "'  ,  ReasonOfRejection ='selfRejected',suggestion='Student has not requested expert feedback' where  interviewSessionId ='" . $interviewSessionId . "'  and interviewId ='" . $interviewId . "' and candidateId = '" . $candidateId . "' ";
                }
                $requestReviewInsertQryResult1 = mysqli_query($databaseConnection, $query4);
                /* No Need of This Peice of Code */
                if ($requestReviewInsertQryResult1) {
                    $contactEmail = 'info@goprac.com';
                    //studentReviewWithFeedbackEmail($contactEmail, $candidateDetails, $interviewDetails);//for student
                    //expertReviewWithFeedbackEmail($contactEmail, $candidateDetails, $interviewDetails);//for admin
                }
            }
            $to_encode = array(
                'result' => "Success",
                'message' => "Information Saved  Successfully",
                'status' => 1,
                'fbr_status' => $fbr_status
            );
        } else {
            $to_encode = array(
                'result' => "error",
                'errorCode' => "Request failed.",
                'status' => 0
            );
        }
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['rejectFeedbackAuto'])) {
    // This function is used for auto reject interview by checking conditions By Anuj verma 28-11-2021
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    if (isset($json)) {
        $interviewId = $json['interviewId'];
        $candidateId = $json['candidateId'];
        $interviewSessionId = $json['interviewSessionId'];
        $createdBy = "0";
        $createdAt = $json['createdAt'];
        $reasonOfRejection = $json['reasonOfRejection'];
        $to_encode = array();

        $getUser = mysqli_query($databaseConnection, "SELECT u.firstName as name, u.emailId as mail, i.name as interviewName FROM `users` u INNER JOIN `interview` i WHERE u.id = '" . $candidateId . "' AND i.id = '" . $interviewId . "'");
        $userDetails = mysqli_fetch_assoc($getUser);
        $userName = $userDetails['name'];
        $userMail = $userDetails['mail'];
        $interviewName = $userDetails['interviewName'];



        if ($json['reasonOfRejection'] == 'incompleteInterview') {
            $suggestion = "Expert will not be able to provide you proper feedback, if you dont complete the interview. In case you find any question difficult, you can tell that you dont know the answer and it will be great if you tell them asto why you dont know the answer. It is advised to quickly revise the concept before giving interview. To revise the concept, pls view the tutorial video. Link of tutorial video : https://goprac.com/interviewDetails?id=" . $interviewId . "";
            $message = "<p>Dear " . $userName . ",</p>
                                
                        <p>Thanks for practicing interviews on GoPrac.com. However, expert feedback of your interview response to the interview named " . $interviewName . "  is not considered for Assessment because of incomplete interview
                        </p>
                        <p>" . $suggestion . "</p>
                        <p><b>Advice :</b> In case you have any doubt , please call us +91-9731107508.</p>
                        <p> Thanks & Regards</p>
                        <p>GoPrac Team.</p>
                       ";
        } else if ($json['reasonOfRejection'] == 'fixedNoOfAssessment') {
            $suggestion = "Keep practicing the interviews. Based on the product that you have subscribed & Experts advice , we will decide if you need assessment or not.";
            $message = "<p>Dear " . $userName . ",</p>
                                
                        <p>Thanks for practicing interviews on GoPrac.com. However, expert feedback of your interview response to the interview named " . $interviewName . "  is not considered for Assessment because we have already provided you the maximum no of assessments subscribed by you.</p>
                        <p><b>Advice :</b> " . $suggestion . " To get assessment, we advise you to subscribe a new product. Link: https://goprac.com/our-products. In case you have any doubt , please call us +91-9731107508.</p>
                        <p> Thanks & Regards</p>
                        <p>GoPrac Team.</p>
                       ";
        } else if ($json['reasonOfRejection'] == 'limitedFreeAssessment') {
            $suggestion = "We would request you to become our paid user for uninterrupted practice & feedback. Once you become a paid member of GoPrac, you will keep receiving the Assessments.";
            $message = "<p>Dear " . $userName . ",</p>

                        <p>Thanks for practicing interviews on GoPrac.com. However, expert feedback of your interview response to the interview named " . $interviewName . " is on hold because Assessments are limited during FREE trial. </p>
                        <p><b>Advice :</b> " . $suggestion . " To get assessment, we advise you to subscribe a new product. Link: https://goprac.com/our-products. . In case you have any doubt , please call us +91-9731107508.</p>
                        <p> Thanks & Regards</p>
                        <p>GoPrac Team.</p>
                       ";
        }

        $query = "SELECT * FROM `feedback_request` WHERE interviewId = '" . $interviewId . "' AND candidateId = '" . $candidateId . "' AND interviewSessionId = '" . $interviewSessionId . "'";
        $queryResult = mysqli_query($databaseConnection, $query);
        if (mysqli_num_rows($queryResult) > 0) {
            // $rejectUpdateQuery = "UPDATE feedback_request SET `review_status` = '-4', `rejectedBy`= '4', `reasonOfRejection` = '".$reasonOfRejection."' , `suggestion` = '".$suggestion."'  WHERE `interviewSessionId` = " . $interviewSessionId . " AND `candidateId` = " . $candidateId . " AND `interviewId` = " . $interviewId." ";
            // shrikant changed : 5/3/2024
            $rejectUpdateQuery = "UPDATE feedback_request SET `review_status` = '-4', `rejectedBy`= '4', `reasonOfRejection` = '" . $reasonOfRejection . "' WHERE `interviewSessionId` = " . $interviewSessionId . " AND `candidateId` = " . $candidateId . " AND `interviewId` = " . $interviewId . " ";
            $rejectUpdateResult = mysqli_query($databaseConnection, $rejectUpdateQuery);
            if ($rejectUpdateResult) {

                sendEmailToUser($userMail, null, 'Feedback Request Rejected', $message);

                /* this is Added by Narayan to check rejected interview employability */
                if ($reasonOfRejection == 'incompleteInterview') {
                    $NewEmployabilityReport = updateNewEmployability($databaseConnection, $interviewSessionId, $interviewId, $candidateId, $reasonOfRejection);
                }



                $to_encode = array(
                    'result' => "success",
                    'message' => "Information Update  Successfully",
                    'status' => 1,
                    'fbr_status' => '-4',
                    'reason' => $reasonOfRejection
                );
            } else {
                $to_encode = array(
                    'result' => "error",
                    'message' => "error while update",
                    'status' => -1,
                    'query' => $rejectUpdateQuery
                );
            }
        } else {
            $fbr_status = -4;
            //$rejectInsertQuery = "INSERT INTO `feedback_request` (`candidateId`,`interviewId`,`interviewSessionId`,`requestDate`,`review_status`,`createdBy`,`rejectedBy`, `reasonOfRejection`,`suggestion`) VALUES('$candidateId','$interviewId','$interviewSessionId',NOW(),-4,'".$createdBy."','4', '".$reasonOfRejection."' ,'".$suggestion."')";
            //Shrikant changed : 5/3/2024
            $rejectInsertQuery = "INSERT INTO `feedback_request` (`candidateId`,`interviewId`,`interviewSessionId`,`requestDate`,`review_status`,`createdBy`,`rejectedBy`, `reasonOfRejection`) VALUES('$candidateId','$interviewId','$interviewSessionId',NOW(),-4,'" . $createdBy . "','4', '" . $reasonOfRejection . "')";
            $rejectInsertResult = mysqli_query($databaseConnection, $rejectInsertQuery);
            if ($rejectInsertResult) {
                sendEmailToUser($userMail, null, 'Feedback Request Rejected', $message);
                /* this is Added by Narayan to check rejected interview employability */
                if ($reasonOfRejection == 'incompleteInterview') {
                    $NewEmployabilityReport = updateNewEmployability($databaseConnection, $interviewSessionId, $interviewId, $candidateId, $reasonOfRejection);
                }
                $to_encode = array(
                    'result' => "success",
                    'status' => '1',
                    'message' => "Information Insert  Successfully",
                    'fbr_status' => '-4',
                    'reason' => $reasonOfRejection
                );
            } else {
                $to_encode = array(
                    'result' => "error",
                    'message' => "error while insert",
                    'status' => '-1',
                    'query' => $rejectInsertQuery
                );
            }
        }

    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Request failed.",
            'status' => 0
        );
    }

    echo json_encode($to_encode);

} elseif (isset($_GET['updateInterviewPriority'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $feedbackRequestId = $json['feedbackRequestId'];

        $result = mysqli_query($databaseConnection, "UPDATE `feedback_request` SET `priority`= '2' WHERE `id`= '" . $feedbackRequestId . "'");
        /* added by Narayan 2/7/2021 for update priorityStatus in questions Table */
        $updateQuestionPriorityStatus = mysqli_query($databaseConnection, "UPDATE questions set priorityStatus='2' where id IN( SELECT temp.* from (select q.id from  feedback_request fr inner join feedback_status_question fsq on fsq.feedbackRequestId= fr.id inner join questions q on q.id = fsq.questionId where  fr.id = '" . $feedbackRequestId . "' and fr.review_status in (0,1) and  (q.expertAdvice is null or q.youtubeId = '314664775' or q.eligibleStreamId IS  NULL or q.subjectId IS NULL or  q.conceptId IS  NULL or  q.key_skill_id IS NULL or  q.topic_id IS  NULL or  q.isWbRequired IS  NULL or q.questionLevel IS  NULL) and (q.peerResponseVideo is  null or q.mbr_id = '0')) as temp);");

        if ($result) {
            $to_encode = array(
                'result' => "Success",
                'message' => "Information Updated  Successfully",
                'status' => 1
            );
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "in Error while updating information"
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while updating information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['speechAceSyn'])) {
    // This method is added by arun for speechace complete the interview
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $feedbackRequestId = $json['feedbackRequestId'];
        $assessmenttype = $json['assessmenttype'];
        $interviewSessionId = $json['interviewSessionId'];
        $interviewId = $json['interviewId'];
        $candidateId = $json['candidateId'];
        $preInterviewId = $json['preInterviewId'];
        $checkReasonOfRejection = '';
        $followUpPresent = false;

        // $submitPendingAssessments=mysqli_query($databaseConnection,"select distinct(feedbackRequestId),fr.interviewSessionId,fr.candidateId,fr.interviewId,i.assessmenttype from feedback_status_question fsq inner join feedback_request fr on fr.id=fsq.feedbackRequestId inner join interview i on i.id=fr.interviewId where fsq.feedbackRequestId not in(select distinct(feedbackRequestId) from feedback_status_question where review_status in(0,1,9)) and fr.review_status in (0,1)");

        // if(mysqli_num_rows($submitPendingAssessments)>0){

        //     while($mainRow=mysqli_fetch_assoc($submitPendingAssessments)){


        $feedbackStatusQuestionsQuery = mysqli_query($databaseConnection, "select m.questionId,fs.id as subjectId,q.isFollowUp,null as questionTag from feedback_request fr inner join mergedVideos m on m.interviewSessionId = fr.interviewSessionId INNER JOIN questions q ON q.id = m.questionId INNER JOIN favourite_subject fs ON fs.id = q.subjectId where fr.id = '" . $feedbackRequestId . "' and m.questionId not in ( select questionId from expert_review where feedback_request_id='" . $feedbackRequestId . "' and questionId is not null)");

        if (mysqli_num_rows($feedbackStatusQuestionsQuery) > 0) {
            while ($row = mysqli_fetch_assoc($feedbackStatusQuestionsQuery)) {
                $fsqQuestions[] = $row;
            }
        }

        $expertReviewQuestionsQuery = mysqli_query($databaseConnection, "SELECT er.questionId,fs.id as subjectId,q.isFollowUp,er.questionTag from expert_review er inner join questions q on q.id=er.questionid inner join favourite_subject fs on fs.id=q.subjectId where er.feedback_request_id='" . $feedbackRequestId . "'");

        if (mysqli_num_rows($expertReviewQuestionsQuery) > 0) {
            while ($row = mysqli_fetch_assoc($expertReviewQuestionsQuery)) {
                $fsqQuestions[] = $row;
            }
        }

        $assignClusterId = parentChildClusterId($fsqQuestions);
        $questionsWithClusterId = $assignClusterId[0];
        $totalParentQuestions = $assignClusterId[1];
        $followUpPresent = $assignClusterId[2];

        // here we are checking whether every followup questions and parent questions has clusterId 
        if ($followUpPresent == true) {
            foreach ($questionsWithClusterId as $key_a => $val_a) {
                if (array_key_exists("clusterID", $questionsWithClusterId[$key_a])) {
                    $updatingSubjectTagQuery = mysqli_query($databaseConnection, "UPDATE expert_review er set er.clusterId=" . $questionsWithClusterId[$key_a]['clusterID'] . " where er.questionid=" . $questionsWithClusterId[$key_a]['questionId'] . " and er.feedback_request_id = " . $feedbackRequestId . "");
                }
            }


            for ($i = 0; $i < $totalParentQuestions; $i++) {
                $questionsCluster = array();
                $val = $i;
                $QuestionsQuery = mysqli_query($databaseConnection, "SELECT er.questionId,fs.id as subjectId,q.isFollowUp,er.questionTag from expert_review er inner join questions q on q.id=er.questionid inner join favourite_subject fs on fs.id=q.subjectId where er.clusterId=" . $val . " and er.feedback_request_id='" . $feedbackRequestId . "'");

                if (mysqli_num_rows($QuestionsQuery) > 0) {
                    while ($row = mysqli_fetch_assoc($QuestionsQuery)) {
                        $questionsCluster[] = $row;
                    }

                    checkClusterGoodBad($databaseConnection, $questionsCluster, $feedbackRequestId, $techIssueTolerance);
                    unset($questionsCluster);
                }
            }
        }

        // for stepper


        if ($assessmenttype == 'stepper') {

            $checkAverage = mysqli_query($databaseConnection, "SELECT review_status from feedback_status_question fsq inner join questions q on q.id = fsq.questionId inner join favourite_subject fs on fs.id = q.subjectId where fsq.feedbackRequestId = '" . $feedbackRequestId . "' and fs.id=178 group by fsq.review_status");

            if (mysqli_num_rows($checkAverage) == 1) {
                $values = mysqli_fetch_all($checkAverage, MYSQLI_ASSOC);
                if ($values[0]['review_status'] == '2') {

                    $subjectClusterAverage = clusterScore($databaseConnection, $feedbackRequestId, '178');
                    $behaviouralSubScore = $subjectClusterAverage / 2;

                    if ($behaviouralSubScore >= 4) {
                        $fbrQuery = "INSERT INTO feedback_status_question(feedbackRequestId, questionId, review_status) select fr.id as feedbackRequestId, m.questionId, 0 as review_status from feedback_request fr inner join mergedVideos m on m.interviewSessionId = fr.interviewSessionId where fr.id = '" . $feedbackRequestId . "' and m.questionId not in ( select questionId from feedback_status_question where feedbackRequestId='" . $feedbackRequestId . "' )";
                        $setQuestionStatus = mysqli_query($databaseConnection, $fbrQuery);

                    } else {
                        if ($followUpPresent == true) {
                            // do not mark review_status = 3
                            // $query = mysqli_query($databaseConnection, "SELECT fr.interviewId, fr.candidateId, i.preInterviewId, fr.review_status FROM feedback_request AS fr INNER JOIN interview AS i ON fr.interviewId = i.id INNER JOIN interviewSchedule AS isch ON i.preInterviewId = isch.preInterviewId AND i.id = isch.interviewId WHERE fr.candidateId = '" . $candidateId . "' and i.preInterviewId= '" . $preInterviewId . "'");
                            // $queryResult = mysqli_fetch_assoc($query);
                            // if ($queryResult && $queryResult['review_status'] == 2) {
                            //     $getFeedbackStatusReview = mysqli_query($databaseConnection, "UPDATE `feedback_request` SET `review_status` = '3' WHERE id = " . $feedbackRequestId);
                            // } else {
                                $getFeedbackStatusReview = mysqli_query($databaseConnection, "UPDATE `feedback_request` SET `review_status` = '2' WHERE id = " . $feedbackRequestId);
                            // }
                        }

                        $stepperRejectedQuery = mysqli_query($databaseConnection, "INSERT INTO expert_review (interviewId,candidateId,questionId,subjectTag,review_type,feedback_request_id,overallRating) select fr.interviewId,fr.candidateId,m.questionId,'notAssessed','question',fr.id as feedbackRequestId,0 from feedback_request fr inner join mergedVideos m on m.interviewSessionId = fr.interviewSessionId where fr.id = " . $feedbackRequestId . " and m.questionId not in ( select questionId from feedback_status_question where feedbackRequestId=" . $feedbackRequestId . " )");

                        $fbrQuery = "INSERT INTO feedback_status_question(feedbackRequestId, expertId, questionId, review_status) select fr.id as feedbackRequestId, 62 as expertId, m.questionId, 2 as review_status from feedback_request fr inner join mergedVideos m on m.interviewSessionId = fr.interviewSessionId where fr.id = '" . $feedbackRequestId . "' and m.questionId not in ( select questionId from feedback_status_question where feedbackRequestId='" . $feedbackRequestId . "' )";
                        $setQuestionStatus = mysqli_query($databaseConnection, $fbrQuery);

                        $checkReasonOfRejection = 'Behavioural subject needs improvment';

                        $interviewQuery = "SELECT i.id AS interviewId, i.name AS interviewname, i.description AS interviewDescription, " . " p.id AS panelId, p.name AS panelName, p.emailid AS panelEmail, p.phonenumber AS panelPhoneNumber " . " FROM interview AS i, panel AS p " . " WHERE p.id = i.panelId AND i.id = " . $interviewId;
                        $interviewQueryResult = mysqli_query($databaseConnection, $interviewQuery);
                        $interviewDetails = $interviewQueryResult->fetch_assoc();

                        $userQuery = "SELECT CONCAT(firstName, ' ', IFNULL(lastName, '')) AS candidateName, emailId AS candidateEmail, mobileNumber AS candidateMobileNumber FROM users WHERE id = " . $candidateId;
                        $userQueryResult = mysqli_query($databaseConnection, $userQuery);
                        $candidateDetails = $userQueryResult->fetch_assoc();

                        //Shrikant added:23/2/2024
                        $query4 = "SELECT speechAceJobWorked from feedback_request WHERE id='" . $feedbackRequestId . "' ";
                        $query4Result = mysqli_query($databaseConnection, $query4);
                        if ($query4Result) {
                            $row = mysqli_fetch_assoc($query4Result);
                            $speechAceJobWorked = $row['speechAceJobWorked'];
                            if ($speechAceJobWorked == 'R') {
                                $NewFeedbackReport = updateNewFeedbackReport($databaseConnection, $interviewSessionId);
                                $NewFeedbackReport1 = skillWiseScoreInNewFeedbackReport($databaseConnection, $interviewId);

                                $query5 = "update feedback_request set speechAceJobWorked='Y' WHERE id='" . $feedbackRequestId . "' ";
                                $query5Result = mysqli_query($databaseConnection, $query5);

                            }

                        }
                        if ($checkReasonOfRejection == 'Behavioural subject needs improvment') {
                            $message = "<p>Dear " . $candidateDetails['candidateName'] . ",</p>
            
                                                             <p>Thanks for practicing interviews on GoPrac.com. Your interview response to the interview named " . $interviewDetails['interviewname'] . " can't be reviewed by the expert. This is because, we feel that you have not taken this interview seriously.</p>
                                                             <p><b>Advice :</b>. In case you have any doubt , please call us +91-9731107508.</p>
                                                             <p> Thanks & Regards</p>
                                                             <p>GoPrac Team.</p>
                                                            ";
                            sendEmailToUser($candidateDetails['candidateEmail'], null, 'Feedback Request Rejected', $message);

                            $emailSentQuery = mysqli_query($databaseConnection, "UPDATE feedback_request set isEmailSent = 'Y' WHere interviewSessionId = '" . $interviewSessionId . "'");
                        }

                    }
                }
            }

        }



        $getFeedbackStatusQuery = mysqli_query($databaseConnection, "select review_status from feedback_status_question where feedbackRequestId = '" . $feedbackRequestId . "' group by review_status order by review_status");

        if (mysqli_num_rows($getFeedbackStatusQuery) == 1) {
            $values = mysqli_fetch_all($getFeedbackStatusQuery, MYSQLI_ASSOC);
            if ($values[0]['review_status'] == '2') {


                $overallRatingQuery = mysqli_query($databaseConnection, "SELECT round(AVG(overallRating),1) as aptitudeScore  FROM `expert_review` WHERE overallRating !='videoIssue' and overallRating is not null and  `feedback_request_id` = '" . $feedbackRequestId . "'");

                $overallRatingResult = mysqli_fetch_assoc($overallRatingQuery);

                $overAllScore = $overallRatingResult['aptitudeScore'];

                $getFinalScore = mysqli_query($databaseConnection, "select er.*, erod.observationAreaId, erod.observationValueId from expert_review er inner join expert_review_observation_details erod on erod.expertReviewId = er.id where review_type = 'Final Score' and er.feedback_request_id = '" . $feedbackRequestId . "' ");
                $expertReviewParamQry = '';
                if (mysqli_num_rows($getFinalScore) == 1) {
                    $result = mysqli_fetch_assoc($getFinalScore);
                    $expertReviewId = $result['id'];

                    if ($overAllScore >= 7) {
                        $expertReviewParamQry = "UPDATE expert_review_observation_details SET observationValueId = '90' WHERE expertReviewId = '" . $expertReviewId . "' AND observationAreaId = '24'";
                    } elseif ($overAllScore < 7 && $overAllScore > 4) {
                        $expertReviewParamQry = "UPDATE expert_review_observation_details SET observationValueId = '89' WHERE expertReviewId = '" . $expertReviewId . "' AND observationAreaId = '24'";
                    } elseif ($overAllScore <= 4) {
                        $expertReviewParamQry = "UPDATE expert_review_observation_details SET observationValueId = '88' WHERE expertReviewId = '" . $expertReviewId . "' AND observationAreaId = '24'";
                    }
                    $expertReviewParamQryResult = mysqli_query($databaseConnection, $expertReviewParamQry);
                } else {
                    $expertSql = "INSERT INTO `expert_review`(`interviewId`, `candidateId`, `review_type`, feedback_request_id) VALUES('" . $interviewId . "', '" . $candidateId . "', 'Final Score', '" . $feedbackRequestId . "')";
                    $experReviewQuery = mysqli_query($databaseConnection, $expertSql);
                    $expertReviewId = mysqli_insert_id($databaseConnection);

                    if ($overAllScore >= 7) {
                        $expertReviewParamQry = "INSERT INTO expert_review_observation_details(expertReviewId, observationAreaId, observationValueId) VALUES($expertReviewId, '24', '90')";
                    } elseif ($overAllScore < 7 && $overAllScore > 4) {
                        $expertReviewParamQry = "INSERT INTO expert_review_observation_details(expertReviewId, observationAreaId, observationValueId) VALUES($expertReviewId, '24', '89')";
                    } elseif ($overAllScore <= 4) {
                        $expertReviewParamQry = "INSERT INTO expert_review_observation_details(expertReviewId, observationAreaId, observationValueId) VALUES($expertReviewId, '24', '88')";
                    }
                    $expertReviewParamQryResult = mysqli_query($databaseConnection, $expertReviewParamQry);
                    $expertReviewParamDetailId = mysqli_insert_id($databaseConnection);

                    $expertReviewParamQryResult = mysqli_query($databaseConnection, "update `expert_review` set review_param_valueId=" . $expertReviewParamDetailId . " where id=" . $expertReviewId);
                }

                if ($followUpPresent == true) {
                    // dont mark review_status = 3 
                    // $query = mysqli_query($databaseConnection, "SELECT fr.interviewId, fr.candidateId, i.preInterviewId, fr.review_status FROM feedback_request AS fr INNER JOIN interview AS i ON fr.interviewId = i.id INNER JOIN interviewSchedule AS isch ON i.preInterviewId = isch.preInterviewId AND i.id = isch.interviewId WHERE fr.candidateId = '" . $candidateId . "' and i.preInterviewId= '" . $preInterviewId . "'");
                    // $queryResult = mysqli_fetch_assoc($query);
                    // if ($queryResult && $queryResult['review_status'] == 2) {
                    //     $feedback_request_status_query = mysqli_query($databaseConnection, "UPDATE `feedback_request` SET `review_status` = '3' , `priority` = 0  WHERE id=" . $feedbackRequestId);
                    // } else {
                        $feedback_request_status_query = mysqli_query($databaseConnection, "UPDATE `feedback_request` SET `review_status` = '2' , `priority` = 0  WHERE id=" . $feedbackRequestId);
                    // }
                } else {
                    $feedback_request_status_query = 0;
                }


                if ($feedback_request_status_query) {
                    $query3 = "SELECT fr.*,now() as createdAt from feedback_request fr  WHERE id='" . $feedbackRequestId . "' ";

                    $requestReviewSelectQryResult = mysqli_query($databaseConnection, $query3);

                    if (mysqli_num_rows($requestReviewSelectQryResult) >= 1) {

                        $feedbackData = mysqli_fetch_assoc($requestReviewSelectQryResult);
                        if ($feedbackData['review_status'] == 2) {
                            //Shrikant added:23/2/2024
                            $query4 = "SELECT speechAceJobWorked from feedback_request WHERE id='" . $feedbackRequestId . "' ";
                            $query4Result = mysqli_query($databaseConnection, $query4);
                            if ($query4Result) {
                                $row = mysqli_fetch_assoc($query4Result);
                                $speechAceJobWorked = $row['speechAceJobWorked'];
                                if ($speechAceJobWorked == 'R') {
                                    $NewFeedbackReport = updateNewFeedbackReport($databaseConnection, $interviewSessionId);
                                    $NewFeedbackReport1 = skillWiseScoreInNewFeedbackReport($databaseConnection, $interviewId);


                                    $query5 = "update feedback_request set speechAceJobWorked='Y'  WHERE id='" . $feedbackRequestId . "' ";
                                    $query5Result = mysqli_query($databaseConnection, $query5);

                                }

                            }

                            if ($feedbackData['isEmailSent'] == 'N') {

                                $sql2 = "select u.firstName AS candidateDetails,u.emailId AS contactEmail,i.name AS interviewDetails,p.name AS panelDetails,u.mobileNumber from users u, interview i, panel p, ratings r where r.candidateId = u.id and r.interviewId = i.id and i.panelId = p.id and interviewSessionId =" . $interviewSessionId;


                                $sql2Query = mysqli_query($databaseConnection, $sql2);
                                $values = mysqli_fetch_assoc($sql2Query);

                                $companyQuery = "select ac.name from feedback_request fr inner join interview i on i.id=fr.interviewId inner join aspiration_company ac on ac.id=i.companyId where fr.id ='" . $feedbackRequestId . "'";
                                $companyQueryResult = mysqli_query($databaseConnection, $companyQuery);
                                $companyValues = mysqli_fetch_assoc($companyQueryResult);

                                $iReviewlink = $emailApiHost . "/review?i=" . $interviewId . "&c=" . $candidateId . "&s=" . $interviewSessionId;

                                expertCompleteReviewEmail($databaseConnection, $values, $interviewSessionId, $feedbackData['createdAt'], $iReviewlink, $companyValues);

                                $emailSentQuery = mysqli_query($databaseConnection, "UPDATE feedback_request set isEmailSent = 'Y' WHere interviewSessionId = '" . $interviewSessionId . "'");

                            }

                            // TO INSERT THE SKILL % IN SKILLMATCH TABLE
                            $skillScores = getskillMatch($databaseConnection, "fbr.id  in (" . $feedbackRequestId . ") and ");

                            $deleteQuerySkillMatch = mysqli_query($databaseConnection, "DELETE FROM skillMatch where feedbackRequestId=" . $feedbackRequestId . "");
                            if (!empty($skillScores)) {
                                for ($i = 0; $i < count($skillScores); $i++) {
                                    for ($j = 0; $j < count($skillScores[$i]); $j++) {
                                        $insertQuerySkillMatch = "INSERT INTO `skillMatch`(`feedbackRequestId`, `candidateId`, `subjectType`,`skillPercent`) VALUES ('" . $skillScores[$i][$j]['feedbackRequestId'] . "','" . $skillScores[$i][$j]['candidateId'] . "', NULLIF('" . $skillScores[$i][$j]['subjectType'] . "', ''), NULLIF('" . $skillScores[$i][$j]['skillPercent'] . "', ''))";
                                        mysqli_query($databaseConnection, $insertQuerySkillMatch);
                                    }
                                }
                            }
                            // TO INSERT THE SKILL % IN SKILLMATCH TABLE END

                        }
                    }

                }
            }
        }


        if ($checkReasonOfRejection == 'Behavioural subject needs improvment') {
            $updatingSubjectTagQuery = mysqli_query($databaseConnection, "UPDATE expert_review er inner join questions q on q.id=er.questionId inner join favourite_subject fs on fs.id=q.subjectId set er.subjectTag='notAssessed' where fs.id!=178 and er.feedback_request_id = " . $currentFeedbackRequestId . "");
        }

        $to_encode = array(
            'status' => 1,
            'result' => "Success",
            'errorCode' => "Sync successfull"
        );


    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while updating information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['madeUltraHighPriority'])) {
    /*added by Narayan for update all interview and all question which is statify ultra high priority but this method in front end is commented */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];

        $result = mysqli_query($databaseConnection, "UPDATE `feedback_request` SET `priority`= '2' WHERE `id` IN (SELECT temp.id  from (select fr.id from feedback_request fr inner join subscription s  on s.candidateId= fr.candidateId where DATEDIFF(s.endDate, CURDATE()) <=0 and DATEDIFF(s.endDate, CURDATE()) >-15 and s.amount !='0' and fr.priority='1' and fr.review_status in (0,1) group by fr.id ) as temp ) ");
        if ($result) {
            $updateQuestionPriorityStatus = mysqli_query($databaseConnection, "UPDATE questions set priorityStatus='2' where id IN(select temp.id from (select q.id from feedback_request fr inner join feedback_status_question fsq on fsq.feedbackRequestId = fr.id inner join questions q on q.id = fsq.questionId where  fr.review_status in (0,1) and  fr.priority IN (2) and (q.expertAdvice is  null or q.youtubeId = '314664775' or q.peerResponseVideo is NULL or q.eligibleStreamId = '' OR q.eligibleStreamId IS NULL OR q.subjectId = '' OR q.subjectId IS NULL OR q.conceptId = '' OR q.conceptId IS NULL OR q.key_skill_id = '' OR q.key_skill_id IS NULL OR q.topic_id = '' OR q.topic_id IS NULL OR q.isWbRequired = '' OR q.isWbRequired IS NULL OR q.questionLevel = '' OR q.questionLevel IS NULL) group by q.id,fr.id) as temp);");
            $to_encode = array(
                'result' => "Success",
                'message' => "Information Updated  Successfully",
                'status' => 1
            );
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "in Error while updating information"
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while updating information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getParameters'])) {
    /* this API is Updated  by Narayan in Jan 2022 */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {

        $expert_review_id = $json['expert_review_id'];
        $currentQuestionVideo = $json['currentQuestionVideo'];
        $currentInterviewId = $json['currentInterviewId'];
        $feedbackRequestId = $json['feedbackRequestId'];
        $isTextReviewExist = $json['isTextReviewExist'];
        $questionId = $json['questionId'];
        $mainParametersArray = array();
        $qParametersArray = array();
        $qParameterstypesArray = array();
        $finalScoreParametersArray = array();

        $get_key_skills_id = mysqli_query($databaseConnection, "select key_skill_id from questions q inner join interview_questions_transection iqt on iqt.questionId = q.id where iqt.interviewId = '" . $currentInterviewId . "' and iqt.questionId = '" . $questionId . "';");
        if (mysqli_num_rows($get_key_skills_id) > 0) {
            $key_skills_id_result = mysqli_fetch_assoc($get_key_skills_id);
            $key_skill_id = $key_skills_id_result['key_skill_id'];
        } else {
            $key_skill_id = null;
        }

        if ($expert_review_id != 0 && $isTextReviewExist == true) {
            $query = "SELECT pm.id, pm.key_skill,pm.observation_type, CASE WHEN pm.key_skill in (select oa.key_skill from expert_review_observation_details erod inner join observation_values ov on erod.observationValueId = ov.id inner join observation_area oa on ov.observation_id = oa.id inner join expert_review er on erod.expertReviewId = er.id where oa.key_skill != '0' and oa.is_final_parameters = 'N' and oa.id != '25' and er.id = '" . $expert_review_id . "' group by oa.key_skill) THEN pm.mandatory WHEN pm.key_skill in (" . $key_skill_id . ",5) THEN pm.mandatory ELSE '0' END as mandatory, pt.`key_skill` AS key_skills_text, pm.observation_name, pm.description, if(erod2.observationAreaId, 'selected', '') as selected, if(erod2.observationValueId, (select observation_values from observation_values where id = erod2.observationValueId), '') as observationValues,if(erod2.observationValueId, (select skill_ier from observation_values where id = erod2.observationValueId), '') as Skill_Ier, erod2.message, if(pm.mandatory = 1 and FIND_IN_SET(pm.key_skill, '" . $key_skill_id . ",5'), 1, 0) as mandatorySkill FROM key_skill as pt, observation_area AS pm left outer join expert_review_observation_details erod2 on erod2.observationAreaId = pm.id and erod2.expertReviewId = '" . $expert_review_id . "' WHERE pm.is_final_parameters = 'N' and pt.id=pm.key_skill and pm.Status='Yes' and pt.status='Yes' order by pm.key_skill, pt.`key_skill`=pm.observation_name desc,observation_name='Nothing to improve' ASC,observation_name='Needs to improve a lot' ASC,observation_name='Others' ASC";
        } else {
            $query = "SELECT pm.id, pm.key_skill,pm.observation_type, if(pm.mandatory = 1 AND FIND_IN_SET(pm.key_skill, '" . $key_skill_id . ",5'), 1, 0) as mandatory, pt.`key_skill` AS key_skills_text, pm.observation_name, pm.description, '' as selected, '' as observationValues, NULL as message, if(pm.mandatory = 1 AND FIND_IN_SET(pm.key_skill, '" . $key_skill_id . ",5'), 1, 0) as mandatorySkill FROM key_skill as pt, observation_area AS pm WHERE pm.is_final_parameters = 'N' and pt.id=pm.key_skill and pm.Status='Yes' and pt.status='Yes' order by pm.key_skill, pt.`key_skill`=pm.observation_name desc,observation_name='Nothing to improve' ASC,observation_name='Needs to improve a lot' ASC,observation_name='Others' ASC";
        }

        $queryResult = mysqli_query($databaseConnection, $query);
        if ($queryResult) {
            $i = 0;
            while ($row = $queryResult->fetch_assoc()) {
                $query1 = "SELECT pv.id,pv.observation_values,pv.skill_ier, IF(pv.id in (select observationValueId from expert_review_observation_details where  expertReviewId<>0 and expertReviewId=" . $expert_review_id . "), 'selected', '') AS selected,ier.levelDefinition,ier.value as scoringLevel from observation_values as pv left join observation_area oa on oa.id=pv.observation_id left join ier_for_skills ier on ier.key_skill_id=oa.key_skill and ier.score=pv.observation_values WHERE pv.observation_id ='" . $row['id'] . "' and pv.id not in (445,444,309,447)";

                $pvResult = mysqli_query($databaseConnection, $query1);

                $result = mysqli_query($databaseConnection, "select * from expert_review where id=" . $expert_review_id);
                if (mysqli_num_rows($result) > 0) {
                    $expert_result = $result->fetch_assoc();
                    $mainParametersArray['expert_review_suggestion'] = $expert_result['expert_review_suggestion'];
                } else {
                    $mainParametersArray['expert_review_suggestion'] = null;
                }

                $pvArray = array();
                //$row['selected']=0;
                $row['show'] = 0;
                $row['expert_review_suggestion'] = '';
                $row['white_board_text'] = '';
                if ($row['mandatory'])
                    $row['show'] = 1;
                $i++;
                while ($row1 = $pvResult->fetch_assoc()) {
                    if ($row1['selected'] == 'selected') {
                        //$row['selected']=$row1['id'];
                        //$row['mandatory']=1;
                        $row['show'] = 1;
                    }
                    array_push($pvArray, $row1);
                }
                $row['values'] = $pvArray;
                $qParameterstypesArray[$row['key_skill']][] = $row;
                array_push($qParametersArray, $row);
            }
            $mainParametersArray['questionsReviewParametersArray'] = $qParametersArray;
            $mainParametersArray['questionsReviewParameterstypesArray'] = array_values($qParameterstypesArray);
        }

        $finalScoreQuery = "SELECT pm.id, pm.key_skill,pm.observation_name,pm.description FROM observation_area AS pm WHERE pm.is_final_parameters = 'Y'";
        $finalScoreQueryResult = mysqli_query($databaseConnection, $finalScoreQuery);
        if ($finalScoreQueryResult) {
            while ($row = $finalScoreQueryResult->fetch_assoc()) {
                $query1 = "SELECT pv.id,pv.observation_values, IF(pv.id in (select observationValueId from expert_review_observation_details where expertReviewId=" . $json['final_review_id'] . "), 'selected', '') AS selected from observation_values as pv WHERE pv.observation_id ='" . $row['id'] . "'";
                $finalpvResult = mysqli_query($databaseConnection, $query1);

                $result = mysqli_query($databaseConnection, "select * from expert_review where id=" . $json['final_review_id']);
                if (mysqli_num_rows($result) > 0) {
                    $expert_result = $result->fetch_assoc();
                    $mainParametersArray['final_review_suggestion'] = $expert_result['expert_review_suggestion'];
                } else {
                    $mainParametersArray['final_review_suggestion'] = null;
                }

                $row['query'] = $query1;
                $final_array = array();
                $row['selected'] = 0;
                $row['expert_review_suggestion'] = '';
                $row['count'] = mysqli_num_rows($finalpvResult);
                while ($row1 = mysqli_fetch_assoc($finalpvResult)) {
                    if ($row1['selected'] == 'selected') {
                        $row['selected'] = $row1['id'];
                    }
                    array_push($final_array, $row1);
                }
                $row['values'] = $final_array;
                array_push($finalScoreParametersArray, $row);
            }
        }

        $mainParametersArray['finalScoreReviewParametersArray'] = $finalScoreParametersArray;

        if ($expert_review_id != 0 && $isTextReviewExist == true) {
            $overallRatingQuery = mysqli_query($databaseConnection, "select * from expert_review where id ='" . $expert_review_id . "'");
            $overallRatingResult = mysqli_fetch_assoc($overallRatingQuery);
            $overallRating = $overallRatingResult['overallRating'];
        } else {
            $overallRating = NULL;
        }

        if (sizeof($finalScoreParametersArray) == 0 && sizeof($qParametersArray) == 0) {
            // Error Response
            $to_encode = array(
                'result' => "error",
                'errorCode' => "Failed.",
                'status' => 0,
                'questionParamQuery' => $query,
                'finalScoreQuery' => $finalScoreQuery,
                'overallRating' => $overallRating
            );
        } else {
            // Success Response
            $to_encode = array(
                'result' => "Success",
                'message' => "True",
                'status' => 1,
                'data' => $mainParametersArray,
                'overallRating' => $overallRating
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Request failed.",
            'status' => 0,
            'json' => $json
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getFinalParameters'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    $sql = "";
    if (isset($json)) {
        $candidateId = $json['candidateId'];
        $interviewId = $json['interviewId'];
        $interviewSessionId = $json['interviewSessionId'];
        $feedbackRequestId = $json['feedbackRequestId'];
        $finalReview = array();
        $qParametersArray = array();
        $qParameterstypesArray = array();
        $actionableAdviceData = array();

        $sql = "select m.mergeId,m.questionVideoId,q.key_skill_id, q.topic_id, m.youtubeId, m.outputVideoURL, m.uploadStatus from questions q inner join interview_questions_transection iqt on iqt.questionId = q.id INNER JOIN mergedVideos m on q.youtubeId = m.questionVideoId and q.id = m.questionId and iqt.interviewId = m.interviewId and m.interviewId='" . $interviewId . "' and m.candidateId ='" . $candidateId . "' and m.interviewSessionId = '" . $interviewSessionId . "'";

        $query = mysqli_query($databaseConnection, $sql);
        while ($row = mysqli_fetch_assoc($query)) {
            $expert_review_query = mysqli_query($databaseConnection, "select * from expert_review where interviewId=" . $interviewId . " and candidateId =" . $candidateId . " and questionVideoId like '" . $row['questionVideoId'] . "' and feedback_request_id=" . $feedbackRequestId);
            if (mysqli_num_rows($expert_review_query) > 0) {
                $expert_review = mysqli_fetch_assoc($expert_review_query);
                $expert_review_id = $expert_review['id'];
                $expert_review_suggestion = $expert_review['expert_review_suggestion'];

                $get_key_skills_id = mysqli_query($databaseConnection, "select GROUP_CONCAT(key_skill SEPARATOR ',') as key_skill from(select oa.key_skill from expert_review_observation_details erod inner join observation_values ov on erod.observationValueId = ov.id inner join observation_area oa on ov.observation_id = oa.id inner join expert_review er on erod.expertReviewId = er.id where oa.key_skill != '0' and oa.is_final_parameters = 'N' and oa.id != '25' and er.feedback_request_id = '" . $feedbackRequestId . "' and er.questionVideoId = '" . $row['questionVideoId'] . "' group by oa.key_skill) as temp;");
                $key_skills_id_result = mysqli_fetch_assoc($get_key_skills_id);
                if ($key_skills_id_result['key_skill'] == null) {
                    $key_skill_id = $row['key_skill_id'];
                } else {
                    $key_skill_id = $key_skills_id_result['key_skill'];
                }
            } else {
                $expert_review_id = 0;
                $expert_review_suggestion = '';
                $key_skill_id = $row['key_skill_id'];
            }
            $row['expert_review_id'] = $expert_review_id;
            $row['expert_review_suggestion'] = $expert_review_suggestion;

            $explodeKeySkills = explode(",", $key_skill_id);
            for ($i = 0; $i < count($explodeKeySkills); $i++) {
                if ($explodeKeySkills[$i] != 9) { //condition added for analytical skill - id 9
                    $getActionableAdvice = mysqli_query($databaseConnection, "select eraa.*,ks.key_skill as key_skills_name,fs.favourite_subject as topic, " . $row['questionVideoId'] . " as questionVideoId from favourite_subject fs, key_skill ks, expert_review_actionable_advice eraa where eraa.topic_id = fs.id and eraa.key_skill_id = ks.id and eraa.feedbackRequestId = '" . $feedbackRequestId . "' and eraa.key_skill_id='" . $explodeKeySkills[$i] . "' and eraa.topic_id='" . $row['topic_id'] . "'");
                    if (mysqli_num_rows($getActionableAdvice) > 0) {
                        $actionableAdviceResult = mysqli_fetch_assoc($getActionableAdvice);
                        $actionableAdviceData[$explodeKeySkills[$i] . $row['topic_id']] = $actionableAdviceResult;
                    } else {
                        $getActionableAdvice = mysqli_query($databaseConnection, "select " . $explodeKeySkills[$i] . " as key_skill_id, ks.key_skill as key_skills_name, " . $row['topic_id'] . " as topic_id, fs.favourite_subject as topic, " . $row['questionVideoId'] . " as questionVideoId, null as actionableAdvice from favourite_subject fs, key_skill ks where fs.id ='" . $row['topic_id'] . "' and ks.id = '" . $explodeKeySkills[$i] . "'");
                        $actionableAdviceResult = mysqli_fetch_assoc($getActionableAdvice);
                        $actionableAdviceData[$explodeKeySkills[$i] . $row['topic_id']] = $actionableAdviceResult;
                    }
                }
            }

            /*if($expert_review_id == 0){
                $getReviewQuery = "SELECT pm.id, pm.key_skill, 1 as mandatory,pt.`key_skill` AS key_skills_text, pm.observation_name,pm.description FROM observation_area AS pm,key_skill as pt WHERE pm.is_final_parameters = 'N' and pt.id=pm.key_skill and pm.key_skill in (".$key_skill_id.",5)";
            } else{
                $getReviewQuery = "SELECT pm.id, pm.key_skill,0 as mandatory,pt.`key_skill` AS key_skills_text, pm.observation_name,pm.description FROM observation_area AS pm,key_skill as pt WHERE pm.is_final_parameters = 'N' and pt.id=pm.key_skill and pm.key_skill in (".$key_skill_id.",5)";
            }
            $getReviewQueryResult = mysqli_query($databaseConnection, $getReviewQuery);

            if ($getReviewQueryResult) {
                while ($row2 = $getReviewQueryResult->fetch_assoc()) {
                    $query1 = "SELECT pv.id,pv.observation_values, IF(pv.id in (select observationValueId from expert_review_observation_details where  expertReviewId<>0 and expertReviewId=".$expert_review_id."), 'selected', '') AS selected from observation_values as pv WHERE pv.observation_id ='" . $row2['id'] . "' ";
                    $pvResult = mysqli_query($databaseConnection, $query1);
                    $pvArray = array();
                    $row2['selected']=0;
                    $row2['show']=0;
                    $row2['expert_review_suggestion']='';
                    $row2['white_board_text']='';
                    if($row2['mandatory'])
                        $row2['show']=1;
                    while ($row3 = $pvResult->fetch_assoc()) {
                        if($row3['selected']=='selected'){
                            $row2['selected']=$row3['id'];
                            $row2['show']=1;
                            $result=mysqli_query($databaseConnection,"select * from expert_review where id=".$expert_review_id);
                            $expert_result = $result->fetch_assoc();
                            $mainParametersArray['expert_review_suggestion']=$expert_result['expert_review_suggestion'];
                        }
                        array_push($pvArray, $row3);
                    }
                    $row2['values'] = $pvArray;
                    $qParameterstypesArray[$row2['key_skill']][]=$row2;
                   array_push($qParametersArray, $row2);
                }
                $row['questionsReviewParametersArray'] = $qParametersArray;
                $row['questionsReviewParameterstypesArray'] = $qParameterstypesArray;
                unset($qParametersArray);
                unset($qParameterstypesArray);
                $qParametersArray = array();
                $qParameterstypesArray = array();
            }*/
            array_push($finalReview, $row);
        }
        $getDataBySkills = "select ks.id,ks.key_skill,oa.observation_name,ov.observation_values, CASE WHEN ks.key_skill=oa.observation_name THEN er.expert_review_suggestion ELSE null END as expert_review_suggestion, er.id as expert_review_id from expert_review_observation_details erod inner join expert_review er on erod.expertReviewId = er.id inner join observation_values ov on erod.observationValueId = ov.id inner join observation_area oa on ov.observation_id = oa.id inner join key_skill ks on oa.key_skill = ks.id where er.feedback_request_id = '" . $feedbackRequestId . "' and not oa.key_skill in (0,4,5) order by ks.id, ks.key_skill=oa.observation_name desc;";
        $getDataBySkillsQuery = mysqli_query($databaseConnection, $getDataBySkills);
        $getDataBySkillsResult = mysqli_fetch_all($getDataBySkillsQuery, MYSQLI_ASSOC);
        array_push($finalReview, $getDataBySkillsResult);

        /*$actionableAdviceData = array_values($actionableAdviceData);
        array_push($finalReview, $actionableAdviceData);*/
        $to_encode = $finalReview;
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'sql' => $sql,
            'errorCode' => "out Error whire retrieving review information.",
            'sql' => $data
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['saveActionableAdvice'])) { // This is used to save the Actionable Advice
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $feedbackRequestId = $json['feedbackRequestId'];
        $actionableAdviceArr = $json['actionableAdviceArr'];
        $insertedCount = 0;

        for ($i = 0; $i < sizeof($actionableAdviceArr); $i++) {
            $checkIsDataAvailableQuery = "select * from expert_review_actionable_advice where feedbackRequestId='" . $feedbackRequestId . "' and key_skill_id = '" . $actionableAdviceArr[$i]['key_skill_id'] . "' and topic_id = '" . $actionableAdviceArr[$i]['topic_id'] . "'";
            $checkIsDataAvailable = mysqli_query($databaseConnection, $checkIsDataAvailableQuery);
            if (mysqli_num_rows($checkIsDataAvailable) >= 1) {
                $query = "update expert_review_actionable_advice set actionableAdvice = '" . $actionableAdviceArr[$i]['actionableAdvice'] . "' where feedbackRequestId = '" . $feedbackRequestId . "' and key_skill_id = '" . $actionableAdviceArr[$i]['key_skill_id'] . "' and topic_id = '" . $actionableAdviceArr[$i]['topic_id'] . "'";
                $result = mysqli_query($databaseConnection, $query);
                if ($result) {
                    $insertedCount = $insertedCount + 1;
                }
            } else {
                $query = "INSERT INTO `expert_review_actionable_advice`(`feedbackRequestId`, `key_skill_id`, `topic_id`, `actionableAdvice`) VALUES ('" . $feedbackRequestId . "', '" . $actionableAdviceArr[$i]['key_skill_id'] . "', '" . $actionableAdviceArr[$i]['topic_id'] . "', '" . $actionableAdviceArr[$i]['actionableAdvice'] . "')";
                $result = mysqli_query($databaseConnection, $query);
                if ($result) {
                    $insertedCount = $insertedCount + 1;
                }
            }
        }

        if ($insertedCount == sizeof($actionableAdviceArr)) {
            $to_encode = array(
                'result' => "Success",
                'message' => "Information Saved  Successfully",
                'status' => 1
            );
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'submittedReviewAdvice' => sizeof($actionableAdviceArr),
                'savedReviewAdvice' => $insertedCount
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "error submission failed.",
            'status' => -1
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['goPracForCollege'])) { // This is used to save the goPracForCollege details
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $contactPersonName = $json['contact_person_name'];
        $instituteName = $json['institutename'];
        $contactNo = $json['contactno'];
        $contactEmail = $json['contact_email'];
        $enquiry = $json['enquiry'];
        $query = "INSERT INTO goprac_college(`contact_person_name`,`institutename`,`contact_email`,`contactno`,`enquiry`) VALUES('$contactPersonName','$instituteName','$contactEmail','$contactNo','$enquiry')";
        $collgeQuery = mysqli_query($databaseConnection, $query);
        if ($collgeQuery) {
            $Id = mysqli_insert_id($databaseConnection);
            goPracForCollegeEmail($contactPersonName, $instituteName, $contactNo, $contactEmail, $enquiry);
            $to_encode = array(
                'result' => "Success",
                'message' => "Information Saved  Successfully",
                'status' => 1
            );
        } else {
            $to_encode = array(
                'result' => "error",
                'errorCode' => "GoPrac For College Request failed.",
                'status' => 0,
                'query' => $query
            );
        }
    }
    /*Changes By Anil 04-10-2018*/
    echo json_encode($to_encode);
    /*Changes By Anil 04-10-2018*/
}
/*----Start Custom Methods by Anil----*/ // Added by Rp
elseif (isset($_GET['getUserAttendedInterviewes'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $sql1 = "select interviewId,questionVideoId,interviewSessionId from mergedVideos where candidateId='" . $userId . "' group by interviewSessionId";
        $interviewResult = mysqli_query($databaseConnection, $sql1);
        if (mysqli_num_rows($interviewResult) >= 1) {
            $values = array();
            $keys = array();
            while ($row = mysqli_fetch_assoc($interviewResult)) {/*
if(in_array($row['interviewId'], $keys)){
$to_encode = $keys;

}else{*/
                array_push($keys, $row['interviewId']);
                $sql2 = "select * from interview where id='" . $row['interviewId'] . "'";
                $to_encode = array(
                    'result' => $sql2,
                    'response' => "if flase",
                    'status' => 0
                );
                $resultData = mysqli_query($databaseConnection, $sql2);
                if (mysqli_num_rows($resultData)) {
                    $result = mysqli_fetch_array($resultData, MYSQLI_ASSOC);
                    $panelData = mysqli_query($databaseConnection, 'select * from panel where id=' . $result['panelId']);
                    $panel = mysqli_fetch_array($panelData, MYSQLI_ASSOC);
                    $result['panelName'] = $panel['name'];

                    $sql4 = "select * from ratings where candidateId=" . $userId . " and interviewSessionId=" . $row['interviewSessionId'] . " and interviewId=" . $row['interviewId'];
                    $ratingsData = mysqli_query($databaseConnection, $sql4);
                    $ratings = mysqli_fetch_assoc($ratingsData);

                    $sql3 = "select * from feedback_request where candidateId=" . $userId . " and interviewSessionId=" . $row['interviewSessionId'] . " and interviewId=" . $row['interviewId'];
                    $feedbackData = mysqli_query($databaseConnection, $sql3);

                    if (mysqli_num_rows($feedbackData) == 0) {
                        array_push($result, array(
                            'sessionId' => $row['interviewSessionId'],
                            'isSubmit' => $ratings['isSubmit'],
                            'fbr_status' => -1,
                            'sql' => $sql3
                        ));
                    } else {
                        $feedback = mysqli_fetch_assoc($feedbackData);
                        array_push($result, array(
                            'candidateId' => $feedback['candidateId'],
                            'sessionId' => $row['interviewSessionId'],
                            'isSubmit' => $ratings['isSubmit'],
                            'fbr_id' => $feedback['id'],
                            'fbr_status' => $feedback['review_status'],
                            'sql' => $sql3
                        ));
                    }
                    array_push($values, $result);

                    // array_push($result, array(
                    // 'sessionId' => $row['interviewSessionId']));
                    // array_push($values, $result);
                }
                /*$resultData = mysqli_query($databaseConnection,$sql2) ;
                    $result = mysqli_fetch_array ($resultData, MYSQLI_ASSOC);

                    $panelData = mysqli_query($databaseConnection,'select * from panel where id='.$result['panelId']);
                    $panel = mysqli_fetch_array ($panelData, MYSQLI_ASSOC);
                    $result['panelName']=$panel['name'];
                    array_push($values, $result);*/
                // }
            }
            $to_encode = $values;
        } else {
            $to_encode = array(
                'result' => "success",
                'response' => "No Interviews found",
                'status' => 0
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Error while retrieving interviewes.",
            'status' => -1
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['getStudentData'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $data = '';
        if ($userType == 'college') {
            $college_query = mysqli_query($databaseConnection, "select * from `colleges` where user_id =" . $json['userId'] . " order by id limit 1");
            $college = mysqli_fetch_array($college_query, MYSQLI_ASSOC);
            $data = "select distinct u.id, u.firstName as 'firstName', u.lastName as 'lastName' ,u.mobileNumber as 'mobileNumber',u.emailId as 'emailId',u.active as 'active',i.name as 'interviewname', m.interviewSessionId as 'isd', m.interviewId as 'intId', p.name as 'panelname', CONCAT((SELECT COUNT(mi.questionId) FROM mergedVideos mi where mi.interviewSessionId=m.interviewSessionId), '/' , CASE WHEN i.categoryType = 9 THEN  (SELECT COUNT( CASE WHEN iqt.attemptStatus is not NULL THEN iqt.questionId ELSE NULL END) FROM interview_questions_transection iqt inner join questions qs on qs.id = iqt.questionId WHERE iqt.interviewId=m.interviewId and qs.deleted_at is null and iqt.deleted_at is null)  ELSE (SELECT COUNT(iqt.questionId) FROM interview_questions_transection iqt inner join questions qs on qs.id = iqt.questionId WHERE iqt.interviewId=m.interviewId and qs.deleted_at is null and iqt.deleted_at is null) -1 END) as 'QA/QT' from `users` u  LEFT JOIN mergedVideos m ON u.id = m.candidateId inner join `interview` i on  m.interviewId=i.id inner join `panel` p on i.panelId = p.id and u.usertype='student' and u.deleted_at is null and college_id =" . $college['id'] . "
                union
                select distinct u1.id, u1.firstName as 'firstName', u1.lastName as 'lastName' ,u1.mobileNumber as 'mobileNumber',u1.emailId as 'emailId',u1.active as 'active',null as 'interviewname', u1.createdOn as 'isd', null as 'intId', null as 'panelname', null as 'QA/QT' from users u1
                    where u1.id not in (select distinct candidateid from mergedVideos) and college_id =" . $college['id'];
        } elseif ($userType == 'admin') {

            $data = "select distinct u.id, u.firstName as 'firstName', u.lastName as 'lastName' ,u.mobileNumber as 'mobileNumber',u.emailId as 'emailId',u.active as 'active',i.name as 'interviewname', m.interviewSessionId as 'isd', date_format(from_unixtime(floor(m.interviewSessionId/1000)),'%d-%b-%y') as 'intTakenDate', date_format(timestampadd(day,2,from_unixtime(floor(m.interviewSessionId/1000))),'%d-%b-%y') as 'intTakenSLA' , m.interviewId as 'intId', p.name as 'panelname', tab.name as companyName  ,(SELECT COUNT(mi.questionId) FROM mergedVideos mi where mi.interviewSessionId=m.interviewSessionId) as 'QA', CASE WHEN i.categoryType = 9 THEN  (SELECT COUNT( CASE WHEN iqt.attemptStatus is not NULL THEN iqt.questionId ELSE NULL END) FROM interview_questions_transection iqt inner join questions qs on qs.id = iqt.questionId WHERE iqt.interviewId=m.interviewId and qs.deleted_at is null and iqt.deleted_at is null) ELSE (SELECT COUNT(iqt.questionId) FROM interview_questions_transection iqt inner join questions qs on qs.id = iqt.questionId WHERE iqt.interviewId=m.interviewId and qs.deleted_at is null and iqt.deleted_at is null) -1 END  as 'QT', date_format(fr.updatedAt,'%d-%b-%y') as Status_Date, 
                case 
                 when fr.review_status = -2 then date_format(timestampadd(day,2,fr.updatedAt),'%d-%b-%y')
                 when fr.review_status = 0 then date_format(timestampadd(day,7,fr.updatedAt),'%d-%b-%y')
                 when fr.review_status = 1 then ' '
                 when fr.review_status = -3 then date_format(timestampadd(day,2,fr.updatedAt),'%d-%b-%y')
                 when fr.review_status = 2 then ' '
                 else ' '
                END as SLA_Date
                from `users` u  inner JOIN mergedVideos m ON u.id = m.candidateId inner join `interview` i on  m.interviewId=i.id inner join `panel` p on i.panelId = p.id left outer join feedback_request fr on m.interviewSessionId=fr.interviewSessionId left outer join (select distinct c.name,s.emailId as emailId from company c, scodes s where c.id = s.source) tab ON tab.emailId = u.emailId and u.deleted_at is null
                 union
                select distinct u1.id, u1.firstName as 'firstName', u1.lastName as 'lastName' ,u1.mobileNumber as 'mobileNumber',u1.emailId as 'emailId',u1.active as 'active',null as 'interviewname', u1.createdOn as 'isd', null as 'intTakenDate', null as 'intTakenSLA', null as 'intId', null as 'panelname',  tab.name as companyName, null as QA, null as QT, null as Status_Date, null as SLA_Date 
                from users u1 left outer join (select distinct c.name,s.emailId as emailId from company c, scodes s where c.id = s.source) tab ON tab.emailId = u1.emailId where u1.id not in (select distinct candidateid from mergedVideos) and u1.deleted_at is null  
                ORDER BY `isd`  DESC";
        }
        if ($data != '') {
            /* End Anil Code*/
            $query = mysqli_query($databaseConnection, $data);
            if (mysqli_num_rows($query) >= 1) {
                $values = array();
                while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {

                    if ($row['intId'] == null) {
                        $values[] = array(
                            'name' => $row['firstName'] . ' ' . $row['lastName'],
                            'mobile' => $row['companyName'],
                            'status' => ($row['active'] == 'Y') ? 'Active' : 'Not Active',
                            'email' => $row['emailId'] . " " . $row['mobileNumber'],
                            'interviewname' => " ",
                            'panelname' => ' ',
                            'isSubmit' => " ",
                            'fbr_id' => " ",
                            'fbr_status' => " ",
                            'isd' => $row['isd'],
                            'intId' => " ",
                            'url' => " ",
                            'sessionId' => $row['isd'],
                            'isSubmit' => " ",
                            'fbr_status' => " ",
                            'id' => $row['id']
                        );
                    }
                    if ($row['intId'] != null) {
                        $sql4 = "select * from ratings where candidateId=" . $row['id'] . " and interviewSessionId=" . $row['isd'] . " and interviewId=" . $row['intId'];
                        $ratingsData = mysqli_query($databaseConnection, $sql4);
                        $ratings = mysqli_fetch_assoc($ratingsData);

                        $sql3 = "select * from feedback_request where candidateId=" . $row['id'] . " and interviewSessionId=" . $row['isd'] . " and interviewId=" . $row['intId'];
                        $feedbackData = mysqli_query($databaseConnection, $sql3);

                        if (mysqli_num_rows($feedbackData) == 0) {
                            $values[] = array(
                                'name' => $row['firstName'] . ' ' . $row['lastName'],
                                'mobile' => $row['companyName'],
                                'status' => ($row['active'] == 'Y') ? 'Active' : 'Not Active',
                                'email' => $row['emailId'] . " " . $row['mobileNumber'],
                                'interviewname' => $row['interviewname'],
                                'panelname' => ($row['QA'] == $row['QT'] - 1) ? 'Full' : '`' . $row['QA'] . '/' . $row['QT'],
                                'isSubmit' => $ratings['isSubmit'],
                                'fbr_id' => "0",
                                'fbr_status' => "0",
                                'isd' => $row['isd'],
                                'intId' => $row['intId'],
                                'url' => "/review?i=" . $row['intId'] . "&c=" . $row['id'] . "&s=" . $row['isd'],
                                'sessionId' => $row['isd'],
                                'isSubmit' => $ratings['isSubmit'],
                                'fbr_status' => -1,
                                'id' => $row['id']
                            );
                        } else {
                            $feedback = mysqli_fetch_assoc($feedbackData);
                            $values[] = array(
                                'id' => $row['id'],
                                'name' => $row['firstName'] . ' ' . $row['lastName'],
                                'mobile' => $row['companyName'],
                                'status' => ($row['active'] == 'Y') ? 'Active' : 'Not Active',
                                'email' => $row['emailId'] . " " . $row['mobileNumber'],
                                'interviewname' => $row['interviewname'],
                                'panelname' => ($row['QA'] == $row['QT'] - 1) ? 'Full' : '`' . $row['QA'] . '/' . $row['QT'],
                                'isSubmit' => $ratings['isSubmit'],
                                'fbr_id' => $feedback['id'],
                                'fbr_status' => $feedback['review_status'],
                                'isd' => $row['isd'],
                                'intId' => $row['intId'],
                                'sessionId' => $row['isd'],
                                'url' => "/review?i=" . $row['intId'] . "&c=" . $row['id'] . "&s=" . $row['isd'],
                                'isSubmit' => $ratings['isSubmit'],
                                'fbr_id' => $feedback['id'],
                                'fbr_status' => $feedback['review_status']
                            );
                        }
                    }
                }
                $to_encode = $values;
            } else {
                $to_encode = array(
                    'result' => "error",
                    'status' => 0,
                    'errorCode' => "in Error while retrieving Student information."
                );
            }
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "in Error You are not having access this page."
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving Student information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['exportStudents'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $data = '';
        if ($userType == 'college') {
            $college_query = mysqli_query($databaseConnection, "select * from `colleges` where user_id =" . $json['userId'] . " and deleted_at is null order by id limit 1");
            $college = mysqli_fetch_array($college_query, MYSQLI_ASSOC);
            $data = "select distinct u.id, u.firstName as 'firstName', u.lastName as 'lastName' ,u.mobileNumber as 'mobileNumber',u.emailId as 'emailId',u.active as 'active',i.name as 'interviewname', m.interviewSessionId as 'isd', m.interviewId as 'intId', p.name as 'panelname', CONCAT((SELECT COUNT(mi.questionId) FROM mergedVideos mi where mi.interviewSessionId=m.interviewSessionId), '/' , CASE WHEN i.categoryType = 9 THEN  (SELECT COUNT( CASE WHEN iqt.attemptStatus is not NULL THEN iqt.questionId ELSE NULL END) FROM interview_questions_transection iqt inner join questions qs on qs.id = iqt.questionId WHERE iqt.interviewId=m.interviewId and qs.deleted_at is null and iqt.deleted_at is null and iqt.deleted_at is null) ELSE (SELECT COUNT(iqt.questionId) FROM interview_questions_transection iqt inner join questions qs on qs.id = iqt.questionId WHERE iqt.interviewId=m.interviewId and qs.deleted_at is null and iqt.deleted_at is null) -1 END)   as 'QA/QT' from `users` u  LEFT JOIN mergedVideos m ON u.id = m.candidateId inner join `interview` i on  m.interviewId=i.id inner join `panel` p on i.panelId = p.id and u.usertype='student' and u.deleted_at is null and college_id =" . $college['id'] . "
                union
                select distinct u1.id, u1.firstName as 'firstName', u1.lastName as 'lastName' ,u1.mobileNumber as 'mobileNumber',u1.emailId as 'emailId',u1.active as 'active',' ' as 'interviewname', u1.createdOn as 'isd', ' ' as 'intId', ' ' as 'panelname', ' ' as 'QA/QT' from users u1
                    where u1.id not in (select distinct candidateid from mergedVideos) and college_id =" . $college['id'];
        } elseif ($userType == 'admin') {

            $data = "select distinct u.id, u.firstName as 'firstName', u.lastName as 'lastName' ,u.mobileNumber as 'mobileNumber',u.emailId as 'emailId',u.active as 'active',i.name as 'interviewname', m.interviewSessionId as 'isd', date_format(from_unixtime(floor(m.interviewSessionId/1000)),'%d-%b-%y') as 'intTakenDate', date_format(timestampadd(day,2,from_unixtime(floor(m.interviewSessionId/1000))),'%d-%b-%y') as 'intTakenSLA' , m.interviewId as 'intId', p.name as 'panelname', tab.name as companyName  ,(SELECT COUNT(mi.questionId) FROM mergedVideos mi where mi.interviewSessionId=m.interviewSessionId) as 'QA', CASE WHEN i.categoryType = 9 THEN  (SELECT COUNT( CASE WHEN iqt.attemptStatus is not NULL THEN iqt.questionId ELSE NULL END) FROM interview_questions_transection iqt inner join questions qs on qs.id = iqt.questionId WHERE iqt.interviewId=m.interviewId and qs.deleted_at is null and iqt.deleted_at is null) ELSE (SELECT COUNT(iqt.questionId) FROM interview_questions_transection iqt inner join questions qs on qs.id = iqt.questionId WHERE iqt.interviewId=m.interviewId and qs.deleted_at is null and iqt.deleted_at is null) -1 END as 'QT', date_format(fr.updatedAt,'%d-%b-%y') as Status_Date, 
                case 
                 when fr.review_status = -2 then date_format(timestampadd(day,2,fr.updatedAt),'%d-%b-%y')
                 when fr.review_status = 0 then date_format(timestampadd(day,7,fr.updatedAt),'%d-%b-%y')
                 when fr.review_status = 1 then ' '
                 when fr.review_status = -3 then date_format(timestampadd(day,2,fr.updatedAt),'%d-%b-%y')
                 when fr.review_status = 2 then ' '
                 else ' '
                END as SLA_Date
                from `users` u  inner JOIN mergedVideos m ON u.id = m.candidateId inner join `interview` i on  m.interviewId=i.id inner join `panel` p on i.panelId = p.id left outer join feedback_request fr on m.interviewSessionId=fr.interviewSessionId left outer join (select distinct c.name,s.emailId as emailId from company c, scodes s where c.id = s.source) tab ON tab.emailId = u.emailId and u.deleted_at is null
                 union
                select distinct u1.id, u1.firstName as 'firstName', u1.lastName as 'lastName' ,u1.mobileNumber as 'mobileNumber',u1.emailId as 'emailId',u1.active as 'active',null as 'interviewname', u1.createdOn as 'isd', null as 'intTakenDate', null as 'intTakenSLA', null as 'intId', null as 'panelname',  tab.name as companyName, null as QA, null as QT, null as Status_Date, null as SLA_Date 
                from users u1 left outer join (select distinct c.name,s.emailId as emailId from company c, scodes s where c.id = s.source) tab ON tab.emailId = u1.emailId where u1.id not in (select distinct candidateid from mergedVideos) and u1.deleted_at is null  
                ORDER BY `isd`  DESC";
        }
        if ($data != '') {

            $query = mysqli_query($databaseConnection, $data);
            if (mysqli_num_rows($query) >= 1) {
                $values = array();
                while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
                    if ($row['intId'] == null) {
                        $values[] = array(
                            'date' => $row['isd'],
                            'name' => $row['firstName'] . ' ' . $row['lastName'],
                            'mobile' => $row['mobileNumber'],
                            'email' => $row['emailId'],
                            'panelname' => $row['panelname'],
                            'interviewname' => $row['interviewname'],
                            'QA/QT' => ' ',
                            'candidateSource' => ($row['companyName'] == null) ? ' ' : $row['companyName'],
                            'feedback' => ' ',
                            'Status_Date' => ' ',
                            'SLA_Date' => ' '

                            //'status' => ($row ['active']=='Y')?'Active':'Not Active',
                            //'verificationStatus' => ($row ['verificationStatus']=='Y')?'Yes':'No',
                        );
                    }
                    if ($row['intId'] != null) {
                        $sql3 = "select * from feedback_request where candidateId=" . $row['id'] . " and interviewSessionId=" . $row['isd'] . " and interviewId=" . $row['intId'];
                        $feedbackData = mysqli_query($databaseConnection, $sql3);
                        if (mysqli_num_rows($feedbackData) == 0) {
                            $values[] = array(
                                'date' => $row['isd'],
                                'name' => $row['firstName'] . ' ' . $row['lastName'],
                                'mobile' => $row['mobileNumber'],
                                'email' => $row['emailId'],
                                'panelname' => $row['panelname'],
                                'interviewname' => $row['interviewname'],
                                'QA/QT' => ($row['QA'] == $row['QT'] - 1) ? 'Full' : '`' . $row['QA'] . '/' . $row['QT'],
                                'candidateSource' => ($row['companyName'] == null) ? ' ' : $row['companyName'],
                                'feedback' => 'InterviewTaken',
                                'Status_Date' => $row['intTakenDate'],
                                'SLA_Date' => $row['intTakenSLA']

                                //'status' => ($row ['active']=='Y')?'Active':'Not Active',
                                //'verificationStatus' => ($row ['verificationStatus']=='Y')?'Yes':'No',
                            );
                        } else {
                            $feedback = mysqli_fetch_assoc($feedbackData);
                            if ($feedback['review_status'] == 0) {
                                $feedback_status = 'Feedback is Open'; //admin requests expert
                            } else if ($feedback['review_status'] == -2) {
                                $feedback_status = 'Feedback Request Pending';
                            } else if ($feedback['review_status'] == -3) {
                                $feedback_status = 'Pending Admin Review';
                            } else if ($feedback['review_status'] == 2) {
                                $feedback_status = 'Feedback Complete';
                            } else {
                                $feedback_status = ' ';
                            }
                            $values[] = array(
                                'date' => $row['isd'],
                                'name' => $row['firstName'] . ' ' . $row['lastName'],
                                'mobile' => $row['mobileNumber'],
                                'email' => $row['emailId'],
                                'panelname' => $row['panelname'],
                                'interviewname' => $row['interviewname'],
                                'QA/QT' => ($row['QA'] == $row['QT'] - 1) ? 'Full' : '`' . $row['QA'] . '/' . $row['QT'],
                                'candidateSource' => ($row['companyName'] == null) ? ' ' : $row['companyName'],
                                'feedback' => $feedback_status,
                                'Status_Date' => $row['Status_Date'],
                                'SLA_Date' => $row['SLA_Date']

                                //'status' => ($row ['active']=='Y')?'Active':'Not Active',
                                //'verificationStatus' => ($row ['verificationStatus']=='Y')?'Yes':'No',
                            );
                        }
                    }
                }
                $to_encode = $values;
            } else {
                $to_encode = array(
                    'result' => "error",
                    'status' => 0,
                    'errorCode' => "in Error while retrieving Student information."
                );
            }
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "in Error You are not having access this page."
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving Student information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['exportFeedback'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $data = '';
        if ($userType == 'college') {
            $college_query = mysqli_query($databaseConnection, "select * from `colleges` where user_id =" . $json['userId'] . " and deleted_at is null order by id limit 1");
            $college = mysqli_fetch_array($college_query, MYSQLI_ASSOC);
            $data = "select *,users.firstName,interview.name from `ratings` inner join users on ratings.candidateId = users.id INNER JOIN interview ON ratings.interviewId = interview.id and usertype ='student' and deleted_at is null and college_id =" . $college['id'] . "ORDER BY isSubmit DESC";
        } elseif ($userType == 'admin') {
            $data = "select *,users.firstName,interview.name from `ratings` inner join users on ratings.candidateId = users.id INNER JOIN interview ON ratings.interviewId = interview.id order by isSubmit desc";
        }
        if ($data != '') {

            $query = mysqli_query($databaseConnection, $data);
            if (mysqli_num_rows($query) >= 1) {
                $values = array();
                while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
                    if ($row['isSubmit'] == 'Y') {
                        if ($row['complexBtn'] == "1") {
                            $complexity = "Simple";
                        } elseif ($row['complexBtn'] == "2") {
                            $complexity = "Medium";
                        } elseif ($row['complexBtn'] == "3") {
                            $complexity = "Hard";
                        } else {
                            $complexity = " ";
                        }
                        $values[] = array(
                            'interviewSessionId' => $row['interviewSessionId'],
                            'candidateId' => $row['firstName'],
                            'interviewId' => $row['name'],
                            'interviewCompleted' => ($row['isSubmit'] == 'Y') ? 'Yes' : 'No',
                            'feedback' => $row['feedbackReason'],
                            'userInterface' => $row['userInterface'],
                            'videoQuality' => $row['videoQuality'],
                            'overallExperience' => $row['overallExperience'],
                            'complexity' => $complexity,
                            'nextInterview' => $row['nextInterview'],
                            'lowBandwidth' => " ",
                            'notLikeQuestion' => " ",
                            'notRelatedInterview' => " ",
                            'otherWork' => " ",
                            'siteIssue' => " "
                        );
                    } else {
                        $values[] = array(
                            'interviewSessionId' => $row['interviewSessionId'],
                            'candidateId' => $row['firstName'],
                            'interviewId' => $row['name'],
                            'interviewCompleted' => ($row['isSubmit'] == 'Y') ? 'Yes' : 'No',
                            'feedback' => $row['feedbackReason'],
                            'userInterface' => " ",
                            'videoQuality' => " ",
                            'overallExperience' => " ",
                            'complexity' => " ",
                            'nextInterview' => " ",
                            'lowBandwidth' => ($row['bandwidth'] == '1') ? 'Yes' : 'No',
                            'notLikeQuestion' => ($row['expert'] == '1') ? 'Yes' : 'No',
                            'notRelatedInterview' => ($row['relevance'] == '1') ? 'Yes' : 'No',
                            'otherWork' => ($row['otherWork'] == '1') ? 'Yes' : 'No',
                            'siteIssue' => ($row['siteIssue'] == '1') ? 'Yes' : 'No'
                        );
                    }
                }
                $to_encode = $values;
            } else {
                $to_encode = array(
                    'result' => "error",
                    'status' => 0,
                    'errorCode' => "in Error while retrieving Student information."
                );
            }
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "in Error You are not having access this page."
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving Student information"
        );
    }
    echo json_encode($to_encode);
}
elseif (isset($_GET['getUserFilters'])) {
    // node-api
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    $userId = $json['userId'] != '' ? $json['userId'] : -1;

    // roles
    $role_query = mysqli_query($databaseConnection, "SELECT DISTINCT rr.id, rr.name AS role FROM relavant_role rr INNER JOIN role_subject rs ON rr.id = rs.roleId WHERE rr.active = 'Y' order by rr.id;");

    $values['role'] = mysqli_fetch_all($role_query, MYSQLI_ASSOC);


        //  subjects
    $subjects_query = mysqli_query($databaseConnection, "SELECT DISTINCT skill.id, role.id as roleId, skill.favourite_subject AS name, CASE WHEN role.id is null then 'Other' ELSE role.name END as role, skill.active AS active, skill.subjectType
            FROM favourite_subject skill
            LEFT JOIN role_subject map ON map.subjectId = skill.id
            LEFT JOIN relavant_role role ON role.id = map.roleId
            WHERE 1 AND skill.active = 'Y'
            order by skill.id");

    $values['subjects'] = mysqli_fetch_all($subjects_query, MYSQLI_ASSOC);

    // competency  subjects
    $competencySkill_query = mysqli_query($databaseConnection, "SELECT DISTINCT skill.id, role.id as roleId, skill.favourite_subject AS name, CASE WHEN role.id is null then 'Other' ELSE role.name END as role
            FROM favourite_subject skill
            LEFT JOIN role_subject map ON map.subjectId = skill.id
            LEFT JOIN relavant_role role ON role.id = map.roleId
            WHERE skill.subjectType = 'competency' AND skill.active = 'Y'
            order by skill.id");

    $values['competencySkill'] = mysqli_fetch_all($competencySkill_query, MYSQLI_ASSOC);


    echo json_encode($values);
}
// node-api
elseif (isset($_GET['getUserData'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $filter_query = " ";
        $limit = $json['limit'];
        $start = ($json['page'] - 1) * $limit;
        $order_query = "  order by u.createdOn desc";
        $limit_query = $limit == 0 ? "" : " limit " . $start . "," . $limit;

        if ($json['college'] != "")
            $filter_query .= " and pd.college in ('" . implode("', '", array_map("addSlashToString", $json['college'])) . "')";
        if ($json['stream'] != "")
            $filter_query .= " and pd.specialization in ('" . implode("', '", $json['stream']) . "')";
        if ($json['usertype'] != "")
            $filter_query .= " and u.usertype like '" . $json['usertype'] . "'";
        if ($json['yop'] != "")
            $filter_query .= " and pd.year in (" . $json['yop'] . ")";
        if ($json['emailId'] != "")
            $filter_query .= " and u.emailId like '%" . $json['emailId'] . "%'";
        if ($json['candidate_name'] != "")
            $filter_query .= " and u.firstName like '%" . $json['candidate_name'] . "%'";
        if ($json['candidate_mob'] != "")
            $filter_query .= " and u.mobileNumber like '%" . $json['candidate_mob'] . "%'";
        if ($json['candidate_id'] != "")
            $filter_query .= " and u.id in (" . $json['candidate_id'] . ")";
        if ($json['verificationStatus'] != "")
            $filter_query .= " and u.verificationStatus ='" . $json['verificationStatus'] . "'";

        if ($json['emailId'] == "" && $json['candidate_name'] == "" && $json['candidate_mob'] == "" && $json['candidate_id'] == "") {
            if ($json['from_date'] != "" && $json['to_date'] == "")
                $filter_query .= " and u.createdOn >= '" . strtotime($json['from_date']) . "'";

            if ($json['from_date'] == "" && $json['to_date'] != "")
                $filter_query .= " and u.createdOn <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";

            if ($json['from_date'] != "" && $json['to_date'] != "")
                $filter_query .= " and u.createdOn >= '" . strtotime($json['from_date']) . "' and u.createdOn <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";
        }

        if (isset($json['yoe_from']) || isset($json['yoe_to'])) {

            $conditions = [];

            $yoe_from = (isset($json['yoe_from']) && $json['yoe_from'] !== '') ? floatval($json['yoe_from']) : null;
            $yoe_to = (isset($json['yoe_to']) && $json['yoe_to'] !== '') ? floatval($json['yoe_to']) : null;


            // Swap values if yoe_from is greater than yoe_to
            if ($yoe_from !== null && $yoe_to !== null && $yoe_from > $yoe_to) {
                $temp = $yoe_from;
                $yoe_from = $yoe_to;
                $yoe_to = $temp;
            }

            // Create conditions based on available values
            if ($yoe_from !== null && $yoe_to !== null) {
                // Both yoe_from and yoe_to are provided
                $conditions[] = "(pd.workExperience >= $yoe_from AND pd.workExperience <= $yoe_to)";
            } elseif ($yoe_from !== null) {
                // Only yoe_from is provided
                $conditions[] = "(pd.workExperience >= $yoe_from)";
            } elseif ($yoe_to !== null) {
                // Only yoe_to is provided
                $conditions[] = "(pd.workExperience <= $yoe_to)";
            }

            if (!empty($conditions)) {
                $filter_query .= " AND (" . implode(" OR ", $conditions) . ")";
            }
        }


        $data = '';
        if ($userType == 'admin') {
            $query = "SELECT
        CASE 
            WHEN EXISTS (
                SELECT 1 
                FROM candidateInterviewMapping cim
                JOIN interviewSchedule isc ON isc.emailId = cim.emailId
                JOIN candidate_interview_transection cit ON cit.interviewId = isc.interviewId
                WHERE cim.emailId = u.emailId AND cit.completion_status = '1'
            ) THEN 'Completed'
            WHEN EXISTS (
                SELECT 1 
                FROM candidateInterviewMapping cim
                JOIN interviewSchedule isc ON isc.emailId = cim.emailId
                JOIN candidate_interview_transection cit ON cit.interviewId = isc.interviewId
                WHERE cim.emailId = u.emailId AND cit.completion_status = '0'
            ) THEN 'In Progress'
            ELSE 'NA'
        END AS completion_status,
        (SELECT isc.candidateStatus 
            FROM interviewSchedule isc 
            WHERE isc.emailId = u.emailId 
              AND isc.candidateStatus IS NOT NULL 
            ORDER BY isc.id DESC 
            LIMIT 1) AS latestCandidateStatus,
        u.*, pd.college, pd.specialization, pd.year, pd.workExperience, pd.resume,
        (SELECT MIN(cim.id) 
            FROM candidateInterviewMapping cim 
            WHERE cim.candidateId = u.id) AS cimId,
        (SELECT source
            FROM candidateInterviewMapping cim 
            WHERE cim.emailId = u.emailId ORDER BY id DESC LIMIT 1) AS source,
        CASE
            WHEN pay.latest_payment_status = 'PAID' THEN 'Paid'
            WHEN pay.latest_payment_status = 'CHECKOUT' THEN 'Checkout'
            ELSE 'Not Paid'
        END AS payment_status,
        pay.payment_history,
        ms.malpractice_stats
    FROM users u
    LEFT JOIN (
        SELECT p1.*
        FROM professionaldetails p1
        JOIN (
            SELECT candidateId, MAX(id) AS max_id
            FROM professionaldetails
            GROUP BY candidateId
        ) p2
        ON p1.candidateId = p2.candidateId
        AND p1.id = p2.max_id
    ) pd ON pd.candidateId = u.id
    LEFT JOIN (
        SELECT 
            pt.user_id,

            JSON_ARRAYAGG(
                JSON_OBJECT(
                    'status', pt.status,
                    'amount', pt.amount,
                    'updated_at', pt.updated_at
                )
            ) AS payment_history,

            SUBSTRING_INDEX(
                GROUP_CONCAT(pt.status ORDER BY pt.updated_at DESC),
                ',', 1
            ) AS latest_payment_status

        FROM payment_transaction pt
        GROUP BY pt.user_id
    ) pay ON pay.user_id = u.id
    LEFT JOIN (
        SELECT 
            t.candidateId,
            JSON_ARRAYAGG(
                JSON_OBJECT(
                    'malpracticeValue', t.malpracticeValue,
                    'interviewName', t.interviewName,
                    'interviewSessionId', t.interviewSessionId,
                    'count', t.cnt
                )
            ) AS malpractice_stats
        FROM (
            SELECT 
                mv.candidateId,
                mv.malpracticeValue,
                pr.interviewName,
                mv.interviewSessionId,
                COUNT(*) AS cnt
            FROM feedback_request fr
            JOIN mergedVideos mv ON fr.interviewSessionId = mv.interviewSessionId
            JOIN AnswerTranscription at ON mv.mergeId = at.mergeId
            JOIN preInterview pr ON pr.id = fr.preInterviewId
            WHERE at.ansText IS NOT NULL
              AND mv.malpracticeValue IS NOT NULL
            GROUP BY mv.candidateId, mv.malpracticeValue, mv.interviewSessionId, pr.interviewName
        ) t
        GROUP BY t.candidateId
    ) ms ON ms.candidateId = u.id
    WHERE 1";

        }

        $data = $query . $filter_query . $order_query;
        // echo $data;
        // exit();
        if ($data != '') {
            $count_query = mysqli_query($databaseConnection, "SELECT
                COUNT(DISTINCT u.id) AS count_result
                FROM users u
                LEFT JOIN (
                    SELECT p1.*
                    FROM professionaldetails p1
                    JOIN (
                        SELECT candidateId, MAX(id) AS max_id
                        FROM professionaldetails
                        GROUP BY candidateId
                    ) p2
                    ON p1.candidateId = p2.candidateId
                    AND p1.id = p2.max_id
                ) pd ON pd.candidateId = u.id
                WHERE 1
                $filter_query
            ");
            $query = mysqli_query($databaseConnection, $data . $limit_query);
            if (!$query) {
                error_log(mysqli_error($databaseConnection)); // server log
                echo json_encode([
                    'status' => 0,
                    'errorCode' => 'Database query failed'
                ]);
                exit;
            }

            if (mysqli_num_rows($query) >= 1) {
                $main_data = mysqli_fetch_all($query, MYSQLI_ASSOC);
                $count_result = mysqli_fetch_assoc($count_query);

                $colleges = mysqli_query($databaseConnection, "select * from colleges order by collegeName");
                $collegesResult = mysqli_fetch_all($colleges, MYSQLI_ASSOC);

                $Companys = mysqli_query($databaseConnection, "select * from aspiration_company order by name");
                $CompanysResult = mysqli_fetch_all($Companys, MYSQLI_ASSOC);

                $panel = mysqli_query($databaseConnection, "select * from panel where deleted_at is null order by name");
                $panelsResult = mysqli_fetch_all($panel, MYSQLI_ASSOC);

                // while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
                //     $values['data'][]=$row;
                // }

                $to_encode = array(
                    'data' => $main_data,
                    'count' => $count_result['count_result'],
                    'panels' => $panelsResult,
                    'colleges' => $collegesResult,
                    'Companys' => $CompanysResult,
                    'status' => 1,
                );
            } else {
                $to_encode = array(
                    'result' => "error",
                    'status' => 0,
                    'errorCode' => "in Error while retrieving User information.",
                );
            }
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "in Error You are not having access this page."
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving User information"
        );
    }
    echo json_encode($to_encode);
}
elseif (isset($_GET['getLiveReport'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $limit = $json['limit'];
        $start = ($json['page'] - 1) * $limit;
        $limit_query = $limit == 0 ? "" : " limit " . $start . "," . $limit;

        $data = '';

        // $query = "SELECT preInterview.interviewStartDate, preInterview.roleId, scps_transaction.subject, scps_transaction.topics as topic
        //           FROM preInterview JOIN scps_transaction ON preInterview.id = scps_transaction.preInterviewId ORDER BY preInterview.interviewStartDate DESC";

        // $query= "SELECT p.interviewStartDate, f.favourite_subject, s.subject, r.name,
        // s.topics as topic, p.interviewName, concat('https://goprac.com/companyDetailsx?a=null&preId=',p.id) as URL
        //   FROM preInterview p
        //   inner join scps_transaction s on s.preInterviewId = p.id
        //       left outer join favourite_subject f on f.id=s.subject
        //       left outer join relavant_role r on r.id=p.roleId
        //   where 
        //   p.id = s.preInterviewId
        //   group by p.interviewName,favourite_subject	
        //   ORDER BY p.interviewStartDate DESC";

        $query = "SELECT p.interviewStartDate, f.favourite_subject, s.subject, r.name,
        s.topics as topic, p.interviewName, concat('https://goprac.com/job?p=',p.id) as URL
          FROM preInterview p
          inner join scps_transaction s on s.preInterviewId = p.id
              left outer join favourite_subject f on f.id=s.subject
              left outer join relavant_role r on r.id=p.roleId
          where 
          p.id = s.preInterviewId
          group by p.interviewName,favourite_subject	
          ORDER BY p.interviewStartDate DESC";

        $data = $query;
        if ($data != '') {
            $count_query = mysqli_query($databaseConnection, "SELECT count(preInterview.id) as count_result  FROM preInterview JOIN scps_transaction ON preInterview.id = scps_transaction.preInterviewId;");

            $query = mysqli_query($databaseConnection, $data . $limit_query);

            if (mysqli_num_rows($query) >= 1) {
                $main_data = mysqli_fetch_all($query, MYSQLI_ASSOC);
                $subjectIds = array_column($main_data, 'subject');
                $count_result = mysqli_fetch_assoc($count_query);
                $values = array();

                // Fetch all topics outside the loop for efficiency
                $filterAll = "SELECT tt.id AS topicId, tt.name AS topicName, q.subjectId 
                            FROM questions q 
                           INNER JOIN topic tt ON tt.id = q.topic_Id 
                           GROUP BY tt.id";
                $filterAllResult = mysqli_query($databaseConnection, $filterAll);
                $allTopics = mysqli_fetch_all($filterAllResult, MYSQLI_ASSOC);

                foreach ($subjectIds as $subjectId) {
                    $filter1 = "SELECT tt.id AS topicId, tt.name AS topicName, q.subjectId 
                    FROM questions q 
                    INNER JOIN topic tt ON tt.id = q.topic_Id 
                    WHERE q.subjectId = '$subjectId'
                    GROUP BY tt.id
                    ORDER BY q.subjectId";

                    $filter1Result = mysqli_query($databaseConnection, $filter1);
                    $topics = mysqli_fetch_all($filter1Result, MYSQLI_ASSOC);

                    $topicIds = implode(',', array_column($topics, 'topicName'));

                    $values[] = array(
                        'subjectId' => $subjectId,
                        'topics' => $topics,
                        'topicIds' => $topicIds,
                    );
                }

                foreach ($main_data as &$row) {
                    $topicIds = explode(',', $row['topic']);
                    // Find the corresponding topicNames for each topicId
                    $topicNames = array();
                    foreach ($topicIds as $topicId) {
                        foreach ($allTopics as $topic) {
                            if ($topic['topicId'] == $topicId) {
                                $topicNames[] = $topic['topicName'];
                                break;
                            }
                        }
                    }

                    // If 'Add Topic' is explicitly mentioned in $row['topic'], add it to $topicNames
                    if (in_array('0', $topicIds) !== false) {
                        $topicNames[] = 'Add Topic';
                    }

                    $row['topicNames'] = implode(',', $topicNames);
                }
                $to_encode = array(
                    'data' => $main_data,
                    'subjectIds' => $subjectIds,
                    'topics' => $values,
                    'count' => $count_result['count_result'],
                    'limit' => $limit_query,
                    'status' => 1,
                );
            } else {
                $to_encode = array(
                    'result' => "error",
                    'status' => 0,
                    'errorCode' => "in Error while retrieving information.",
                );
            }
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "in Error You are not having access this page."
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['uploadResumeVideoToVimeo'])) {
    if ($_FILES['video-blob']) {
        $currentStreamId = $_POST['currentStreamId'];
        $panelId = $_POST['panelId'];
        $description = 'Resueme Video';
        $client = new Vimeo("be1cd73378131270e832b71009c3aa10cfe8f6e3", "ACJ7SgqpXse9nD0pfgP6+IXOD5XxvVxuTk6Hr9T2a5D8ROhVqkgJ+EWsB6pgXf7U3JoXaR2eN0ysj8jjVBPgbGjSHCnPvMIye97nv1GmeDn+wzH7mrk/4a6Bsfv/nVVy", "59f892688f66084c8288f030ff53038c");

        $file_name = $_FILES['video-blob']['tmp_name'];
        $uri = $client->upload($file_name, array(
            "name" => $currentStreamId,
            "description" => $description
        ));

        $vimeoURL = explode("/", $uri);
        $vimeoId = end($vimeoURL);
        $sql = "UPDATE `panel` SET `resumeVideo`='" . $vimeoId . "'   WHERE `id`='" . $panelId . "'";
        mysqli_query($databaseConnection, $sql);
        $to_encode = array(
            'result' => "Success",
            'message' => "video uploaded",
            'status' => 1,
            'response' => $uri,
            'query' => $sql,
            'resumeVideo' => $vimeoId
        );
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while uploading information"
        );
    }
    echo json_encode($to_encode);
}
// node-api
elseif (isset($_GET['userTypeChange'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $usertype = $json['usertype'];
        // $college_id = $json['college_id'] == 0 ? '' : implode(",", $json['college_id']);
        // $corporate_id = $json['corporate_id'] == 0 ? '' : implode(",", $json['corporate_id']);

        // Handle college_id (array for college users, null for others)
        $college_id = null;
        if (!empty($json['college_id']) && is_array($json['college_id'])) {
            $college_id = ($json['college_id'][0] == '0') ? null : implode(",", $json['college_id']);
        }
        // Handle corporate_id (integer for corporate users, null for others)  
        $corporate_id = null;
        if (!empty($json['corporate_id'])) {
            $corporate_id = ($json['corporate_id'] == 0) ? null : intval($json['corporate_id']);
        }

        $panelId = $json['panelId'] == 0 ? '' : $json['panelId'];
        $recruiter_name = $json['recruiter_name'];

        // $sql = "UPDATE `users` SET `usertype`='" . $usertype . "', `panelId`=NULLIF('" . $panelId . "', ''), `college_id`=NULLIF('" . $college_id . "', ''), `corporate_id`=NULLIF('" . $corporate_id . "', '') WHERE id=" . $userId;

        $sql = "UPDATE `users` SET 
            `usertype` = '$usertype', 
            `panelId` = " . ($panelId == '' ? 'NULL' : "'$panelId'") . ",
            `college_id` = " . ($college_id === null ? 'NULL' : "'$college_id'") . ",
            `corporate_id` = " . ($corporate_id === null ? 'NULL' : $corporate_id) . "
            WHERE id = $userId";

        if (mysqli_query($databaseConnection, $sql)) {
            if ($json['usertype'] == 'expert' && $panelId == '') {
                $userQuery = mysqli_query($databaseConnection, "select u.id, u.emailId, u.firstName, u.mobileNumber, q.qualification, c.collegeName from users u inner join professionaldetails pd on pd.candidateId = u.id left outer join colleges c on c.id = pd.college left outer join qualification q on q.id = pd.qualification WHERE u.id=" . $userId);
                $user = mysqli_fetch_assoc($userQuery);

                $result = mysqli_query($databaseConnection, "select * from panel WHERE emailId='" . $user['emailId'] . "' limit 1");
                if (mysqli_num_rows($result) > 0) {
                    $expertResult = mysqli_fetch_assoc($result);
                    $panelResult = mysqli_query($databaseConnection, "update users SET panelId='" . $expertResult['id'] . "' WHERE id=" . $userId);
                } else {
                    $panelquery = "INSERT INTO `panel` (`name`, `qualification`, `oraganisation`, `emailId`, `phonenumber`, `panelTitle`,`expertStatus`,`publishStatus`) VALUES ('" . $user['firstName'] . "', '" . $user['qualification'] . "', '" . addslashes($user['collegeName']) . "', '" . $user['emailId'] . "', '" . $user['mobileNumber'] . "', '" . $user['firstName'] . "','0','0');";
                    mysqli_query($databaseConnection, $panelquery);
                    $expertId = mysqli_insert_id($databaseConnection);
                    $panelResult = mysqli_query($databaseConnection, "update users SET panelId='" . $expertId . "' WHERE id=" . $userId);

                    $expertRateQuery = "INSERT INTO expert_rate_card (rateCardStartDate, expertId, assessmentRate_Per_Qns, qnsVideoDurationRate_Per_hr, guidanceVideoDurationRate_Per_hr, peerResponseRate_Per_Qns, personalizedVideoDurationRate_Per_hr, candidateVideoWatchDurationRate_Per_hr, imageusedinGVRate_Per_Image, imageusedinQVRate_Per_Image, videousedinGVRate_Per_Video, videousedinQVRate_Per_Video, taggingRate_Per_Qns, createQuesRate_Per_Qns, imageusedinCreateQnsRate_Per_Image, videousedinCreateQnsRate_Per_Video, reviewQuesRate_Per_Qns, qnsVideoRate_Per_Qns, guidanceVideoRate_Per_Qns, internet_Allowance_Per_Month) VALUES 
                    (now(), '" . $expertId . "', '" . $json['rate'] . "', '0', '0', '0', '0', '" . $json['videowatch'] . "', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0');";
                    $expertRateQuery_result = mysqli_query($databaseConnection, $expertRateQuery);

                    $panelsTransectionInsert = "INSERT INTO `panels_transection`(`panelId`) VALUES ('" . $expertId . "')";
                    $panelsTransection_result = mysqli_query($databaseConnection, $panelsTransectionInsert);
                }
                $to_encode = array(
                    'status' => 1,
                    'result' => "success",
                    'msg' => "User change To Panel successfully"
                );
            }
            elseif ($json['usertype'] == 'corporate') {
                $checkQuery = "SELECT COUNT(*) as count FROM recruiterList WHERE corporateId = $userId";
                $checkResult = mysqli_query($databaseConnection, $checkQuery);
                $recordExists = false;
                if ($checkResult) {
                    $row = mysqli_fetch_assoc($checkResult);
                    $recordExists = ($row['count'] > 0);
                }
                if ($recordExists) {
                    $userQuery = "update recruiterList set name='$recruiter_name' WHERE corporateId =$userId";
                } else {
                    $userQuery = "INSERT INTO recruiterList (name, corporateId) VALUES ('$recruiter_name',$userId)";
                }
                // echo  $userQuery;
                $result = mysqli_query($databaseConnection, $userQuery);

                $to_encode = array(
                    'status' => 1,
                    'result' => "success",
                    'msg' => "recuireter_name updated successfully"
                );

            }
            // College handling - ADD THIS AFTER CORPORATE HANDLING
            elseif ($json['usertype'] == 'college') {
                $contactType = isset($json['contact_type']) ? mysqli_real_escape_string($databaseConnection, $json['contact_type']) : '';
                
                // Get user and college information
                $userInfoQuery = mysqli_query($databaseConnection, "
                    SELECT u.id, u.emailId, u.firstName, u.mobileNumber, c.collegeName 
                    FROM users u 
                    LEFT JOIN colleges c ON c.id = " . intval(str_replace(['[', ']', '"'], '', $college_id)) . "
                    WHERE u.id=" . $userId
                );
                
                if ($userInfoQuery && mysqli_num_rows($userInfoQuery) > 0) {
                    $userInfo = mysqli_fetch_assoc($userInfoQuery);
                    $collegeName = $userInfo['collegeName'] ?? 'Unknown College';
                    
                    // Generate unique institute code (same logic as saveInJobMailList)
                    do {
                        $uniqueCode = strval(mt_rand(100000, 999999));
                        $checkStmt = mysqli_prepare($databaseConnection, "SELECT 1 FROM JobMailList WHERE instituteCode = ? LIMIT 1");
                        mysqli_stmt_bind_param($checkStmt, "s", $uniqueCode);
                        mysqli_stmt_execute($checkStmt);
                        mysqli_stmt_store_result($checkStmt);
                        $collision = mysqli_stmt_num_rows($checkStmt) > 0;
                        mysqli_stmt_close($checkStmt);
                    } while ($collision);
                    
                    // Check if record exists in JobMailList
                    $checkJMLQuery = "SELECT COUNT(*) as count FROM JobMailList WHERE emailId = '" . $userInfo['emailId'] . "'";
                    $checkJMLResult = mysqli_query($databaseConnection, $checkJMLQuery);
                    $jmlRecordExists = false;
                    
                    if ($checkJMLResult) {
                        $row = mysqli_fetch_assoc($checkJMLResult);
                        $jmlRecordExists = ($row['count'] > 0);
                    }
                    
                    if ($jmlRecordExists) {
                        // Update existing record
                        $updateJMLQuery = "UPDATE JobMailList SET 
                            contactType = '$contactType',
                            name = '" . mysqli_real_escape_string($databaseConnection, $collegeName) . "',
                            expRange = '0-1',
                            mobileNumber = '" . $userInfo['mobileNumber'] . "',
                            numberOfCandidates = '200+'
                            WHERE emailId = '" . $userInfo['emailId'] . "'";
                        mysqli_query($databaseConnection, $updateJMLQuery);
                    } else {
                        // Insert new record
                        $insertJMLQuery = "INSERT INTO JobMailList 
                            (contactType, name, expRange, mobileNumber, emailId, instituteCode, locationId, numberOfCandidates) 
                            VALUES 
                            ('$contactType', '" . mysqli_real_escape_string($databaseConnection, $collegeName) . "', '0-1', '" . $userInfo['mobileNumber'] . "', '" . $userInfo['emailId'] . "', '$uniqueCode', NULL, '200+')";
                        mysqli_query($databaseConnection, $insertJMLQuery);
                    }
                    
                    $to_encode = array(
                        'status' => 1,
                        'result' => "success",
                        'msg' => "College user updated successfully"
                    );
                } else {
                    $to_encode = array(
                        'status' => 0,
                        'result' => "error",
                        'errorCode' => "Failed to fetch user/college information"
                    );
                }
            } else {
                $to_encode = array(
                    'status' => 1,
                    'result' => "success",
                    'msg' => "User change  successfully"
                );
            }

        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "out Error while chnaging User Type" . $sql
                // 'errorCode' => "MySQL Error: " . mysqli_error($databaseConnection) . " | SQL: " . $sql
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving User information"
        );
    }
    echo json_encode($to_encode);
}
// node-api
elseif (isset($_GET['deleteUser'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $sql = "update users set deleted_at= CASE when deleted_at is null THEN CURRENT_DATE else null end where id=" . $userId;
        if (mysqli_query($databaseConnection, $sql)) {
            $to_encode = array(
                'status' => 1,
                'result' => "success"
            );
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "out Error while retrieving User information" . $sql
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving User information"
        );
    }
    echo json_encode($to_encode);
}
elseif (isset($_GET['getReasonOfRejectionData'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $limit = $json['limit'];
        $start = ($json['page'] - 1) * $limit;
        $limit_query = $limit == 0 ? "" : " limit " . $start . "," . $limit;
        $filter_query = "";
        $rawData = " ";
        if ($json['college'] != "" and sizeof($json['college']) > 0) {
            $filter_query .= " and pd.college in ('" . implode("', '", array_map("addSlashToString", $json['college'])) . "')";
        }
        if ($json['stream'] != "" and sizeof($json['stream']) > 0) {
            $filter_query .= " and pd.specialization in ('" . implode("', '", $json['stream']) . "')";
        }
        if ($json['year'] != "") {
            $filter_query .= " and pd.year in (" . $json['year'] . ")";
        }
        if ($json['name'] != "") {
            $filter_query .= " and u.firstName like '%" . $json['name'] . "%'";
        }
        if ($json['from_date'] != "" && $json['to_date'] == "") {
            $filter_query .= " and fr.interviewSessionId >= '" . strtotime($json['from_date']) . "'";
        }
        if ($json['from_date'] == "" && $json['to_date'] != "") {
            $filter_query .= " and fr.interviewSessionId <= '" . strtotime($json['to_date']) . "'";
        }
        if ($json['from_date'] != "" && $json['to_date'] != "") {
            $filter_query .= " and fr.interviewSessionId >= '" . strtotime($json['from_date']) . "' and fr.interviewSessionId <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";
        }
        if ($json['isTieUpStatus'] != "") {
            if ($userType != 'college') {
                $rawData .= " inner join raw_data rd on rd.email_id = u.emailId ";
                if ($json['isTieUpStatus'] == 'Y') {
                    $filter_query .= " and rd.isPaid = 'Y'";
                } elseif ($json['isTieUpStatus'] == 'F') {
                    $filter_query .= " and rd.isPaid = 'F'";
                } else {
                    $filter_query .= " and rd.isPaid = 'N'";
                }
            }
        }
        if ($json['reasonForRejection'] != "") {
            $filter_query .= " and fr.reasonOfRejection in ('" . implode("','", $json['reasonForRejection']) . "') ";
        }
        if ($userType == 'college') {
            $college_query = mysqli_query($databaseConnection, "select u1.* from users u1 where u1.id =" . $json['userId'] . " ");
            $college_result = mysqli_fetch_array($college_query, MYSQLI_ASSOC);
            $filter_query .= " and pd.college in (" . $college_result['college_id'] . ")";
            $collegeId = $college_result['college_id'];

            $rawData .= " inner join raw_data rd on rd.email_id = u.emailId ";
            if ($json['isTieUpStatus'] == 'Y') {
                $filter_query .= " and rd.isPaid = 'Y'";
            } elseif ($json['isTieUpStatus'] == 'F') {
                $filter_query .= " and rd.isPaid = 'F'";
            } elseif ($json['isTieUpStatus'] == 'N') {
                $filter_query .= " and rd.isPaid = 'N'";
            } else {
                $filter_query .= " and rd.isPaid in('Y','F')";
            }
        }
        if ($userType == 'mentor') {
            $filter_query .= " and pd.assignMentorId in (" . $json['userId'] . ")";
        }
        // interview filter sibin 07 NOV 2022 
        if ($json['interviewname'] != "") {
            $filter_query .= " and i.companyId in (" . implode(",", $json['interviewname']) . ") ";
        }


        $sql = "select fr.candidateId, u.firstName as name, u.mobileNumber, u.emailId, s.stream,pd.year as yearOfPassing, c.collegeName, fr.interviewId, i.name as interviewName, fr.interviewSessionId, CASE WHEN fr.reasonOfRejection is null THEN 'Other Reason' WHEN fr.reasonOfRejection = 'outOfProductScope' THEN 'Out of Product Scope' WHEN fr.reasonOfRejection = 'yourPracticeDurationIsDue' THEN 'Your Practice Duration is Due' WHEN fr.reasonOfRejection = 'selfRejected' THEN 'Self Rejected' WHEN fr.reasonOfRejection = 'assessmentOnHold' THEN 'Assessment on Hold' WHEN fr.reasonOfRejection = 'PracticeInterview' THEN 'Practice Interview' WHEN fr.reasonOfRejection ='fixedNoOfAssessment' THEN 'Completed the Max no of Assessments'  WHEN fr.reasonOfRejection ='limitedFreeAssessment' THEN 'Limited FREE Assessment'    WHEN fr.reasonOfRejection = 'incompleteInterview' THEN 'Incomplete Interview' WHEN fr.reasonOfRejection = 'incompleteAnswer' THEN 'Incomplete Answer' WHEN fr.reasonOfRejection = 'Testing' THEN 'Testing' WHEN fr.reasonOfRejection = 'nonSeriousInterview' THEN 'Non Serious Interview' WHEN fr.reasonOfRejection = 'technicalIssue' THEN 'Technical Issue' WHEN fr.reasonOfRejection = 'unauthorizedUser' THEN 'Unauthorized User' WHEN fr.reasonOfRejection = 'studentIsIndulgedInMalpractice' THEN 'Student is Indulged in Malpractice' WHEN fr.reasonOfRejection = 'duplicateAttempt' THEN 'Duplicate Attempt' WHEN fr.reasonOfRejection = 'anslessno' THEN 'Answered Less No. of Questions'  WHEN fr.reasonOfRejection = 'linkexpire' THEN 'Your Interview Link is Expired' WHEN fr.reasonOfRejection = 'notEligible' THEN 'Your Not Eligible for this Job' ELSE fr.reasonOfRejection END as reasonOfRejection, fr.suggestion, fr.review_status from feedback_request fr inner join users u on u.id = fr.candidateId inner join professionaldetails pd on pd.candidateId = u.id inner join stream s on s.id = pd.specialization left outer join colleges c on c.id = pd.college inner join interview i on i.id = fr.interviewId " . $rawData . " where fr.review_status = '-4' " . $filter_query . " order by fr.interviewSessionId desc";
        $query = mysqli_query($databaseConnection, $sql . $limit_query);
        if (mysqli_num_rows($query) > 0) {
            $count_query = mysqli_query($databaseConnection, $sql);
            $result['data'] = mysqli_fetch_all($query, MYSQLI_ASSOC);
            $result['count'] = mysqli_num_rows($count_query);
            $to_encode = $result;
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "success",
                'errorCode' => "no data avaialble"
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while retrieving information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getStudentControlListData'])) {
    /* added by Narayan 06-08-2021 for getting table data on student control page */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $result = array();
        $result1 = array();
        $limit = $json['limit'];
        $start = ($json['page'] - 1) * $limit;
        $limit_query = $limit == 0 ? "" : " limit " . $start . "," . $limit;
        $filter_query = "  ";
        $data = '';
        $having_query1 = " having 1 ";
        $group_query = ' GROUP BY u.id';
        $order_query = " order by u.createdOn desc ";
        $noofInterview = $json['noOfInterview'];
        $noofFeedback = $json['noOfFeedback'];
        $rawData = '';


        if ($noofFeedback != "") {
            if ($noofFeedback == '3+') {
                $having_query1 .= " and feedbackDelivered > 3 ";
            } elseif ($noofFeedback == '0+') {
                $having_query1 .= " and feedbackDelivered > 0 ";
            } else {
                $having_query1 .= " and feedbackDelivered= '" . $noofFeedback . "' ";
            }
        }
        if ($json['webinar'] != '') {
            if ($json['webinar'] == '0') {
                $filter_query .= " and wrd.attend = 'Y' ";
            } else {
                $filter_query .= " and (wrd.attend is NULL  OR wrd.attend ='N') ";
            }
        }
        if ($noofInterview != "") {
            if ($noofInterview == '3+') {
                $having_query1 .= " and interviewTaken > 3 ";
            } elseif ($noofInterview == '0+') {
                $having_query1 .= " and interviewTaken >0 ";
            } else {
                $having_query1 .= " and interviewTaken = '" . $noofInterview . "' ";
            }
        }
        if ($json['stream'] != "" and sizeof($json['stream']) > 0) {
            $filter_query .= " and pd.specialization in ('" . implode("', '", $json['stream']) . "')";
        }

        if ($json['year'] != "") {
            $filter_query .= " and pd.year in (" . $json['year'] . ")";
        }
        if ($json['name'] != "") {
            $filter_query .= " and u.firstName like '%" . $json['name'] . "%'";
        }
        if ($json['createdOn'] != "" && $json['to_date'] == "")
            $filter_query .= " and u.createdOn >= '" . strtotime($json['createdOn']) . "'";
        if ($json['createdOn'] == "" && $json['to_date'] != "")
            $filter_query .= " and u.createdOn <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";
        if ($json['createdOn'] != "" && $json['to_date'] != "")
            $filter_query .= " and u.createdOn >= '" . strtotime($json['createdOn']) . "' and u.createdOn <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";

        if ($json['startSubscription'] !== "") {
            $having_query1 .= " and startDate >= '" . $json['startSubscription'] . "'";
        }

        if ($json['endSubscription'] !== "") {
            $having_query1 .= " and endDate <= '" . $json['endSubscription'] . "'";
        }
        if ($json['college'] != "" and sizeof($json['college']) > 0) {
            $filter_query .= " and pd.college in ('" . implode("', '", array_map("addSlashToString", $json['college'])) . "')";
            //$filter_query.=" and pd.college='".$json['college']."'";
        }
        if ($json['paymentStatus'] != "") {
            if ($json['paymentStatus'] == '0') {
                $having_query1 .= " and DATEDIFF(endDate,CURDATE()) < 0 ";
            } else if ($json['paymentStatus'] == '1') {
                $having_query1 .= " and DATEDIFF(endDate,CURDATE()) >= 0  and amount ='0' ";
            } else {
                $having_query1 .= " and DATEDIFF(endDate,CURDATE()) >= 0 and amount !='0' ";
            }
        }
        if ($json['isCollegePaid'] != "") {
            $rawData .= " inner join raw_data rd on rd.email_id = u.emailId ";
            if ($json['isCollegePaid'] == 'Y') {
                $filter_query .= " and rd.isPaid = 'Y'";
            } else {
                $filter_query .= " and rd.isPaid = 'N'";
            }
        }
        if ($json['time_contact'] != "") {
            $filter_query .= " and pd.timetocontact in ( '" . implode("','", $json['time_contact']) . "')";
        }

        if ($json['connecttomentor'] != "") {
            $filter_query .= "and pd.connecttomentor in (" . implode(",", $json['connecttomentor']) . ")";
        }
        $condition = $filter_query . $group_query . $having_query1 . $order_query;
        $data = getSubsciptionDetailsForAllStudent(
            $databaseConnection,
            $condition,
            $limit_query,
            $rawData
        );
        if ($data) {
            $to_encode = $data;
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "success",
                'errorCode' => "no data avaialble"
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while retrieving information",

        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['revertAssessmentFromOpen'])) {
    /* this method is added by devanand for reveting review status  assessment  is open  to feedback open  6-nov -2021*/
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $fbr_id = $json['fbr_id'];
        $expert_ob_details = mysqli_query($databaseConnection, "DELETE FROM expert_review_observation_details WHERE expertReviewId in (select id from expert_review where feedback_request_id ='" . $fbr_id . "')");
        $expert_review = mysqli_query($databaseConnection, "DELETE from expert_review where questionTag !='skipped' and feedback_request_id ='" . $fbr_id . "'");
        $expert_review2 = mysqli_query($databaseConnection, "DELETE from expert_review where questionTag is null and feedback_request_id ='" . $fbr_id . "'");
        $expert_reviewClusterId = mysqli_query($databaseConnection, "UPDATE expert_review set clusterId=null,subjectTag=null where feedback_request_id ='" . $fbr_id . "'");
        $feedback_status_question = mysqli_query($databaseConnection, "DELETE FROM feedback_status_question WHERE feedbackRequestId ='" . $fbr_id . "'");
        $feedback_request = mysqli_query($databaseConnection, "update feedback_request set review_status = '-2',reasonOfRejection=NULL,suggestion=NULL,rejectedBy = NULL,isEmailSent = 'N' WHERE id = '" . $fbr_id . "'");
        if ($feedback_request && $feedback_status_question) {
            $to_encode = array(
                'result' => 'sucess',
                'status' => 1,
                'fbr_status' => -2
            );

        } else {
            $to_encode = array(
                'result' => 'error',
                'status' => 0
            );

        }

    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Query Not executed",
            'status' => -1
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['OpeningStepperquestions'])) {
    /* this method is added by Arun for opening the stepper non feedback provided questions on 22 Nov 2022 */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $fbr_id = $json['fbr_id'];
        $opening_nullexpertId = mysqli_query($databaseConnection, "update feedback_status_question set review_status=0 where feedbackRequestId='" . $fbr_id . "' and expertId is null");

        $turning_otherques_status = mysqli_query($databaseConnection, "update feedback_status_question set review_status=10 where feedbackRequestId='" . $fbr_id . "' and expertId is not null and expertId!=62");

        $feedback_request = mysqli_query($databaseConnection, "UPDATE feedback_request fr SET fr.review_status = '1',fr.reasonOfRejection=NULL,fr.suggestion=NULL,fr.rejectedBy = NULL,fr.isEmailSent = 'N' WHERE id = '" . $fbr_id . "'");

        if ($feedback_request && $opening_nullexpertId && $turning_otherques_status) {
            $to_encode = array(
                'result' => 'sucess',
                'status' => 1,
                'fbr_status' => -2
            );

        } else {
            $to_encode = array(
                'result' => 'error',
                'status' => 0
            );

        }

    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Query Not executed",
            'status' => -1
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getMenteeListData'])) {
    /* this method is used in student control page for getting in individual subscription or other details Data */

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $result = array();
        $data = '';
        $data = "select u.id,u.createdOn as signUpDate,u.isMentee, u.firstName as name,sb.amount,sb.startDate,DATEDIFF(sb.endDate,CURDATE()) as s_endDifference,sb.freeTrialAllowed,sb.mockInterviewAllowed,sb.communicationInterviewAllowed,sb.behaviouralInterviewAllowed,sb.problemsolvingInterviewAllowed,sb.codingInterviewAllowed,sb.freeTrialAssesmentAllowed,sb.mockAssesmentAllowed,sb.communicationAssesmentAllowed,sb.behaviouralAssesmentAllowed,sb.problemsolvingAssesmentAllowed,sb.codingAssesmentAllowed,sb.endDate,u.emailId, u.mobileNumber, st.stream as specialization, pd.year,pd.qualification, pd.college as cl_id,pd.languages, pd.communicationSkillRate, pd.cgpa, pd.fav_subjects, pd.fav_programming_skill,pd.fav_domain,pd.asp_companies, cl.collegeName as college, pd.specialization as str_id, SUM(CASE WHEN fr.review_status = 2 THEN 1 ELSE 0 END) as numOfFeedbackDelivered, SUM(CASE WHEN fr.review_status = 1 OR fr.review_status = 0 OR fr.review_status = -2 OR fr.review_status = -3 THEN 1 ELSE 0 END) as numOfFeedbackPending from users u left outer join professionaldetails pd on u.id = pd.candidateId left outer join stream st on pd.specialization=st.id left outer join colleges cl on cl.id=pd.college left outer join feedback_request fr on fr.candidateId = u.id  left outer join subscription sb on u.id = sb.candidateId where u.deleted_at is NULL and u.usertype='student' and u.id='" . $json['Id'] . "' ";
        // $data =$sql.$filter_query.$orderByQry; 
        $queryResult = mysqli_query($databaseConnection, $data);
        $query = mysqli_query($databaseConnection, $data);

        if (mysqli_num_rows($query) > 0) {
            $row = mysqli_fetch_all($queryResult, MYSQLI_ASSOC);
            $total_data['data'] = $row;
            $to_encode = $total_data;
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "success",
                'errorCode' => "no data avaialble"
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while retrieving information",

        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['UpdateMenteeData'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['candidateId'];
        $amount = $json['amount'];
        $date = date('Y-m-d');
        $endDate = $json['endSubscription'];
        $startDate = $json['startSubscription'];
        $diff = (strtotime($endDate) - strtotime($startDate)) / 86400;
        $duration = strval($diff) . ' days';
        if ($json['productId'] != null) {
            $productId = implode(',', $json['productId']);
        } else {
            $productId = $json['productId'];
        }
        $mockInterview = $json['mockInterview'];
        $communicationInterview = $json['communicationInterview'];
        $behaviouralInterview = $json['behaviouralInterview'];
        $problemsolvingInterview = $json['problemsolvingInterview'];
        $codingInterview = $json['codingInterview'];
        $freeTrialInterview = $json['freeTrialInterview'];

        /* change in update query startDate and product allowed added in subscription by Narayan 20-07-2021 */
        $updateSubQuery = "Update subscription SET amount = '" . $amount . "', duration = '" . $duration . "', endDate= '" . $endDate . "', startDate ='" . $startDate . "', productId='" . $productId . "',`freeTrialAllowed`='" . $freeTrialInterview . "',`mockInterviewAllowed`='" . $mockInterview . "',`communicationInterviewAllowed`='" . $communicationInterview . "',`behaviouralInterviewAllowed`='" . $behaviouralInterview . "',`problemsolvingInterviewAllowed`='" . $problemsolvingInterview . "',`codingInterviewAllowed`='" . $codingInterview . "' WHERE candidateId = '" . $candidateId . "'";
        $updateSubResult = mysqli_query($databaseConnection, $updateSubQuery);
        if ($updateSubResult) {
            $to_encode = array(
                'status' => 1,
                'result' => "success",
                'message' => "Data updated successfully"
            );
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'message' => 'Error while updating subscription data'
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while retrieving information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['exportStudentControlListData'])) {
    /* added by Narayan 07-08-2021 for getting exported  data on student control page */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $filter_query = "  ";
        $data = '';
        $having_query1 = " having 1 ";
        $group_query = ' GROUP BY u.id';
        $order_query = " order by u.createdOn desc ";
        $noofInterview = $json['noOfInterview'];
        $noofFeedback = $json['noOfFeedback'];
        $rawData = '';


        if ($noofFeedback != "") {
            if ($noofFeedback == '3+') {
                $having_query1 .= " and feedbackDelivered > 3 ";
            } elseif ($noofFeedback == '0+') {
                $having_query1 .= " and feedbackDelivered > 0 ";
            } else {
                $having_query1 .= " and feedbackDelivered= '" . $noofFeedback . "' ";
            }
        }
        if ($noofInterview != "") {
            if ($noofInterview == '3+') {
                $having_query1 .= " and interviewTaken > 3 ";
            } elseif ($noofInterview == '0+') {
                $having_query1 .= " and interviewTaken >0 ";
            } else {
                $having_query1 .= " and interviewTaken = '" . $noofInterview . "' ";
            }
        }
        if ($json['stream'] != "" and sizeof($json['stream']) > 0) {
            $filter_query .= " and pd.specialization in ('" . implode("', '", $json['stream']) . "')";
        }

        if ($json['year'] != "") {
            $filter_query .= " and pd.year in (" . $json['year'] . ")";
        }
        if ($json['name'] != "") {
            $filter_query .= " and u.firstName like '%" . $json['name'] . "%'";
        }
        if ($json['createdOn'] != "" && $json['to_date'] == "")
            $filter_query .= " and u.createdOn >= '" . strtotime($json['createdOn']) . "'";
        if ($json['createdOn'] == "" && $json['to_date'] != "")
            $filter_query .= " and u.createdOn <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";
        if ($json['createdOn'] != "" && $json['to_date'] != "")
            $filter_query .= " and u.createdOn >= '" . strtotime($json['createdOn']) . "' and u.createdOn <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";

        if ($json['startSubscription'] !== "") {
            $having_query1 .= " and startDate >= '" . $json['startSubscription'] . "'";
        }

        if ($json['endSubscription'] !== "") {
            $having_query1 .= " and endDate <= '" . $json['endSubscription'] . "'";
        }
        if ($json['college'] != "" and sizeof($json['college']) > 0) {
            $filter_query .= " and pd.college in ('" . implode("', '", array_map("addSlashToString", $json['college'])) . "')";
            //$filter_query.=" and pd.college='".$json['college']."'";
        }
        if ($json['paymentStatus'] != "") {
            if ($json['paymentStatus'] == '0') {
                $having_query1 .= " and DATEDIFF(endDate,CURDATE()) < 0 ";
            } else if ($json['paymentStatus'] == '1') {
                $having_query1 .= " and DATEDIFF(endDate,CURDATE()) >= 0  and amount ='0' ";
            } else {
                $having_query1 .= " and DATEDIFF(endDate,CURDATE()) >= 0 and amount !='0' ";
            }
        }
        if ($json['webinar'] != '') {
            if ($json['webinar'] == '0') {
                $filter_query .= " and wrd.attend = 'Y' ";
            } else {
                $filter_query .= " and (wrd.attend is NULL  OR wrd.attend ='N') ";
            }
        }

        if ($json['isCollegePaid'] != "") {
            $rawData .= " inner join raw_data rd on rd.email_id = u.emailId ";
            if ($json['isCollegePaid'] == 'Y') {
                $filter_query .= " and rd.isPaid = 'Y'";
            } else {
                $filter_query .= " and rd.isPaid = 'N'";
            }
        }

        $condition = $filter_query . $group_query . $having_query1 . $order_query;
        $data = exportSubsciptionDetailsForAllStudent($databaseConnection, $condition, $rawData);
        if ($data) {
            $to_encode = $data;
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "success",
                'errorCode' => "no data avaialble"
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while retrieving information",

        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getExportMenteeListData'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $result = array();
        $limit = $json['limit'];
        $start = ($json['page'] - 1) * $limit;
        $limit_query = $limit == 0 ? "" : " limit " . $start . "," . $limit;
        $filter_query = "";
        $data = '';
        $having_query1 = " having 1 ";
        $having_query2 = " having 1 ";
        $group_query = ' GROUP BY u.id';
        $order_query = " order by u.createdOn desc ";
        if ($json['stream'] != "" and sizeof($json['stream']) > 0) {
            $filter_query .= " and pd.specialization in ('" . $json['stream'] . "')";
        }

        if ($json['year'] != "") {
            $filter_query .= " and pd.year ='" . $json['year'] . "'";
        }
        if ($json['name'] != "") {
            $filter_query .= " and u.firstName like '%" . $json['name'] . "%'";
        }
        if ($json['interview'] != "") {
            if ($json['interview'] == '2+') {
                $having_query2 .= " and interviewsTaken > 2";
            } else {
                $having_query2 .= " and interviewsTaken = '" . $json['interview'] . "'";
            }
        }
        if ($json['createdOn'] != "") {
            $filter_query .= " and u.createdOn >= '" . strtotime($json['createdOn']) . "'";
        }

        if ($json['endSubscription'] !== "") {
            $filter_query .= " and sb.endDate <= '" . $json['endSubscription'] . "'";
        }
        if ($json['college'] != "" and sizeof($json['stream']) > 0) {
            $filter_query .= " and pd.college='" . $json['college'] . "'";
        }
        if ($json['paymentStatus'] != "") {
            if ($json['paymentStatus'] == '0') {
                $filter_query .= " and DATEDIFF(sb.endDate,CURDATE()) <= 0 ";
            } else if ($json['paymentStatus'] == '1') {
                $filter_query .= " and DATEDIFF(sb.endDate,CURDATE()) > 0  and sb.amount ='0' ";
            } else {
                $filter_query .= " and DATEDIFF(sb.endDate,CURDATE()) > 0 and sb.amount !='0' ";
            }
        }
        /* if($json['Id'] !=null){
            $filter_query.=" and u.id='".$json['Id']."'";
        } */
        $data = "select temp.*, max(m.interviewSessionId) as lastInterviewDate, count(distinct m.interviewSessionId) as interviewsTaken from (select u.id,u.createdOn as signUpDate, u.firstName as name,sb.amount,sb.duration,DATEDIFF(sb.endDate,CURDATE()) as sub_difference,sb.endDate,sb.productId,u.emailId, u.mobileNumber, st.stream as specialization, pd.year,pd.qualification, pd.college as cl_id,pd.languages, pd.communicationSkillRate, pd.cgpa, pd.fav_subjects, pd.fav_programming_skill,pd.fav_domain,pd.asp_companies, cl.collegeName as college, pd.specialization as str_id, SUM(CASE WHEN fr.review_status = 2 THEN 1 ELSE 0 END) as numOfFeedbackDelivered, SUM(CASE WHEN fr.review_status = 1 OR fr.review_status = 0 OR fr.review_status = -2 OR fr.review_status = -3 THEN 1 ELSE 0 END) as numOfFeedbackPending from users u left outer join professionaldetails pd on u.id = pd.candidateId left outer join stream st on pd.specialization=st.id left outer join colleges cl on cl.id=pd.college left outer join feedback_request fr on fr.candidateId = u.id  left outer join subscription sb on u.id = sb.candidateId where u.deleted_at is NULL and u.usertype='student'" . $filter_query . $group_query . $having_query1 . $order_query . " ) as temp left outer join mergedVideos m on m.candidateId = temp.id and m.interviewSessionId is not null GROUP by temp.id " . $having_query2 . " order by temp.signUpDate desc";

        // $data =$sql.$filter_query.$orderByQry;
        $queryResult = mysqli_query($databaseConnection, $data . $limit_query);
        //$query = mysqli_query($databaseConnection,$data);

        if ($queryResult) {
            //$total_data['count'] = mysqli_num_rows($query); 
            while ($row = mysqli_fetch_array($queryResult, MYSQLI_ASSOC)) {
                if ($row['productId'] != null) {
                    $productQuery = mysqli_query($databaseConnection, "SELECT sb.productId, 
                    group_concat(pt.name SEPARATOR ', ') AS product_name FROM subscription sb, 
                    product pt WHERE FIND_IN_SET(pt.id, sb.productId) and sb.candidateId = '" . $row['id'] . "'");
                    $productResult = mysqli_fetch_array($productQuery, MYSQLI_ASSOC);
                    $row['subscribedProduct_name'] = $productResult['product_name'];
                } else {
                    $row['product_name'] = null;
                }

                $progSkillQuery = mysqli_query($databaseConnection, "SELECT pd.fav_programming_skill, group_concat(fps.fav_prog_skill SEPARATOR ', ') AS fav_programming_skill_name FROM professionaldetails pd, fav_prog_skill fps WHERE FIND_IN_SET(fps.id, pd.fav_programming_skill) and candidateId = '" . $row['id'] . "'");
                $progSkillResult = mysqli_fetch_array($progSkillQuery, MYSQLI_ASSOC);
                $row['fav_programming_skill_name'] = $progSkillResult['fav_programming_skill_name'];

                $favSubjectsQuery = mysqli_query($databaseConnection, "SELECT pd.fav_subjects, group_concat(fs.favourite_subject SEPARATOR ', ') AS fav_subjects_name FROM professionaldetails pd, favourite_subject fs WHERE FIND_IN_SET(fs.id, pd.fav_subjects) and candidateId = '" . $row['id'] . "'");
                $favSubjectsResult = mysqli_fetch_array($favSubjectsQuery, MYSQLI_ASSOC);
                $row['fav_subjects_name'] = $favSubjectsResult['fav_subjects_name'];

                $aspCompaniesQuery = mysqli_query($databaseConnection, "SELECT pd.asp_companies, group_concat(ac.name SEPARATOR ', ') AS asp_companies_name FROM professionaldetails pd, aspiration_company ac WHERE FIND_IN_SET(ac.id, pd.asp_companies) and candidateId = '" . $row['id'] . "'");
                $aspCompaniesResult = mysqli_fetch_array($aspCompaniesQuery, MYSQLI_ASSOC);
                $row['asp_companies_name'] = $aspCompaniesResult['asp_companies_name'];

                $favDomainQuery = mysqli_query($databaseConnection, "SELECT pd.fav_domain, group_concat(fd.name SEPARATOR ', ') AS fav_domain_name FROM professionaldetails pd, favourite_domain fd WHERE FIND_IN_SET(fd.id, pd.fav_domain) and candidateId = '" . $row['id'] . "'");
                $favDomainResult = mysqli_fetch_array($favDomainQuery, MYSQLI_ASSOC);
                $row['fav_domain_name'] = $favDomainResult['fav_domain_name'];

                $languageQuery = mysqli_query($databaseConnection, "SELECT pd.languages, group_concat(l.name SEPARATOR ', ') AS languagesKnown FROM professionaldetails pd, language l WHERE FIND_IN_SET(l.id, pd.languages) and candidateId = '" . $row['id'] . "'");
                $languageResult = mysqli_fetch_array($languageQuery, MYSQLI_ASSOC);
                $row['languagesKnown'] = $languageResult['languagesKnown'];

                if ($row['interviewsTaken'] >= 1) {
                    $row['overallRatings'] = getOverallRatingsForAllInterviews($databaseConnection, $row['id']);
                } else {
                    $row['overallRatings'] = NULL;
                }

                array_push($result, $row);
            }
            $total_data['data'] = $result;

            $to_encode = $total_data;
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "success",
                'errorCode' => "no data avaialble",
                'query' => $data
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while retrieving information",

        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['updateStudentProduct'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['candidateId'];
        if ($json['productId'] != null) {
            $productId = implode(',', $json['productId']);
        } else {
            $productId = $json['productId'];
        }
        if ($json['totalhourAllow'] != null) {
            $totalhourAllow = implode(',', $json['totalhourAllow']);
        } else {
            $totalhourAllow = $json['totalhourAllow'];
        }
        if ($json['totalInterviewAllow'] != null) {
            $totalInterviewAllow = implode(',', $json['totalInterviewAllow']);
        } else {
            $totalInterviewAllow = $json['totalInterviewAllow'];
        }
        $amount = 0;
        $duration = '15 days';
        $date = date("Y-m-d");
        $endDate = date('Y-m-d', strtotime($date . ' + 15 days'));
        $sql = "select * from subscription where candidateId = '" . $candidateId . "'";
        $query = mysqli_query($databaseConnection, $sql);
        if (mysqli_num_rows($query) > 0) {
            $data = "UPDATE subscription set productId='" . $productId . "',totalInterviewAllowed='" . $totalInterviewAllow . "', hoursOfPractice='" . $totalhourAllow . "'  where candidateId='" . $candidateId . "'";
            $query1 = mysqli_query($databaseConnection, $data);
            if ($query1) {
                $to_encode = array(
                    'result' => "Success",
                    'response' => 'product in subscription Updated Successful.',
                    'status' => 1
                );
            } else {
                $to_encode = array(
                    'result' => "error",
                    'errorCode' => "product  update failed.",
                    'status' => -1,
                    'query' => $query
                );
            }
        } else {
            $insertSubQuery = "insert into subscription(candidateId, amount, duration, endDate,productId) values ('" . $candidateId . "','" . $amount . "' , '" . $duration . "','" . $endDate . "','" . $productId . "')";
            $insertSubResult = mysqli_query($databaseConnection, $insertSubQuery);
            if ($insertSubResult) {
                $Id = mysqli_insert_id($databaseConnection);
                $to_encode = array(
                    'status' => 1,
                    'result' => "success",
                    'Id' => $Id,
                    'message' => "Data inserted successfully",
                    'query' => $insertSubQuery
                );
            } else {
                $to_encode = array(
                    'status' => 0,
                    'result' => "error",
                    'message' => "Error while inserting subscription product data"
                );
            }
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "product information update failed.",
            'status' => -1
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getFreeTrialProductList'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $values = array();
        $data1 = "Select productId from interview where categoryType='8' group by productId order by productId";
        $query1 = mysqli_query($databaseConnection, $data1);
        $values1 = mysqli_fetch_all($query1, MYSQLI_ASSOC);

        $to_encode = $values1;
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while retrieving product"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getProductList'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $values = array();
        $data1 = "Select * from product order by id";
        $query1 = mysqli_query($databaseConnection, $data1);
        $values1 = mysqli_fetch_all($query1, MYSQLI_ASSOC);
        $values['product'] = $values1;
        $to_encode = $values;
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while retrieving product"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['insertCollegeSubscriptionData'])) {
    /* change in query startDate and allowed product added in subscription by Narayan 20-07-2021 */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $streamId = implode(',', $json['streamId']);
        $productId = implode(',', $json['productId']);
        $mockInterview = $json['mockInterview'];
        $communicationInterview = $json['communicationInterview'];
        $behaviouralInterview = $json['behaviouralInterview'];
        $problemsolvingInterview = $json['problemsolvingInterview'];
        $codingInterview = $json['codingInterview'];
        $freeTrialInterview = $json['freeTrialInterview'];
        $amount = $json['amount'];
        $startDate = $json['startSubscription'];
        $endDate = $json['endSubscription'];
        $collegeId = $json['collegeId'];
        $s_id = explode(",", $streamId);
        $insertSubResult = '';
        $updateSubResult = '';
        $allStreamQuery = mysqli_query($databaseConnection, "SELECT GROUP_CONCAT(DISTINCT id SEPARATOR ',') as stream FROM `stream` where isActive='Y' ");
        $allStreamValue = mysqli_fetch_all($allStreamQuery, MYSQLI_ASSOC);
        $all_sid = $allStreamValue[0]['stream'];
        $allStream = explode(",", $all_sid);
        $yop_value = explode(",", $json['yop']);
        for ($i = 0; $i < count($s_id); $i++) {
            for ($j = 0; $j < count($yop_value); $j++) {
                if ($s_id[$i] == '17') {
                    $checkCollege = mysqli_query($databaseConnection, "select * from college_subscription where collegeId='" . $collegeId . "' and yop = '" . $yop_value[$j] . "'");
                } else {
                    $checkCollege = mysqli_query($databaseConnection, "select * from college_subscription where collegeId='" . $collegeId . "'  and streamId ='" . $s_id[$i] . "' and yop = '" . $yop_value[$j] . "'");
                }

                if (mysqli_num_rows($checkCollege) == 0) {
                    if ($s_id[$i] == '17') {
                        for ($k = 0; $k < count($allStream); $k++) {
                            $insertSubQuery = "insert into college_subscription(`collegeId`,`streamId`,`yop`, `amount`,`subscriptionEndDate`,`subscriptionStartDate`,`productId`,`mockInterviewAllowed`, `communicationInterviewAllowed`, `behaviouralInterviewAllowed`, `problemsolvingInterviewAllowed`, `codingInterviewAllowed`,`freeTrialAllowed`) values ('" . $collegeId . "','" . $allStream[$k] . "','" . $yop_value[$j] . "','" . $amount . "' ,'" . $endDate . "','" . $startDate . "','" . $productId . "','" . $mockInterview . "','" . $communicationInterview . "','" . $behaviouralInterview . "','" . $problemsolvingInterview . "','" . $codingInterview . "','" . $freeTrialInterview . "')";
                            $insertSubResult = mysqli_query($databaseConnection, $insertSubQuery);
                        }
                    } else {
                        $insertSubQuery = "insert into college_subscription(`collegeId`,`streamId`,`yop`, `amount`,`subscriptionEndDate`,`subscriptionStartDate`,`productId`,`mockInterviewAllowed`, `communicationInterviewAllowed`, `behaviouralInterviewAllowed`, `problemsolvingInterviewAllowed`, `codingInterviewAllowed`,`freeTrialAllowed`) values ('" . $collegeId . "','" . $s_id[$i] . "','" . $yop_value[$j] . "','" . $amount . "' ,'" . $endDate . "','" . $startDate . "','" . $productId . "','" . $mockInterview . "','" . $communicationInterview . "','" . $behaviouralInterview . "','" . $problemsolvingInterview . "','" . $codingInterview . "','" . $freeTrialInterview . "')";
                        $insertSubResult = mysqli_query($databaseConnection, $insertSubQuery);
                    }
                } else {
                    if ($s_id[$i] == '17') {
                        for ($k = 0; $k < count($allStream); $k++) {
                            $updateSubQuery = "Update college_subscription set amount = '" . $amount . "',`subscriptionStartDate`='" . $startDate . "',subscriptionEndDate='" . $endDate . "',productId='" . $productId . "',`freeTrialAllowed`='" . $freeTrialInterview . "',`mockInterviewAllowed`='" . $mockInterview . "',`communicationInterviewAllowed`='" . $communicationInterview . "',`behaviouralInterviewAllowed`='" . $behaviouralInterview . "',`problemsolvingInterviewAllowed`='" . $problemsolvingInterview . "',`codingInterviewAllowed`='" . $codingInterview . "'  WHERE  collegeId='" . $collegeId . "' and streamId = '" . $allStream[$k] . "' and yop = '" . $yop_value[$j] . "' ";
                            $updateSubResult = mysqli_query($databaseConnection, $updateSubQuery);
                        }
                    } else {
                        $updateSubQuery = "Update college_subscription set amount = '" . $amount . "',`subscriptionStartDate`='" . $startDate . "',subscriptionEndDate='" . $endDate . "',productId='" . $productId . "',`freeTrialAllowed`='" . $freeTrialInterview . "',`mockInterviewAllowed`='" . $mockInterview . "',`communicationInterviewAllowed`='" . $communicationInterview . "',`behaviouralInterviewAllowed`='" . $behaviouralInterview . "',`problemsolvingInterviewAllowed`='" . $problemsolvingInterview . "',`codingInterviewAllowed`='" . $codingInterview . "'  WHERE  collegeId='" . $collegeId . "' and streamId = '" . $s_id[$i] . "' and yop = '" . $yop_value[$j] . "' ";
                        $updateSubResult = mysqli_query($databaseConnection, $updateSubQuery);
                    }
                }
            }
        }
        if ($insertSubResult != '') {
            $Id = mysqli_insert_id($databaseConnection);
            $to_encode = array(
                'status' => 1,
                'result' => "success",
                'Id' => $Id,
                'message' => "Data inserted successfully",
                'query' => $insertSubQuery
            );
        } else if ($updateSubResult != '') {
            $to_encode = array(
                'status' => 1,
                'result' => "success",
                'message' => "Data updated successfully"
            );
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'message' => "Error while inserting subscription data"
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while retrieving information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['updateBlukSubscription'])) {
    /* change in update query startDate  and product allowed added in subscription by Narayan 20-07-2021 */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = implode(',', $json['candidateId']);
        if ($json['productId'] != null) {
            $productId = implode(',', $json['productId']);
        } else {
            $productId = $json['productId'];
        }
        $mockInterview = $json['mockInterview'];
        $communicationInterview = $json['communicationInterview'];
        $behaviouralInterview = $json['behaviouralInterview'];
        $problemsolvingInterview = $json['problemsolvingInterview'];
        $codingInterview = $json['codingInterview'];
        $freeTrialInterview = $json['freeTrialInterview'];
        $amount = $json['amount'];
        $date = date('Y-m-d');
        $endDate = $json['endSubscription'];
        $startDate = $json['startSubscription'];
        $diff = (strtotime($endDate) - strtotime($startDate)) / 86400;
        $duration = strval($diff) . ' days';
        $updateSubQuery = "Update subscription SET amount = '" . $amount . "', duration = '" . $duration . "', endDate= '" . $endDate . "',startDate='" . $startDate . "', productId='" . $productId . "',`freeTrialAllowed`='" . $freeTrialInterview . "',`mockInterviewAllowed`='" . $mockInterview . "',`communicationInterviewAllowed`='" . $communicationInterview . "',`behaviouralInterviewAllowed`='" . $behaviouralInterview . "',`problemsolvingInterviewAllowed`='" . $problemsolvingInterview . "',`codingInterviewAllowed`='" . $codingInterview . "' WHERE candidateId in($candidateId)";
        $updateSubResult = mysqli_query($databaseConnection, $updateSubQuery);
        if ($updateSubResult) {
            $to_encode = array(
                'status' => 1,
                'result' => "success",
                'message' => "Data updated successfully"
            );
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'message' => 'Error while updating subscription data',
                'query1' => $updateSubQuery
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while retrieving information"
        );
    }
    echo json_encode($to_encode);
}
// node-api
elseif (isset($_GET['updateMentorAssign'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $candidateId = implode(',', $json['candidateId']);
        $mentorId = $json['mentorId'];

        $sql = "UPDATE `professionaldetails` SET `assignMentorId`= '" . $mentorId . "',`mentorAssignDate`=CURDATE() WHERE `candidateId` IN ($candidateId);";
        $query = mysqli_query($databaseConnection, $sql);
        if ($query) {
            $to_encode = array(
                'status' => 1,
                'result' => "success",
                'message' => "Data updated successfully"
            );
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'message' => "in Error while updating data",
                'qry' => $sql
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while retrieving information"
        );
    }
    echo json_encode($to_encode);
}
elseif (isset($_GET['updateStudentInfo'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['candidateId'];
        $specialization = $json['specialization'];
        $college = $json['college'];
        $year = $json['year'];
        $email = $json['emailId'];
        $name = $json['userName'];
        $mobile = $json['mobileNumber'];
        $qualification = $json['qualification'];
        $communication = $json['communication'];
        if ($json['favSubject'] != null) {
            $favSubject = implode(',', $json['favSubject']);
        } else {
            $favSubject = $json['favSubject'];
        }
        if ($json['favProgSkill'] != null) {
            $favProgSkill = implode(',', $json['favProgSkill']);
        } else {
            $favProgSkill = $json['favProgSkill'];
        }

        if ($json['aspCompanies'] != null) {
            $aspCompanies = implode(',', $json['aspCompanies']);
        } else {
            $aspCompanies = $json['aspCompanies'];
        }
        if ($json['languages'] != null) {
            $languages = implode(',', $json['languages']);
        } else {
            $languages = $json['languages'];
        }

        $userData = "update users set firstName='" . $name . "',isMentee='Y',`mobileNumber`='" . $mobile . "',`emailId`='" . $email . "' where id='" . $candidateId . "' ";
        $userQuery = mysqli_query($databaseConnection, $userData);


        $profData = "select * from professionaldetails where candidateId='" . $candidateId . "' limit 0,1";
        $profQuery = mysqli_query($databaseConnection, $profData);

        if (mysqli_num_rows($profQuery) == 0) {
            if ($qualification == NULL && $favSubject == NULL && $favProgSkill == NULL && $aspCompanies == NULL && $languages == NULL) {
                $sql = "INSERT INTO `professionaldetails` 
                (`candidateId`, `specialization`, `communicationSkillRate`,`college`, `year`) VALUES 
                ('$candidateId', '$specialization','$communication','$college', '$year');";
            } else {
                $sql = "INSERT INTO `professionaldetails` 
                (`candidateId`, `qualification`, `specialization`,`communicationSkillRate`,`college`, `year`, `fav_subjects`,  `fav_programming_skill`,  `asp_companies`,`languages`) VALUES 
                ('$candidateId', '$qualification', '$specialization','$communication', '$college', '$year', '$favSubject', '$favProgSkill', '$aspCompanies','$languages')";
            }
            $query = mysqli_query($databaseConnection, $sql);
        } else {
            if ($qualification == NULL && $favSubject == NULL && $favProgSkill == NULL && $aspCompanies == NULL && $languages == NULL) {
                $data = "UPDATE professionaldetails set specialization='" . $specialization . "',communicationSkillRate='" . $communication . "', college='" . $college . "',year='" . $year . "' where candidateId='" . $candidateId . "'";
            } else {
                $data = "UPDATE professionaldetails set qualification='" . $qualification . "', specialization= '" . $specialization . "',communicationSkillRate='" . $communication . "',college='" . $college . "', year='" . $year . "', fav_subjects= '" . $favSubject . "',fav_programming_skill= '" . $favProgSkill . "',asp_companies='" . $aspCompanies . "', languages='" . $languages . "' where candidateId='" . $candidateId . "'";
            }
            $query = mysqli_query($databaseConnection, $data);
        }
        if ($query) {
            mysqli_query($databaseConnection, "update users set isMentee = 'Y' where id = '" . $candidateId . "'");
            $to_encode = array(
                'result' => "Success",
                'response' => 'professional information Updated Successful.',
                'status' => 1,
            );
        } else {
            $to_encode = array(
                'result' => "error",
                'errorCode' => "Professional information update failed.",
                'status' => -1,
                'query' => $query
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Professional and user  information update failed.",
            'status' => -1
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['getStudentControlData'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['candidateId'];
        $values = array();

        $data1 = "select * from favourite_subject order by id";
        $query1 = mysqli_query($databaseConnection, $data1);
        $values1 = mysqli_fetch_all($query1, MYSQLI_ASSOC);

        $data2 = "select * from stream where isActive = 'Y' order by id=11,stream";
        $query2 = mysqli_query($databaseConnection, $data2);
        $values2 = mysqli_fetch_all($query2, MYSQLI_ASSOC);

        $data3 = "select * from favourite_domain order by id=39,name";
        $query3 = mysqli_query($databaseConnection, $data3);
        $values3 = mysqli_fetch_all($query3, MYSQLI_ASSOC);

        $data4 = "select * from aspiration_company order by id=40,name";
        $query4 = mysqli_query($databaseConnection, $data4);
        $values4 = mysqli_fetch_all($query4, MYSQLI_ASSOC);

        $data5 = "SELECT * FROM `fav_prog_skill` order by id=1";
        $query5 = mysqli_query($databaseConnection, $data5);
        $values5 = mysqli_fetch_all($query5, MYSQLI_ASSOC);

        $data6 = "SELECT * FROM `language` order by id=1";
        $query6 = mysqli_query($databaseConnection, $data6);
        $values6 = mysqli_fetch_all($query6, MYSQLI_ASSOC);

        $data7 = "SELECT * FROM `qualification` order by id=1";
        $query7 = mysqli_query($databaseConnection, $data7);
        $values7 = mysqli_fetch_all($query7, MYSQLI_ASSOC);

        $data8 = "SELECT * FROM `colleges` order by id=1";
        $query8 = mysqli_query($databaseConnection, $data8);
        $values8 = mysqli_fetch_all($query8, MYSQLI_ASSOC);

        $data9 = "SELECT id, concat(firstName,' ( ',usertype,' )') as name FROM `users` where usertype = 'mentor' or usertype='tpmentor' and deleted_at is null order by usertype,firstName Asc";
        $query9 = mysqli_query($databaseConnection, $data9);
        $values9 = mysqli_fetch_all($query9, MYSQLI_ASSOC);

        $data10 = "SELECT * from areasofinterest order by id asc";
        $query10 = mysqli_query($databaseConnection, $data10);
        $values10 = mysqli_fetch_all($query10, MYSQLI_ASSOC);


        $values['favourite_subject'] = $values1;
        $values['stream'] = $values2;
        $values['favourite_domain'] = $values3;
        $values['aspiration_company'] = $values4;
        $values['fav_prog_skill'] = $values5;
        $values['language'] = $values6;
        $values['qualification'] = $values7;
        $values['college'] = $values8;
        $values['mentor'] = $values9;
        $values['connecttomentor'] = $values10;
        $to_encode = $values;
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while getting student information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getCollegeSubscriptionData'])) {
    /* Added By Narayan 21-07-2021 for updating college subscription data*/
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $limit = $json['limit'];
        $start = ($json['page'] - 1) * $limit;
        $limit_query = $limit == 0 ? "" : " limit " . $start . "," . $limit;
        $filter_query = "";
        $data = '';
        $group_query = ' GROUP BY cs.collegeId,cs.streamId,cs.yop ';
        $order_query = " order by cs.subscriptionStartDate desc ";
        if ($json['stream'] != "" and sizeof($json['stream']) > 0) {
            $filter_query .= " and cs.streamId in ('" . implode("', '", $json['stream']) . "')";
        }

        if ($json['year'] != "") {
            $filter_query .= " and cs.yop in (" . $json['year'] . ")";
        }

        if ($json['startDate'] != "") {
            $filter_query .= " and  cs.subscriptionStartDate >= '" . $json['startDate'] . "'";
        }

        if ($json['endSubscription'] !== "") {
            $filter_query .= " and cs.subscriptionEndDate <= '" . $json['endSubscription'] . "' ";
        }
        if ($json['college'] != "" and sizeof($json['college']) > 0) {
            $filter_query .= " and cs.collegeId in ('" . implode("', '", array_map("addSlashToString", $json['college'])) . "')";
        }
        if ($json['paymentStatus'] != "") {
            if ($json['paymentStatus'] == '0') {
                $filter_query .= " and DATEDIFF(cs.subscriptionEndDate,CURDATE()) <= 0 ";
            } else if ($json['paymentStatus'] == '1') {
                $filter_query .= " and DATEDIFF(cs.subscriptionEndDate,CURDATE()) > 0  and cs.amount ='0' ";
            } else {
                $filter_query .= " and DATEDIFF(cs.subscriptionEndDate,CURDATE()) > 0 and cs.amount !='0' ";
            }
        }
        $data = " SELECT cs.* , c.collegeName,s.stream,DATEDIFF(cs.subscriptionEndDate,cs.subscriptionStartDate) as duration ,DATEDIFF(cs.subscriptionEndDate,CURDATE()) as s_endDifference from college_subscription cs inner join colleges c on cs.collegeId = c.id inner join stream s on s.id = cs.streamId " . $filter_query . $group_query . $order_query;
        $queryResult = mysqli_query($databaseConnection, $data . $limit_query);
        $query = mysqli_query($databaseConnection, $data);

        if (mysqli_num_rows($query) > 0) {
            $total_data['count'] = mysqli_num_rows($query);
            $row = mysqli_fetch_all($queryResult, MYSQLI_ASSOC);
            $total_data['data'] = $row;

            $to_encode = $total_data;
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "success",
                'errorCode' => "no data avaialble"
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while retrieving information",

        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getCurrentCollegeSubscriptionData'])) {
    /* Added By Naraayn  22-07-2021 for getiing particular row of  college subscription data*/
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $data = '';
        $data = " SELECT cs.* , c.collegeName,s.stream,DATEDIFF(cs.subscriptionEndDate,cs.subscriptionStartDate) as duration ,DATEDIFF(cs.subscriptionEndDate,CURDATE()) as s_endDifference from college_subscription cs inner join colleges c on cs.collegeId = c.id inner join stream s on s.id = cs.streamId WHERE cs.collegeId = '" . $json['college'] . "'  and cs.streamId ='" . $json['stream'] . "' and cs.yop = '" . $json['year'] . "'  ";
        $query = mysqli_query($databaseConnection, $data);
        if (mysqli_num_rows($query) == 1) {
            $row = mysqli_fetch_all($query, MYSQLI_ASSOC);
            $total_data['data'] = $row;
            $to_encode = $total_data;
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "success",
                'errorCode' => "no data avaialble"
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while retrieving information",

        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getCollegeSubscriptionControlData'])) {
    /* This method is Added for filter data on college subscription Page By Naraayn  7-20-2021 */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['candidateId'];
        $values = array();

        $data1 = "Select productId from interview where categoryType='8' group by productId order by productId";
        $query1 = mysqli_query($databaseConnection, $data1);
        $values1 = mysqli_fetch_all($query1, MYSQLI_ASSOC);
        $data2 = "select id,stream from stream where isActive = 'Y' order by id=11,stream";
        $query2 = mysqli_query($databaseConnection, $data2);
        $values2 = mysqli_fetch_all($query2, MYSQLI_ASSOC);
        $data3 = "SELECT id,collegeName FROM `colleges` order by id=1";
        $query3 = mysqli_query($databaseConnection, $data3);
        $values3 = mysqli_fetch_all($query3, MYSQLI_ASSOC);

        $values['freeProduct'] = $values1;
        $values['stream'] = $values2;
        $values['college'] = $values3;

        $to_encode = $values;
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while getting student information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['UpdateCollegeSubscriptionData'])) {
    /* Added By Naraayn  22-07-2021 for updating college subscription data*/
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $collegeId = $json['collegeId'];
        $yop = $json['yop'];
        $streamId = $json['streamId'];
        $amount = $json['amount'];
        $date = date('Y-m-d');
        $endDate = $json['endSubscription'];
        $startDate = $json['startSubscription'];
        $diff = (strtotime($endDate) - strtotime($startDate)) / 86400;
        if ($json['productId'] != null) {
            $productId = implode(',', $json['productId']);
        } else {
            $productId = $json['productId'];
        }
        $mockInterview = $json['mockInterview'];
        $communicationInterview = $json['communicationInterview'];
        $behaviouralInterview = $json['behaviouralInterview'];
        $problemsolvingInterview = $json['problemsolvingInterview'];
        $codingInterview = $json['codingInterview'];
        $freeTrialInterview = $json['freeTrialInterview'];

        /* change in update query startDate and product allowed added in subscription by Naraayn  20-07-2021 */
        $updateSubQuery = "Update college_subscription set `amount` = '" . $amount . "',`subscriptionStartDate`='" . $startDate . "',`subscriptionEndDate`='" . $endDate . "',`productId`='" . $productId . "',`freeTrialAllowed`='" . $freeTrialInterview . "',`mockInterviewAllowed`='" . $mockInterview . "',`communicationInterviewAllowed`='" . $communicationInterview . "',`behaviouralInterviewAllowed`='" . $behaviouralInterview . "',`problemsolvingInterviewAllowed`='" . $problemsolvingInterview . "',`codingInterviewAllowed`='" . $codingInterview . "'  WHERE  collegeId='" . $collegeId . "' and streamId = '" . $streamId . "' and yop = '" . $yop . "' ";
        $updateSubResult = mysqli_query($databaseConnection, $updateSubQuery);
        if ($updateSubResult) {
            $to_encode = array(
                'status' => 1,
                'result' => "success",
                'message' => "Data updated successfully"
            );
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'message' => 'Error while updating subscription data'
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while retrieving information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getQuestionForPersonalizedVideo'])) {
    /*this is for question info which have video feedback provided by expert Added by Naraayn  6/9/2021 */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    if (isset($json)) {
        $questionId = $json['questionId'];
        $values = array();

        $sql = "select q.*, t.name as topic_name, fs.favourite_subject as subject_name, c.name as concept_name from questions q left outer join topic t on q.topic_id = t.id left outer join favourite_subject fs on fs.id = q.subjectId left outer join concepts c on c.id = q.conceptId where q.id='" . $questionId . "'";
        $query = mysqli_query($databaseConnection, $sql);

        if (mysqli_num_rows($query) >= 1) {
            $values = array();
            //$row = mysqli_fetch_array($query, MYSQLI_ASSOC);
            while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {

                $row['questionHtml'] = nl2br($row['questionText']);

                $row['shortExpectedAnsHtml'] = nl2br($row['shortExpectedAns']);
                $values[] = $row;
            }
            $to_encode = $values;
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "out Error while retrieving question information"
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while retrieving question information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getpersonalizedVideoList'])) {
    /* this is for getting list of experts who provided video feedback for a same question 
        Added by Naraayn 6/9/2021 
    */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    if (isset($json)) {
        $limit = 50;
        $start = 0;
        $questionId = $json['questionId'];
        $filter_query = ' ';
        $limit = $json['limit'];
        $start = ($json['page'] - 1) * $limit;
        $order_query = "";
        $limit_query = $limit == 0 ? "" : " limit " . $start . "," . $limit;
        $values = array();

        $query = 'select p.name,er.rejected,er.vidLength,m.created as createdAt,er.id as expert_review_id,p.id as expertId,er.questionId, m.youtubeId as expertResponseVideoId from expert_review  er  inner join mergedVideos m on er.feedbackVideoURL= m.outputVideoURL inner join panel p on p.id = er.feedbackGivenBy where er.feedbackVideoURL is not NULL and er.questionId = "' . $questionId . '"  order by m.created desc';

        $result = mysqli_query($databaseConnection, $query . $limit_query);
        if (mysqli_num_rows($result) > 0) {
            $count_query = mysqli_query($databaseConnection, $query);
            $count_result = mysqli_num_rows($count_query);
            while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
                array_push($values, $row);
            }
            $to_encode = array(
                'personalizedVideoList' => $values,
                'count' => $count_result,
                'status' => 1
            );
        } else {
            $to_encode = array(
                'personalizedVideoList' => $values,
                'status' => 0,
                'count' => 0
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while retrieving question information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['covertPersonalizedVideoToGuidanceVideo'])) {
    /* this is converting personalized video feedback into guidance video inside Personalized-Video-feedback page
        Added by Naraayn 6/9/2021 
    */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $expertReviewId = $json['expertReviewId'];
        $questionId = $json['questionId'];
        $expertVideoId = $json['expertResponseVideoId'];
        $expertId = $json['expertId'];
        $vidLength = $json['vidLength'];
        $videoNumber = $json['videoNumber'];
        $imagesNumber = $json['imagesNumber'];

        $guidanceVideoQuery = "select * from questions_transection where questionId = '" . $questionId . "' and delegationType = 'guidanceVideo' ";
        $guidanceVideoResult = mysqli_query($databaseConnection, $guidanceVideoQuery);
        if (mysqli_num_rows($guidanceVideoResult) > 0) {
            $guidanceQry = "UPDATE questions_transection SET expertId = '" . $expertId . "', uploadStatus = '2', vimeoId = '" . $expertVideoId . "', vidLength = '" . $vidLength . "',noOfImages='" . $imagesNumber . "',noOfVideos='" . $videoNumber . "' WHERE questionId = '" . $questionId . "' and delegationType = 'guidanceVideo'";
            $guidanceRes = mysqli_query($databaseConnection, $guidanceQry);
        } else {
            $guidanceQry = "INSERT INTO questions_transection(expertId, questionId, delegationType, uploadStatus, vimeoId, vidLength,noOfImages,noOfVideos) VALUES ('" . $expertId . "', '" . $questionId . "', 'guidanceVideo', '2', '" . $expertVideoId . "', '" . $vidLength . "','" . $imagesNumber . "','" . $videoNumber . "')";
            $guidanceRes = mysqli_query($databaseConnection, $guidanceQry);
        }
        if ($guidanceRes === true) {
            $updateExpertReview = "update expert_review set feedbackVideoURL = NULL, vidLength = NULL, uploadStatus = NULL where id = '$expertReviewId'";
            $updateExpertReviewRes = mysqli_query($databaseConnection, $updateExpertReview);

            $updateQuestion = "update questions set expertAdvice = '" . $expertVideoId . "' where id = '" . $questionId . "'";
            $updateQuestionRes = mysqli_query($databaseConnection, $updateQuestion);

            if ($updateExpertReviewRes && $updateQuestionRes) {
                $to_encode = array(
                    'result' => "success",
                    'status' => 1
                );
            } else {
                $to_encode = array(
                    'result' => "error",
                    'status' => 0,
                    'errorCode' => "in Error while updating info."
                );
            }
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "in Error while updating information."
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while updating information.",
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['rejectPersonalizedVideoForGuidanceVideo'])) {
    /* this is for Rejecting  personalized video feedback FOr guidance video inside Personalized-Video-feedback page
        Added by Naraayn 18-06-2021 
    */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $expertReviewId = $json['expertReviewId'];
        $questionId = $json['questionId'];
        $expertId = $json['expertId'];
        $updateExpertReview = "update expert_review set rejected = 'Y' where id = '$expertReviewId'";
        $updateExpertReviewRejected = mysqli_query($databaseConnection, $updateExpertReview);
        if ($updateExpertReviewRejected) {
            $to_encode = array(
                'result' => "success",
                'status' => 1
            );
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "in Error while updating info."
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while updating information.",
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['rejectCandidateResponseForBestPeerVideo'])) {
    /* this is for Rejecting  personalized video feedback FOr guidance video inside Personalized-Video-feedback page
        Added by Naraayn 18-06-2021 
    */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $mergeId = $json['mergeId'];
        $questionId = $json['questionId'];
        // $candidateId =  $json['candidateId'];
        $updateMergedVideos = "update mergedVideos set rejected = 'Y', `rejectTime` = now() where mergeId = '$mergeId'";
        $rejectForPeerResponse = mysqli_query($databaseConnection, $updateMergedVideos);
        if ($rejectForPeerResponse) {
            $countQuery = mysqli_query($databaseConnection, "Select count(m.mergeId) as videoCount from mergedVideos m inner join feedback_request fr on fr.interviewSessionId = m.interviewSessionId where m.rejected='N' and m.interviewSessionId is not null and fr.review_status='2' and m.questionId='" . $questionId . "' ");
            $countResult = mysqli_fetch_array($countQuery, MYSQLI_ASSOC);
            if ($countResult['videoCount'] == '0') {
                $updateQuestion = "update questions set peerResponseStatus = 'NA' where peerResponseStatus = 'A' and id = '" . $questionId . "' ";
                $updateQuestionResult = mysqli_query($databaseConnection, $updateQuestion);
            }

            $to_encode = array(
                'result' => "success",
                'status' => 1
            );
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "in Error while updating info."
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while updating information.",
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getBestPeerResponse'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    if (isset($json)) {
        $questionId = $json['questionId'];
        $values = array();

        $sql = "select q.*, t.name as topic_name, fs.favourite_subject as subject_name, c.name as concept_name from questions q left outer join topic t on q.topic_id = t.id left outer join favourite_subject fs on fs.id = q.subjectId left outer join concepts c on c.id = q.conceptId where q.id='" . $questionId . "'";
        $query = mysqli_query($databaseConnection, $sql);

        if (mysqli_num_rows($query) >= 1) {
            $values = array();
            //$row = mysqli_fetch_array($query, MYSQLI_ASSOC);
            while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
                $keySkillQuery = mysqli_query($databaseConnection, "SELECT q.key_skill_id, group_concat(ks.key_skill SEPARATOR ', ') AS key_skill_name FROM questions q, key_skill ks WHERE FIND_IN_SET(ks.id, q.key_skill_id) and q.id = '" . $row['id'] . "';");
                $keySkillResult = mysqli_fetch_array($keySkillQuery, MYSQLI_ASSOC);
                $row['key_skill_name'] = $keySkillResult['key_skill_name'];

                $row['questionHtml'] = nl2br($row['questionText']);
                if ($row['source'] != null) {
                    $aspCompaniesQuery = mysqli_query($databaseConnection, "SELECT q.source, group_concat(ac.name SEPARATOR ',') AS questionSource FROM questions q, aspiration_company ac WHERE FIND_IN_SET(ac.id, q.source) and q.id = '" . $row['id'] . "'");
                    $aspCompaniesResult = mysqli_fetch_array($aspCompaniesQuery, MYSQLI_ASSOC);
                    $row['questionSource'] = $aspCompaniesResult['questionSource'];
                }
                $row['shortExpectedAnsHtml'] = nl2br($row['shortExpectedAns']);

                if ($row['mbr_id'] != 0) {
                    $row['isBestPeerExist'] = 'Y';

                    $mbr_query = mysqli_query($databaseConnection, 'select * from mergedVideos where mergeId=' . $row['mbr_id']);
                    $mbr_row = mysqli_fetch_assoc($mbr_query);
                    $mbr_wd_query = mysqli_query($databaseConnection, "select wd.text from whiteboard w,whiteboard_details wd where w.interviewSessionId = '" . $mbr_row['interviewSessionId'] . "' and wd.whiteBoardId=w.whiteboardId and w.interviewId='" . $mbr_row['interviewId'] . "' and w.candidateId ='" . $mbr_row['candidateId'] . "' and w.questionVideoId='" . $mbr_row['questionVideoId'] . "' and w.questionId = '" . $mbr_row['questionId'] . "' order by wd.id desc limit 0,1");
                    $mbr_wd_details = mysqli_fetch_assoc($mbr_wd_query);
                    $row['whiteboard_text'] = nl2br(htmlspecialchars($mbr_wd_details['text']));
                    $row['peerResponse'] = $mbr_row['youtubeId'];
                } else {
                    $row['isBestPeerExist'] = 'N';
                    $row['whiteboard_text'] = NULL;
                    $row['peerResponse'] = NULL;
                }

                $values[] = $row;
            }
            $to_encode = $values;
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "out Error while retrieving Interview information"
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while retrieving question information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getPeerResponseList'])) {
    /* this method is changed by narayan Jan 2022 */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    if (isset($json)) {
        $limit = 50;
        $start = 0;
        $questionId = $json['questionId'];
        $filter_query = " and er.overallRating > 4 and er.overallRating !='videoIssue' ";
        $having_query = " having 1 ";
        $limit = $json['limit'];
        $start = ($json['page'] - 1) * $limit;
        $order_query = "";
        $limit_query = $limit == 0 ? "" : " limit " . $start . "," . $limit;
        $values = array();
        if ($json['overallRatings'] != "") {
            if ($json['overallRatings'] == '7') {
                $filter_query .= " and er.overallRating  >= 7";
            } elseif ($json['overallRatings'] == '4') {
                $filter_query .= " and er.overallRating  > 4  and er.overallRating  < 7 ";
            } elseif ($json['overallRatings'] == '7,4') {
                $filter_query .= " and er.overallRating  > 4";
            } else {
                $filter_query .= " and er.overallRating  <= 4 ";
            }
        }

        if ($json['communicationSkill'] != "") {
            if ($json['communicationSkill'] === 'good') {
                $having_query .= " and communication >=7 ";
            } elseif ($json['communicationSkill'] === 'acceptable') {
                $having_query .= " and communication  < 7 and communication > 4 ";
            } else {
                $having_query .= " and communication <=4 ";
            }
        }
        if ($json['problemSolvingSkill'] != "") {
            if ($json['problemSolvingSkill'] === 'good') {
                $having_query .= " and problemSolving >=7 ";
            } elseif ($json['problemSolvingSkill'] === 'acceptable') {
                $having_query .= " and problemSolving  < 7 and problemSolving > 4 ";
            } else {
                $having_query .= " and problemSolving <=4 ";
            }
        }
        if ($json['codingSkill'] != "") {
            if ($json['codingSkill'] === 'good') {
                $having_query .= " and coding >=7 ";
            } elseif ($json['codingSkill'] === 'acceptable') {
                $having_query .= " and coding  < 7 and coding > 4 ";
            } else {
                $having_query .= " and coding <=4 ";
            }
        }
        if ($json['behaviouralSkill'] != "") {
            if ($json['behaviouralSkill'] === 'good') {
                $having_query .= " and behavioural >=7 ";
            } elseif ($json['behaviouralSkill'] === 'acceptable') {
                $having_query .= " and behavioural  < 7 and behavioural  > 4 ";
            } else {
                $having_query .= " and behavioural <=4 ";
            }
        }
        if ($json['confidence'] != "") {
            if ($json['confidence'] === 'good') {
                $having_query .= " and confidence >=7 ";
            } elseif ($json['confidence'] === 'acceptable') {
                $having_query .= " and confidence  < 7 and confidence  > 4 ";
            } else {
                $having_query .= " and confidence <=4 ";
            }
        }
        if ($json['readingSkill'] != "") {
            if ($json['readingSkill'] === 'good') {
                $having_query .= " and reading >=7 ";
            } elseif ($json['readingSkill'] === 'acceptable') {
                $having_query .= " and reading < 7 and reading > 4 ";
            } else {
                $having_query .= " and reading <=4 ";
            }
        }
        if ($json['listeningSkill'] != "") {
            if ($json['listeningSkill'] === 'good') {
                $having_query .= " and listening >=7 ";
            } elseif ($json['listeningSkill'] === 'acceptable') {
                $having_query .= " and listening < 7  and listening > 4 ";
            } else {
                $having_query .= " and listening <=4 ";
            }
        }
        if ($json['comprehensionSkill'] != "") {
            if ($json['comprehensionSkill'] === 'good') {
                $having_query .= " and comprehension >=7 ";
            } elseif ($json['comprehensionSkill'] === 'acceptable') {
                $having_query .= " and comprehension < 7 and comprehension > 4 ";
            } else {
                $having_query .= " and comprehension <=4 ";
            }
        }
        if ($json['grammarSkill'] != "") {
            if ($json['grammarSkill'] === 'good') {
                $having_query .= " and grammar >=7 ";
            } elseif ($json['grammarSkill'] === 'acceptable') {
                $having_query .= " and grammar < 7 and grammar > 4 ";
            } else {
                $having_query .= " and grammar <=4 ";
            }
        }
        if ($json['presentationSkill'] != "") {
            if ($json['presentationSkill'] === 'good') {
                $having_query .= " and presentation >=7 ";
            } elseif ($json['presentationSkill'] === 'acceptable') {
                $having_query .= " and presentation < 7 and presentation  > 4 ";
            } else {
                $having_query .= " and presentation <=4 ";
            }
        }

        $query = "select m.mergeId,m.emailSentDate,fr.id,m.rejected, m.interviewSessionId, m.vidLength,m.candidateId, u.firstName as name, u.mobileNumber, u.emailId, m.interviewId,(SELECT GROUP_CONCAT(key_skill) FROM `key_skill` WHERE FIND_IN_SET(id,q.key_skill_id)) as key_skill, i.name as interviewName, m.questionId, m.questionVideoId, m.youtubeId as studentResponseVideoId, er.overallRating,MAX(case when ks.key_skill = 'Communication Skill' then ov.observation_values end) as communication,MAX(case when  ks.key_skill = 'Confidence' then ov.observation_values end) as confidence,MAX(case when  ks.key_skill= 'Coding Skill' then ov.observation_values end) as coding,MAX(case when  ks.key_skill = 'Problem Solving Skill' then ov.observation_values end) as problemSolving,MAX(case when  ks.key_skill = 'Behavioural Skill' then ov.observation_values end) as behavioural,MAX(case when  ks.key_skill = 'Issues with Video' then ov.observation_values end) as videoIssue, MAX(case when ks.key_skill = 'Reading Skill' then ov.observation_values end) as reading ,MAX(case when  ks.key_skill = 'Listening Skill' then ov.observation_values end) as listening,MAX(case when ks.key_skill = 'Reading Comprehension' then ov.observation_values end) as comprehension,MAX(case when  ks.key_skill = 'Presentation Skill' then ov.observation_values end) as presentation,MAX(case when  ks.key_skill = 'Grammar & Vocabulary' then ov.observation_values end) as grammar,m.priority,m.rejectTime,p.name as expertName, p.linkedinProfile , p.phonenumber,p.emailId as expertEmail,er.id as reviewId from mergedVideos m LEFT OUTER JOIN questions q ON q.id = m.questionId inner join interview_questions_transection iqt on iqt.interviewId = m.interviewId and iqt.questionId = m.questionId inner join feedback_request fr on fr.interviewSessionId = m.interviewSessionId inner join expert_review er on er.feedback_request_id = fr.id and m.questionId = er.questionId LEFT OUTER JOIN panel p ON p.id = er.feedbackGivenBy inner join interview i on i.id = m.interviewId inner join expert_review_observation_details erod on erod.expertReviewId = er.id inner join observation_area oa on oa.id = erod.observationAreaId inner join key_skill as ks on ks.id = oa.key_skill left outer join observation_values as ov on ov.id = erod.observationValueId  inner join users u on u.id = m.candidateId  where m.interviewSessionId is not null and fr.review_status = '2' and m.questionId = '" . $questionId . "' " . $filter_query . " group by m.interviewSessionId " . $having_query . " ORDER BY m.priority DESC ";

        $count_query = "select m.interviewSessionId,
        MAX(case when ks.key_skill = 'Communication Skill' then ov.observation_values end) as communication,MAX(case when  ks.key_skill = 'Confidence' then ov.observation_values end) as confidence,MAX(case when  ks.key_skill= 'Coding Skill' then ov.observation_values end) as coding,MAX(case when  ks.key_skill = 'Problem Solving Skill' then ov.observation_values end) as problemSolving,MAX(case when  ks.key_skill = 'Behavioural Skill' then ov.observation_values end) as behavioural,MAX(case when  ks.key_skill = 'Issues with Video' then ov.observation_values end) as videoIssue, MAX(case when ks.key_skill = 'Reading Skill' then ov.observation_values end) as reading ,MAX(case when  ks.key_skill = 'Listening Skill' then ov.observation_values end) as listening,MAX(case when ks.key_skill = 'Reading Comprehension' then ov.observation_values end) as comprehension,MAX(case when  ks.key_skill = 'Presentation Skill' then ov.observation_values end) as presentation,MAX(case when  ks.key_skill = 'Grammar & Vocabulary' then ov.observation_values end) as grammar from mergedVideos m inner join feedback_request fr on fr.interviewSessionId = m.interviewSessionId inner join expert_review er on er.feedback_request_id = fr.id and m.questionId = er.questionId inner join interview i on i.id = m.interviewId inner join expert_review_observation_details erod on erod.expertReviewId = er.id inner join observation_area oa on oa.id = erod.observationAreaId inner join key_skill as ks on ks.id = oa.key_skill left outer join observation_values as ov on ov.id = erod.observationValueId  inner join users u on u.id = m.candidateId where m.interviewSessionId is not null and fr.review_status = '2' and m.questionId = '" . $questionId . "' " . $filter_query . " group by m.interviewSessionId " . $having_query . "";

        //filter query to get peer response
        //$query = 'select m.mergeId, m.interviewSessionId, m.candidateId, u.firstName as name, u.mobileNumber, u.emailId, m.interviewId, i.name as interviewName, m.questionId, m.questionVideoId, m.youtubeId as studentResponseVideoId from mergedVideos m inner join users u on u.id = m.candidateId inner join interview i on i.id = m.interviewId inner join feedback_request fr on fr.interviewSessionId = m.interviewSessionId inner join expert_review er on er.feedback_request_id = fr.id and er.questionId = m.questionId inner join expert_review_observation_details erod on erod.expertReviewId = er.id where m.interviewSessionId is not null and erod.observationValueId in (3,4,6,7,28,29,123,124,127,128) and fr.review_status = 2 and m.questionId ="'.$questionId.'" group by erod.expertReviewId';
        $result = mysqli_query($databaseConnection, $query . $limit_query);
        if (mysqli_num_rows($result) > 0) {
            $count_query1 = mysqli_query($databaseConnection, $count_query);
            $count_result = mysqli_num_rows($count_query1);
            //$values = mysqli_fetch_all($result, MYSQLI_ASSOC);
            while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
                $question_sequence = mysqli_query($databaseConnection, "select temp.row_number  from (SELECT  @rownum := @rownum + 1 as row_number , interviewSessionId,questionId  FROM mergedVideos cross join (select @rownum := 0) r where interviewSessionId ='" . $row['interviewSessionId'] . "' order by mergeId) as temp  where  temp.questionId  =  '" . $row['questionId'] . "' limit 1");
                $questionSequenceResult = mysqli_fetch_all($question_sequence, MYSQLI_ASSOC);
                $row['qnsNo'] = $questionSequenceResult[0]['row_number'];
                $mbr_wd_query = mysqli_query($databaseConnection, "select wd.text from whiteboard w,whiteboard_details wd where w.interviewSessionId = '" . $row['interviewSessionId'] . "' and wd.whiteBoardId=w.whiteboardId and w.interviewId='" . $row['interviewId'] . "' and w.candidateId ='" . $row['candidateId'] . "' and w.questionVideoId='" . $row['questionVideoId'] . "' and w.questionId = '" . $row['questionId'] . "' order by wd.id desc limit 0,1");
                $mbr_wd_details = mysqli_fetch_assoc($mbr_wd_query);
                $row['whiteboard_text'] = nl2br(htmlspecialchars($mbr_wd_details['text']));
                // $review_query = mysqli_query($databaseConnection, "SELECT erpd.observationValueId, group_concat(if(oa.observation_name = 'Others', erpd.message, oa.observation_name) SEPARATOR ', ') as observation_name, ov.observation_values, ks.key_skill, erpd.message FROM  expert_review er inner join `expert_review_observation_details` erpd on erpd.expertReviewId = er.id inner join observation_area as oa on oa.id = erpd.observationAreaId inner join key_skill as ks on ks.id = oa.key_skill left outer join observation_values as ov on ov.id = erpd.observationValueId WHERE er.feedback_request_id='" . $row['id'] . "' and er.questionId = '" . $row['questionId'] . "' and erpd.observationValueId is not null and oa.key_skill != 0 group by ks.id, erpd.observationValueId order by ks.id, ov.observation_values");
                $review_query = mysqli_query($databaseConnection, "SELECT t.name,CASE WHEN t1.observationValueId IS NULL THEN CONCAT(t.name,': ',t1.observation_namee) ELSE t1.observation_namee END as observation_name,t1.* from topic t LEFT OUTER JOIN questions q ON q.topic_id = t.id JOIN ( SELECT erpd.observationValueId, group_concat(if(oa.observation_name = 'Others', erpd.message, oa.observation_name) SEPARATOR ', ') as observation_namee, ov.observation_values, ks.id as key_skill_id, ks.key_skill,oa.observation_type, erpd.message FROM `expert_review_observation_details` as erpd inner join observation_area as oa on oa.id = erpd.observationAreaId inner join key_skill as ks on ks.id = oa.key_skill left outer join observation_values as ov on ov.id = erpd.observationValueId WHERE erpd.expertReviewId = " . $row['reviewId'] . " and oa.key_skill != 0 group by ks.id, erpd.observationValueId,oa.observation_type order by ks.id, ov.observation_values desc ) as t1 WHERE q.id =" . $row['questionId'] . "");
                if (mysqli_num_rows($review_query) > 0) {
                    $row['review_data'] = mysqli_fetch_all($review_query, MYSQLI_ASSOC);
                }

                array_push($values, $row);
            }
            $to_encode = array(
                'peerResponseList' => $values,
                'count' => $count_result,
                'status' => 1,
                'qry' => $query . $limit_query
            );
        } else {
            $to_encode = array(
                'peerResponseList' => $values,
                'status' => 0,
                'count' => 0
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while retrieving question information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['exportSelectedPeerResponseList'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userType = $json['userType'];
        $values = array();
        if ($userType === 'admin') {
            $query = "SELECT m.InterviewSessionId as SessionId,m.mergeId as MergeId,q.id as QuestionId,u.firstName as CandidateName,CASE WHEN m.emailSentDate is not null THEN m.emailSentDate ELSE 'NOT SENT' END  AS AutoEmailStatus, u.emailId as EmailId, u.mobileNumber as MobileNumber,i.name as InterviewName, concat('https://goprac.com/review?i=', i.id, '&c=', m.candidateId, '&s=', m.interviewSessionId) as InterviewLink FROM mergedVideos m inner join users u on m.candidateId = u.id inner join questions q on q.id = m.questionId inner join interview i on i.id=m.interviewId  inner join interview_questions_transection iqt on iqt.interviewId = i.id and m.questionId = iqt.questionId  WHERE interviewSessionId is not null and q.peerResponseStatus !='A' and q.peerResponseStatus !='NA' and q.mbr_id ='0' and find_in_set(m.mergeId,q.peerResponseStatus) group by m.mergeId order by m.candidateId";
            $queryResult = mysqli_query($databaseConnection, $query);
            if (mysqli_num_rows($queryResult) >= 1) {
                while ($row = mysqli_fetch_array($queryResult, MYSQLI_ASSOC)) {
                    $question_sequence = mysqli_query($databaseConnection, "select temp.row_number  from (SELECT  @rownum := @rownum + 1 as row_number , interviewSessionId,questionId  FROM mergedVideos cross join (select @rownum := 0) r where interviewSessionId ='" . $row['InterviewSessionId'] . "' order by mergeId) as temp  where  temp.questionId  =  '" . $row['QuestionId'] . "' limit 1");
                    $questionSequenceResult = mysqli_fetch_all($question_sequence, MYSQLI_ASSOC);
                    $row['QnsNoInInterview'] = $questionSequenceResult[0]['row_number'];
                    array_push($values, $row);
                }
                $to_encode = array(
                    'result' => "success",
                    'status' => 1,
                    'data' => $values
                );
            } else {
                $to_encode = array(
                    'result' => "error",
                    'status' => 0,
                    'errorCode' => "Error while downloading report"
                );
            }
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "You don't have premission to download"
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while retrieving slected PeerResponse information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['SendMailAgainForPeerResponse'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    /* This method is added for sending mail again to selected candidate who is already received mail for peerResponse video */
    /* added by Naraayn 24-sep-2021 */
    if (isset($json)) {
        $questionId = $json['questionId'];
        $interviewUrl = $json['interviewUrl'];
        $mergeId = $json['mergeId'];
        $email = $json['emailId'];
        $message = "<p>Dear " . $json['candidateName'] . ",</p>
                <p>Hope this mail finds you in great health!!</p>
                <p>First of all , I would like to appreciate you for the fantastic performance in the interview. Keep it up.</p>
                <p>One of your video response of a question has been selected by the expert of GoPrac.com for the purpose of training other students on the platform . Please find the details of that specfic qns below :</p>
                <ol>
                    <li>Interview Name:" . $json['interviewName'] . "</li>
                    <li>No of Qns selected by Expert:1</li>
                    <li>Qns No:" . $json['qnsNo'] . "</li>
                    <li>Qns ID:" . $questionId . "</li>
                    <li>Link of Interview:" . $interviewUrl . "</li>
                </ol>
                <p>We seek your permission to share your video response mentioned above with other students on the GoPrac platform. Other students will be able view & learn your video response . As a token of appreciation , we propose to pay Rs 100/- .</p>
                <p>If you are fine with our proposal, kindly acknowledge this mail and  share your Full Name &  Google pay / Paytm/ Phonepay wallet Number along with your PAN card number , so that our finance team can transfer the proposed amount in your account.</p>
                <p>In case you have any query , pls feel free to call me.</p>

                <p>Thanks & Regards,<br>Sunanda Tadi<br>Product Manager</P>
                <p>GOPRAC PVT. LTD.<br/>#607, 6th Floor,<br>Pride building,Bannergatta Road, <br> Bangalore - 560076<br>+91-9731107508</p>";
        $messageSend = sendEmailToUser($email, null, 'GoPrac.com: Reimburse your earnings', $message);
        if ($messageSend == 'Message has been sent successfully') {
            $updateIsEmailSend = mysqli_query($databaseConnection, "UPDATE mergedVideos set emailSentDate=CURDATE() where mergeId  in (" . $mergeId . ")");
            $to_encode = array(
                'status' => 1,
                'result' => "success",
                'message' => "email Sent successfully"
            );
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'message' => "email  Sending is failed",
                'query' => $message
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while sending mail information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['submitBestPeerResponse'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    if (isset($json)) {
        $questionId = $json['questionId'];
        $selectedMergeId = implode(",", $json['selectedMergeId']);
        $finalizedMergeId = $json['finalizedMergeId'];
        $messages = array();
        $emails = array();
        $emailMergeIds = array();


        $query = "update questions set peerResponseStatus = '" . $selectedMergeId . "', mbr_id = '" . $finalizedMergeId . "'  where id = '" . $questionId . "' ";
        $result = mysqli_query($databaseConnection, $query);
        if ($result) {
            if ($finalizedMergeId == 0 && $selectedMergeId != 'A') {
                $userInfo = mysqli_query($databaseConnection, "select m.mergeId, m.candidateId, u.firstName as name, i.name as interviewName, m.interviewSessionId,CONCAT('https://goprac.com/review?i=', m.interviewId, '&c=', m.candidateId, '&s=', m.interviewSessionId) as interviewURL,u.mobileNumber, u.emailId, m.interviewId,m.questionId from mergedVideos m inner join users u on u.id = m.candidateId inner join interview i on i.id = m.interviewId inner join interview_questions_transection iqt on iqt.interviewId = i.id and m.questionId = iqt.questionId where m.emailSentDate is null and  m.mergeId in (" . $selectedMergeId . ") ");

                if (mysqli_num_rows($userInfo) > 0) {
                    while ($candidateDetails = mysqli_fetch_array($userInfo, MYSQLI_ASSOC)) {
                        $question_sequence = mysqli_query($databaseConnection, "select temp.row_number  from (SELECT  @rownum := @rownum + 1 as row_number , interviewSessionId,questionId  FROM mergedVideos cross join (select @rownum := 0) r where interviewSessionId ='" . $candidateDetails['interviewSessionId'] . "' order by mergeId) as temp  where  temp.questionId  =  '" . $candidateDetails['questionId'] . "' limit 1");
                        $questionSequenceResult = mysqli_fetch_all($question_sequence, MYSQLI_ASSOC);
                        $candidateDetails['qnsNo'] = $questionSequenceResult[0]['row_number'];


                        $message = "<p>Dear " . $candidateDetails['name'] . ",</p>
                                <p>Hope this mail finds you in great health!!</p>
                                <p>First of all , I would like to appreciate you for the fantastic performance in the interview. Keep it up.</p>
                                <p>One of your video response of a question has been selected by the expert of GoPrac.com for the purpose of training other students on the platform . Please find the details of that specfic qns below :</p>
                                <ol>
                                    <li>Interview Name:" . $candidateDetails['interviewName'] . "</li>
                                    <li>No of Qns selected by Expert:1</li>
                                    <li>Qns No:" . $candidateDetails['qnsNo'] . "</li>
                                    <li>Qns ID:" . $candidateDetails['questionId'] . "</li>
                                    <li>Link of Interview:" . $candidateDetails['interviewURL'] . "</li>
                                </ol>
                                <p>We seek your permission to share your video response mentioned above with other students on the GoPrac platform. Other students will be able view & learn your video response . As a token of appreciation , we propose to pay Rs 100/- .</p>
                                <p>If you are fine with our proposal, kindly acknowledge this mail and  share your Full Name &  Google pay / Paytm/ Phonepay wallet Number along with your PAN card number , so that our finance team can transfer the proposed amount in your account.</p>
                                <p>In case you have any query , pls feel free to call me.</p>
    
    
                                <p>Thanks & Regards,<br>Sunanda Tadi<br>Product Manager</P>
                                <p>GOPRAC PVT. LTD.<br/>#607, 6th Floor,<br>Pride building,Bannergatta Road, <br> Bangalore - 560076<br>+91-9731107508</p>";
                        array_push($messages, $message);
                        array_push($emails, $candidateDetails['emailId']);
                        array_push($emailMergeIds, $candidateDetails['mergeId']);
                    }
                    $mergeIds = implode(",", $emailMergeIds);
                    $messageSend = sendEmailToMultiUser($emails, null, 'GoPrac.com: Reimburse your earnings', $messages);
                    if ($messageSend == 'Message has been sent successfully') {
                        $updateIsEmailSend = mysqli_query($databaseConnection, "UPDATE mergedVideos set emailSentDate=CURDATE() where mergeId  in (" . $mergeIds . ")");
                    }
                } else {
                    $to_encode = array(
                        'status' => 1,
                        'result' => "success",
                        'message' => "User have already got Mail"
                    );
                }
            }
            $to_encode = array(
                'status' => 1,
                'result' => "success",
                'message' => "updated successfully"
            );
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "in Error while retrieving question information"
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while retrieving question information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getExpertListForExpertAdvice'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    $filter = " where 1 and (0";
    $areaOfExpertise = $json['areaOfExpertise'];
    foreach ($areaOfExpertise as $afe) {
        $filter .= " OR FIND_IN_SET('" . $afe . "', areaOfExpertiseId )";
    }
    if (isset($json)) {
        $data = "select * from `panel` " . $filter . " ) AND deleted_at is null and expertStatus=1  order by name";
        $query = mysqli_query($databaseConnection, $data);
        if ($query) {
            if (mysqli_num_rows($query) >= 1) {
                $values = array();
                $values = mysqli_fetch_all($query, MYSQLI_ASSOC);
                $to_encode = $values;
            } else {
                $to_encode = array(
                    'result' => "error",
                    'status' => 0,
                    'errorCode' => "in Error while retrieving expert information."
                );
            }
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "in Error while retrieving expert information."

            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving expert information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['delegateQuestionForExpertAdvice'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    if (isset($json)) {
        $questionId = $json['questionId'];
        $questionIds = implode(',', array_map(function ($q) {
            return $q['id'];
        }, $questionId));
        $delegateQuesId = explode(',', $questionIds);
        $expertId = $json['expertId'];
        $guidanceVideo = $json['guidanceVideo'];
        $questionVideo = $json['questionVideo'];
        $peerResponseVideo = $json['peerResponseVideo'];
        $tagging = $json['tagging'];
        $quesQuery = "";
        // $highPriority = $json['highPriority'];

        foreach ($delegateQuesId as $quesId) {
            if ($guidanceVideo == true) {

                $gudCheck = "SELECT id , delegationType,uploadStatus from questions_transection where questionId= '" . $quesId . "' and delegationType= 'guidanceVideo'  ";
                $guidResult = mysqli_query($databaseConnection, $gudCheck);
                if (mysqli_num_rows($guidResult) >= 1) {
                    $guidrow = mysqli_fetch_assoc($guidResult);
                    if ($guidrow['uploadStatus'] == 0) {
                        $readynesscheck = mysqli_query($databaseConnection, "select q.id from questions q where q.expertAdvice is  null and q.id='" . $quesId . "' ");
                        if (mysqli_num_rows($readynesscheck) >= 1) {
                            $quesQuery = "update questions_transection set `expertId` = '" . $expertId . "', `uploadStatus`=0  where questionId = '" . $quesId . "' and delegationType= 'guidanceVideo'  ";
                            mysqli_query($databaseConnection, $quesQuery);
                        }
                    }

                } else {
                    $quesQuery = "INSERT INTO `questions_transection`(`expertId`, `questionId`, `uploadStatus`, `delegationType`) VALUES ('" . $expertId . "','" . $quesId . "', 0, 'guidanceVideo') ";
                    mysqli_query($databaseConnection, $quesQuery);
                }

            }
            if ($questionVideo == true) {
                $questionCheck = "SELECT id , delegationType,uploadStatus from questions_transection where questionId= '" . $quesId . "' and delegationType= 'questionVideo'  ";
                $quesResult = mysqli_query($databaseConnection, $questionCheck);
                if (mysqli_num_rows($quesResult) >= 1) {
                    $quesrow = mysqli_fetch_assoc($quesResult);
                    if ($quesrow['uploadStatus'] == 0) {
                        $readynesscheck = mysqli_query($databaseConnection, "select q.id from questions q where q.youtubeId = '314664775' and q.id='" . $quesId . "' ");
                        if (mysqli_num_rows($readynesscheck) >= 1) {

                            $quesQuery = "update questions_transection set `expertId` = '" . $expertId . "', `uploadStatus`=0  where questionId = '" . $quesId . "' and delegationType= 'questionVideo'  ";
                            mysqli_query($databaseConnection, $quesQuery);
                        }
                    }
                } else {
                    $quesQuery = "INSERT INTO `questions_transection`(`expertId`, `questionId`, `uploadStatus`, `delegationType`) VALUES ('" . $expertId . "','" . $quesId . "', 0, 'questionVideo') ";
                    mysqli_query($databaseConnection, $quesQuery);
                }

            }
            if ($peerResponseVideo == true) {
                $peerCheck = "SELECT id , delegationType,uploadStatus from questions_transection where questionId = '" . $quesId . "' and delegationType= 'peerResponseVideo'  ";
                $peerResult = mysqli_query($databaseConnection, $peerCheck);
                if (mysqli_num_rows($peerResult) >= 1) {
                    $peerrow = mysqli_fetch_assoc($peerResult);
                    if ($peerrow['uploadStatus'] == 0) {
                        $readynesscheck = mysqli_query($databaseConnection, "select q.id from questions q where (q.peerResponseVideo is not null or q.mbr_id != '0' or (q.peerResponseStatus !='A' and q.peerResponseStatus !='NA' ) ) and q.id='" . $quesId . "' ");
                        if (mysqli_num_rows($readynesscheck) == 0) {

                            $quesQuery = "update questions_transection set `expertId` = '" . $expertId . "', `uploadStatus`=0  where questionId = '" . $quesId . "' and delegationType= 'peerResponseVideo'  ";
                            mysqli_query($databaseConnection, $quesQuery);
                        }

                    }
                } else {
                    $readynesscheck = mysqli_query($databaseConnection, "select q.id from questions q where (q.peerResponseVideo is not null or q.mbr_id != '0' or (q.peerResponseStatus !='A' and q.peerResponseStatus !='NA' ) ) and q.id='" . $quesId . "' ");
                    if (mysqli_num_rows($readynesscheck) == 0) {

                        $quesQuery = "INSERT INTO `questions_transection`(`expertId`, `questionId`, `uploadStatus`, `delegationType`) VALUES ('" . $expertId . "','" . $quesId . "', 0, 'peerResponseVideo') ";
                        mysqli_query($databaseConnection, $quesQuery);
                    }
                }

            }
            if ($tagging == true) {
                $taggCheck = "SELECT id , delegationType,uploadStatus from questions_transection where questionId = '" . $quesId . "' and delegationType= 'tagging'  ";
                $taggResult = mysqli_query($databaseConnection, $taggCheck);
                if (mysqli_num_rows($taggResult) >= 1) {
                    $taggrow = mysqli_fetch_assoc($taggResult);
                    if ($taggrow['uploadStatus'] == 0) {
                        $readynesscheck = mysqli_query($databaseConnection, "select q.id from questions q where
                         (q.eligibleStreamId != '' AND q.eligibleStreamId IS NOT NULL AND q.subjectId != '' AND q.subjectId IS NOT NULL AND q.conceptId != '' AND q.conceptId IS NOT NULL AND q.key_skill_id != '' AND q.key_skill_id IS NOT NULL AND q.topic_id != '' AND q.topic_id IS NOT NULL AND q.isWbRequired != '' AND q.isWbRequired IS NOT NULL AND q.questionLevel != '' AND q.questionLevel IS NOT NULL) and q.id='" . $quesId . "' ");
                        if (mysqli_num_rows($readynesscheck) == 0) {
                            $quesQuery = "update questions_transection set `expertId` = '" . $expertId . "', `uploadStatus`=0  where questionId = '" . $quesId . "' and delegationType= 'tagging'  ";
                            mysqli_query($databaseConnection, $quesQuery);
                        }
                    }

                } else {
                    $quesQuery = "INSERT INTO `questions_transection`(`expertId`, `questionId`, `uploadStatus`, `delegationType`) VALUES ('" . $expertId . "','" . $quesId . "', 0, 'tagging') ";
                    mysqli_query($databaseConnection, $quesQuery);
                }

            }
            if ($tagging == true) {
                $Questionquery = mysqli_query($databaseConnection, "SELECT * from `questions` where id = '" . $quesId . "' ");
                $questionValue = mysqli_fetch_assoc($Questionquery);

                $check = mysqli_query($databaseConnection, "SELECT qtt.id ,qt.uploadStatus from questions_tagging_transection  qtt  inner join questions_transection qt on qt.id = qtt.id   where qt.delegationType = 'tagging' and qtt.questionId = '" . $quesId . "' ");
                if (mysqli_num_rows($check) >= 1) {
                    $checkrow = mysqli_fetch_assoc($check);
                    if ($checkrow['uploadStatus'] == 0) {
                        $readynesscheck = mysqli_query($databaseConnection, "select q.id from questions q where
                        (q.eligibleStreamId != '' AND q.eligibleStreamId IS NOT NULL AND q.subjectId != '' AND q.subjectId IS NOT NULL AND q.conceptId != '' AND q.conceptId IS NOT NULL AND q.key_skill_id != '' AND q.key_skill_id IS NOT NULL AND q.topic_id != '' AND q.topic_id IS NOT NULL AND q.isWbRequired != '' AND q.isWbRequired IS NOT NULL AND q.questionLevel != '' AND q.questionLevel IS NOT NULL) and q.id='" . $quesId . "' ");
                        if (mysqli_num_rows($readynesscheck) == 0) {
                            $transQuery = "update 
                        `questions_tagging_transection`
                        set `topicId`='" . $questionValue['topic_id'] . "', 
                            `keySkillId`='" . $questionValue['key_skill_id'] . "', 
                            `questionLevel`='" . $questionValue['questionLevel'] . "', 
                            `source`='" . $questionValue['source'] . "',
                            `eligibleStreamId`='" . $questionValue['eligibleStreamId'] . "',
                            `subjectId`='" . $questionValue['subjectId'] . "', 
                            `conceptId`='" . $questionValue['conceptId'] . "',
                            `domainId`='" . $questionValue['domainId'] . "',
                            `shortExpectedAns`='" . addslashes($questionValue['shortExpectedAns']) . "',
                            `instruction`='" . addslashes($questionValue['instruction']) . "',
                            `answerDuration`='" . $questionValue['answerDuration'] . "',
                            `thinkingTime` = '" . $questionValue['thinkingTime'] . "',
                            `isWbRequired`='" . $questionValue['isWbRequired'] . "',
                            `tutorialLink`='" . addslashes($questionValue['tutorialLink']) . "',
                            `remarks`='" . addslashes($questionValue['remarks']) . "',
                            `questionText` = '" . addslashes($questionValue['questionText']) . "'
                        where questionId = '" . $quesId . "' ";
                            $pass = mysqli_query($databaseConnection, $transQuery);
                        }
                    }
                } else {
                    $transQuery = "INSERT INTO `questions_tagging_transection`(`questionId`,`topicId`, `keySkillId`, `questionLevel`,`source`, `eligibleStreamId`, `subjectId`, `conceptId`, `domainId`,`shortExpectedAns`,`instruction`,`answerDuration`,`isWbRequired`,`tutorialLink`,`remarks`,`questionText`,`thinkingTime`) VALUES ('" . $quesId . "', '" . $questionValue['topic_id'] . "', '" . $questionValue['key_skill_id'] . "','" . $questionValue['questionLevel'] . "', '" . $questionValue['source'] . "','" . $questionValue['eligibleStreamId'] . "', '" . $questionValue['subjectId'] . "', '" . $questionValue['conceptId'] . "', '" . $questionValue['domainId'] . "','" . addslashes($questionValue['shortExpectedAns']) . "','" . addslashes($questionValue['instruction']) . "','" . $questionValue['answerDuration'] . "','" . $questionValue['isWbRequired'] . "','" . addslashes($questionValue['tutorialLink']) . "','" . addslashes($questionValue['remarks']) . "','" . addslashes($questionValue['questionText']) . "','" . $questionValue['thinkingTime'] . "') ";
                    $pass = mysqli_query($databaseConnection, $transQuery);
                }

            }
            // if ($highPriority == true) {
            //     $updatePriorityquery = "UPDATE questions set highPriority ='Y' where id ='" . $quesId . "' ";
            //     $updatePriorityResult = mysqli_query($databaseConnection, $updatePriorityquery);
            // }
        }
        if ($quesQuery != "") {
            $to_encode = array(
                'status' => 1,
                'result' => "success",
                'message' => "updated successfully"

            );
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "None of  Questions is Delegated"
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "None of  Questions is Delegated"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['autoDelegateQuestionForExpertAdvice'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    if (isset($json)) {
        $questionId = $json['questionId'];
        $questionIds = implode(',', array_map(function ($q) {
            return $q['id'];
        }, $questionId));
        $delegateQuesId = explode(',', $questionIds);
        $guidanceVideo = $json['guidanceVideo'];
        $questionVideo = $json['questionVideo'];
        $peerResponseVideo = $json['peerResponseVideo'];
        $tagging = $json['tagging'];
        $quesQuery = "";

        //$highPriority = $json['highPriority'];

        foreach ($delegateQuesId as $quesId) {
            if ($guidanceVideo == true) {
                $gudCheck = "SELECT id,delegationType,uploadStatus from questions_transection where questionId= '" . $quesId . "' and delegationType= 'guidanceVideo'  ";
                $guidResult = mysqli_query($databaseConnection, $gudCheck);
                if (mysqli_num_rows($guidResult) >= 1) {
                    $guidrow = mysqli_fetch_assoc($guidResult);
                    if ($guidrow['uploadStatus'] == 0) {
                        $readynesscheck = mysqli_query($databaseConnection, "select q.id from questions q where q.expertAdvice is  null and q.id='" . $quesId . "' ");
                        if (mysqli_num_rows($readynesscheck) >= 1) {
                            $quesQuery = "update questions_transection set `expertId` =NULL, `uploadStatus`=0  where questionId = '" . $quesId . "' and delegationType= 'guidanceVideo'  ";
                            mysqli_query($databaseConnection, $quesQuery);
                        }
                    }
                } else {

                    $quesQuery = "INSERT INTO `questions_transection`(`questionId`, `uploadStatus`, `delegationType`) VALUES ('" . $quesId . "', 0, 'guidanceVideo') ";
                    mysqli_query($databaseConnection, $quesQuery);
                }

            }
            if ($questionVideo == true) {
                $questionCheck = "SELECT id , delegationType,uploadStatus from questions_transection where questionId= '" . $quesId . "' and delegationType= 'questionVideo'  ";
                $quesResult = mysqli_query($databaseConnection, $questionCheck);
                if (mysqli_num_rows($quesResult) >= 1) {
                    $quesrow = mysqli_fetch_assoc($quesResult);
                    if ($quesrow['uploadStatus'] == 0) {
                        $readynesscheck = mysqli_query($databaseConnection, "select q.id from questions q where q.youtubeId = '314664775' and q.id='" . $quesId . "' ");
                        if (mysqli_num_rows($readynesscheck) >= 1) {
                            $quesQuery = "update questions_transection set `expertId` = NULL, `uploadStatus`=0  where questionId = '" . $quesId . "' and delegationType= 'questionVideo'  ";
                            mysqli_query($databaseConnection, $quesQuery);
                        }
                    }
                } else {
                    $quesQuery = "INSERT INTO `questions_transection`(`questionId`, `uploadStatus`, `delegationType`) VALUES ('" . $quesId . "', 0, 'questionVideo') ";
                    mysqli_query($databaseConnection, $quesQuery);
                }

            }
            if ($peerResponseVideo == true) {
                $peerCheck = "SELECT id , delegationType,uploadStatus from questions_transection where questionId = '" . $quesId . "' and delegationType= 'peerResponseVideo'  ";
                $peerResult = mysqli_query($databaseConnection, $peerCheck);
                if (mysqli_num_rows($peerResult) >= 1) {
                    $peerrow = mysqli_fetch_assoc($peerResult);
                    if ($peerrow['uploadStatus'] == 0) {
                        $readynesscheck = mysqli_query($databaseConnection, "select q.id from questions q where (q.peerResponseVideo is not null or q.mbr_id != '0' or (q.peerResponseStatus !='A' and q.peerResponseStatus !='NA' ) ) and q.id='" . $quesId . "' ");
                        if (mysqli_num_rows($readynesscheck) == 0) {
                            $quesQuery = "update questions_transection set `expertId` = NULL,`uploadStatus`=0  where questionId = '" . $quesId . "' and delegationType= 'peerResponseVideo'  ";
                            mysqli_query($databaseConnection, $quesQuery);
                        }
                    }
                } else {
                    $readynesscheck = mysqli_query($databaseConnection, "select q.id from questions q where (q.peerResponseVideo is not null or q.mbr_id != '0' or (q.peerResponseStatus !='A' and q.peerResponseStatus !='NA' ) ) and q.id='" . $quesId . "' ");
                    if (mysqli_num_rows($readynesscheck) == 0) {
                        $quesQuery = "INSERT INTO `questions_transection`(`questionId`, `uploadStatus`, `delegationType`) VALUES ('" . $quesId . "', 0, 'peerResponseVideo') ";
                        mysqli_query($databaseConnection, $quesQuery);
                    }
                }

            }
            if ($tagging == true) {
                $taggCheck = "SELECT id , delegationType,uploadStatus from questions_transection where questionId = '" . $quesId . "' and delegationType= 'tagging'  ";
                $taggResult = mysqli_query($databaseConnection, $taggCheck);
                if (mysqli_num_rows($taggResult) >= 1) {
                    $taggrow = mysqli_fetch_assoc($taggResult);
                    if ($taggrow['uploadStatus'] == 0) {
                        $readynesscheck = mysqli_query($databaseConnection, "select q.id from questions q where
                        (q.eligibleStreamId != '' AND q.eligibleStreamId IS NOT NULL AND q.subjectId != '' AND q.subjectId IS NOT NULL AND q.conceptId != '' AND q.conceptId IS NOT NULL AND q.key_skill_id != '' AND q.key_skill_id IS NOT NULL AND q.topic_id != '' AND q.topic_id IS NOT NULL AND q.isWbRequired != '' AND q.isWbRequired IS NOT NULL AND q.questionLevel != '' AND q.questionLevel IS NOT NULL) and q.id='" . $quesId . "' ");
                        if (mysqli_num_rows($readynesscheck) == 0) {
                            $quesQuery = "update questions_transection set `expertId` = '', `uploadStatus`=0  where questionId = '" . $quesId . "' and delegationType= 'tagging'  ";
                            mysqli_query($databaseConnection, $quesQuery);
                        }

                    }
                } else {
                    $quesQuery = "INSERT INTO `questions_transection`(`questionId`, `uploadStatus`, `delegationType`) VALUES ('" . $quesId . "', 0, 'tagging') ";
                    mysqli_query($databaseConnection, $quesQuery);
                }

            }
            if ($tagging == true) {

                $Questionquery = mysqli_query($databaseConnection, "SELECT * from `questions` where id = '" . $quesId . "' ");
                $questionValue = mysqli_fetch_assoc($Questionquery);

                $check = mysqli_query($databaseConnection, "SELECT qtt.id ,qt.uploadStatus from questions_tagging_transection  qtt  inner join questions_transection qt on qt.id = qtt.id   where qt.delegationType = 'tagging' and qtt.questionId = '" . $quesId . "' ");
                if (mysqli_num_rows($check) >= 1) {
                    $checkrow = mysqli_fetch_assoc($check);
                    if ($checkrow['uploadStatus'] == 0) {
                        $readynesscheck = mysqli_query($databaseConnection, "select q.id from questions q where
                        (q.eligibleStreamId != '' AND q.eligibleStreamId IS NOT NULL AND q.subjectId != '' AND q.subjectId IS NOT NULL AND q.conceptId != '' AND q.conceptId IS NOT NULL AND q.key_skill_id != '' AND q.key_skill_id IS NOT NULL AND q.topic_id != '' AND q.topic_id IS NOT NULL AND q.isWbRequired != '' AND q.isWbRequired IS NOT NULL AND q.questionLevel != '' AND q.questionLevel IS NOT NULL) and q.id='" . $quesId . "' ");
                        if (mysqli_num_rows($readynesscheck) == 0) {
                            $transQuery = "update 
                        `questions_tagging_transection`
                        set `topicId`='" . $questionValue['topic_id'] . "', 
                            `keySkillId`='" . $questionValue['key_skill_id'] . "', 
                            `questionLevel`='" . $questionValue['questionLevel'] . "', 
                            `source`='" . $questionValue['source'] . "',
                            `eligibleStreamId`='" . $questionValue['eligibleStreamId'] . "',
                            `subjectId`='" . $questionValue['subjectId'] . "', 
                            `conceptId`='" . $questionValue['conceptId'] . "',
                            `domainId`='" . $questionValue['domainId'] . "',
                            `shortExpectedAns`='" . addslashes($questionValue['shortExpectedAns']) . "',
                            `instruction`='" . addslashes($questionValue['instruction']) . "',
                            `answerDuration`='" . $questionValue['answerDuration'] . "',
                            `thinkingTime` = '" . $questionValue['thinkingTime'] . "',
                            `isWbRequired`='" . $questionValue['isWbRequired'] . "',
                            `tutorialLink`='" . addslashes($questionValue['tutorialLink']) . "',
                            `remarks`='" . addslashes($questionValue['remarks']) . "',
                            `questionText` = '" . addslashes($questionValue['questionText']) . "'
                        where questionId = '" . $quesId . "' ";

                            $pass = mysqli_query($databaseConnection, $transQuery);
                        }
                    }
                } else {
                    $transQuery = "INSERT INTO `questions_tagging_transection`(`questionId`,`topicId`, `keySkillId`, `questionLevel`,`source`, `eligibleStreamId`, `subjectId`, `conceptId`, `domainId`,`shortExpectedAns`,`instruction`,`answerDuration`,`isWbRequired`,`tutorialLink`,`remarks`,`questionText`,`thinkingTime`) VALUES ('" . $quesId . "', '" . $questionValue['topic_id'] . "', '" . $questionValue['key_skill_id'] . "','" . $questionValue['questionLevel'] . "', '" . $questionValue['source'] . "','" . $questionValue['eligibleStreamId'] . "', '" . $questionValue['subjectId'] . "', '" . $questionValue['conceptId'] . "', '" . $questionValue['domainId'] . "','" . addslashes($questionValue['shortExpectedAns']) . "','" . addslashes($questionValue['instruction']) . "','" . $questionValue['answerDuration'] . "','" . $questionValue['isWbRequired'] . "','" . addslashes($questionValue['tutorialLink']) . "','" . addslashes($questionValue['remarks']) . "','" . addslashes($questionValue['questionText']) . "','" . $questionValue['thinkingTime'] . "') ";
                    $pass = mysqli_query($databaseConnection, $transQuery);
                }

            }
            // if ($highPriority == true) {
            //     $updatePriorityquery = "UPDATE questions set highPriority ='Y' where id ='" . $quesId . "' ";
            //     $updatePriorityResult = mysqli_query($databaseConnection, $updatePriorityquery);
            // }
        }
        if ($quesQuery != "") {
            $to_encode = array(
                'status' => 1,
                'result' => "success",
                'message' => "updated successfully"

            );
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "No Question is Delegated "
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "No Question is Delegated"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getSuggestedNameList'])) {
    /* this method is added by devanand 13-nov-2021 for getting user name suggestion */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        if ($json['name'] != "") {
            $name = $json['name'];
            $data = " SELECT name as name FROM `panel` where name like '%" . $name . "%' limit 0,20";
            $query = mysqli_query($databaseConnection, $data);
            if (mysqli_num_rows($query) >= 1) {
                $values = mysqli_fetch_all($query, MYSQLI_ASSOC);
                $to_encode = $values;
            } else {
                $to_encode = array(
                    'status' => 0,
                    'result' => "no info",
                    'errorCode' => "no interview info found",
                    'query' => $data
                );
            }

        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "no info",
                'errorCode' => "No Key Press yet",
            );
        }

    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving interview information."
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getStudentActivityData'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $filter_query = " ";
        $limit = $json['limit'];
        $start = ($json['page'] - 1) * $limit;
        $limit_query = $limit == 0 ? "" : " limit " . $start . "," . $limit;
        $values = array();
        $collegeId = '';
        $specialization = '';
        $year = '';
        $name = '';
        $rawData = " ";
        $having_query1 = " having 1 ";
        $having_query2 = " having 1 ";
        $group_query = ' GROUP BY u.id';
        $order_query = " order by u.createdOn desc ";
        $interview_query = " Where 1 ";
        $led_filter_query = " ";
        $passive0_led = " ";
        $active0_led = " ";
        $active1_led = " ";
        $having_query = " having 1 ";
        $skillQuery = " ";
        $skill_filter = " ";


        /*  if ($json['led_from_date'] != "" || $json['led_to_date'] != ""){

             if ($json['passiveStudent'] == "Y") {

                 $passive0_led .= " and DATEDIFF(date_format(from_unixtime(floor(mv.interviewSessionId/1000)),'%Y-%m-%d'),pd.contact_Date) >=0";
             }

             if ($json['activeStudent'] == "Y") {

                 $active0_led .= " and DATEDIFF(date_format(from_unixtime(floor(mv.interviewSessionId/1000)),'%Y-%m-%d'),pd.contact_Date) >=0";
             }

             if ($json['ultraActiveStudent'] == "Y") {

                 $active1_led .= " and DATEDIFF(date_format(from_unixtime(floor(mv.interviewSessionId/1000)),'%Y-%m-%d'),pd.contact_Date) >=0";
             }
         }
  */
        if ($json['passiveStudent'] == "Y") {

            $having_query2 .= " and interviewsTaken  >= 0 ";
            $filter_query .= " and (Select count(DISTINCT mv.interviewSessionId ) from mergedVideos mv where mv.interviewSessionId is not null " . $passive0_led . "  and mv.candidateId = pd.candidateId ) = 0";
        }

        if ($json['activeStudent'] == "Y") {

            $having_query2 .= " and interviewsTaken > 0 ";
            $filter_query .= " AND (Select count(DISTINCT mv.interviewSessionId ) from mergedVideos mv where mv.interviewSessionId is not null and mv.candidateId = pd.candidateId " . $active0_led . " ) >= 1 AND (Select count(DISTINCT fr.interviewSessionId ) from feedback_request fr where  fr.candidateId = pd.candidateId and fr.review_status in (-3,1,2,0)) = 0";
        }

        if ($json['ultraActiveStudent'] == "Y") {

            $having_query2 .= " and interviewsTaken  > 0 ";
            $filter_query .= " and (Select count(DISTINCT mv.interviewSessionId ) from mergedVideos mv where mv.interviewSessionId is NOT null and mv.candidateId = pd.candidateId " . $active1_led . " ) >= 1 AND (Select count(DISTINCT fr.interviewSessionId ) from feedback_request fr where  fr.candidateId = pd.candidateId and fr.review_status in (-3,1,2,0))>0";
        }
        /* 

                if($userType == 'mentor' || $userType == 'admin' ){
                    if($json['isSalesFilter'] == 'Y') {
                        if ($json['led_from_date'] != "" && $json['led_to_date'] == ""){
                            $led_filter_query .= "  AND pd.s_contact_Date>='" .$json['led_from_date']. "'";
                        }

                        if ($json['led_from_date'] == "" && $json['led_to_date'] != ""){
                            $led_filter_query .= " and pd.s_contact_Date <= '" .$json['led_to_date']. "'";
                        }

                        if ($json['led_from_date'] != "" && $json['led_to_date'] != ""){
                            $led_filter_query .= " and pd.s_contact_Date >= '" .$json['led_from_date']. "' and pd.s_contact_Date <= '" .$json['led_to_date']. "'";
                        }
                    }
                    else {
                        if ($json['led_from_date'] != "" && $json['led_to_date'] == ""){
                            $led_filter_query .= "  AND pd.contact_Date>='" .$json['led_from_date']. "'";
                        }

                        if ($json['led_from_date'] == "" && $json['led_to_date'] != ""){
                            $led_filter_query .= " and pd.contact_Date <= '" .$json['led_to_date']. "'";
                        }

                        if ($json['led_from_date'] != "" && $json['led_to_date'] != ""){
                            $led_filter_query .= " and pd.contact_Date >= '" .$json['led_from_date']. "' and pd.contact_Date <= '" .$json['led_to_date']. "'";
                        }
                    }
                }
         */

        /*  if($json['webinar'] !=''){
             if($json['webinar'] == '0') {
                 $filter_query .= " and wrd.attend = 'Y' ";
             } else{
                 $filter_query .= " and (wrd.attend is NULL  OR wrd.attend ='N') ";
             }
         }

  */
        if ($json['college'] != "" and sizeof($json['college']) > 0)
            $filter_query .= " and pd.college in ('" . implode("', '", array_map("addSlashToString", $json['college'])) . "')";
        if ($json['stream'] != "" and sizeof($json['stream']) > 0)
            $filter_query .= " and pd.specialization in ('" . implode("', '", $json['stream']) . "')";
        //$filter_query.=" and pd.specialization in ('".$json['stream']."')";
        if ($json['year'] != "")
            $filter_query .= " and pd.year in (" . $json['year'] . ")";
        if ($json['name'] != "")
            $filter_query .= " and u.firstName like '%" . $json['name'] . "%'";
        /* if ($json['favouriteSubject'] != "" and sizeof($json['favouriteSubject']) > 0)
            $filter_query .= " and pd.fav_subjects in ('" . implode("','", $json['favouriteSubject']) . "')"; */
        /*  if ($json['progLanguage'] != "" and sizeof($json['progLanguage']) > 0)
             $filter_query .= " and pd.fav_programming_skill in ('" . implode("','", $json['progLanguage']) . "')"; */
        /*  if ($json['targetCompanies'] != "" and sizeof($json['targetCompanies']) > 0)
             $filter_query .= " and pd.asp_companies in ('" . implode("','", $json['targetCompanies']) . "')"; */
        /* if ($json['mentorshipFormStatus'] != "")
            $filter_query .= " and u.isMentee ='" . $json['mentorshipFormStatus'] . "'"; */
        if ($json['numOfInterviewsTaken'] != "") {
            if ($json['numOfInterviewsTaken'] == '3+') {
                $having_query2 .= " and interviewsTaken > 3";
            } elseif ($json['numOfInterviewsTaken'] == '0+') {
                $having_query2 .= " and interviewsTaken > 0";
            } else {
                $having_query2 .= " and interviewsTaken = '" . $json['numOfInterviewsTaken'] . "'";
            }
        }
        /*  if ($json['studentIssue'] != "") {
             $filter_query .= " and pd.student_issue = '" . addslashes($json['studentIssue']) . "'";
         } */
        if ($userType == 'admin') {
            if ($json['isTieUpStatus'] != "") {
                if ($userType != 'college') {
                    $rawData .= " inner join raw_data rd on rd.email_id = u.emailId ";

                    if ($json['isTieUpStatus'] == 'Y') {
                        $filter_query .= " and rd.isPaid = 'Y'";
                    } elseif ($json['isTieUpStatus'] == 'F') {
                        $filter_query .= " and rd.isPaid = 'F'";
                    } else {
                        $filter_query .= " and rd.isPaid = 'N'";
                    }

                }

            }
        }
        if ($json['from_date'] != "" && $json['to_date'] == "") {
            $filter_query .= " and u.createdOn >= '" . strtotime($json['from_date']) . "'";
        }
        if ($json['from_date'] == "" && $json['to_date'] != "") {
            $filter_query .= " and u.createdOn <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";
        }
        if ($json['from_date'] != "" && $json['to_date'] != "") {
            $filter_query .= " and u.createdOn >= '" . strtotime($json['from_date']) . "' and u.createdOn <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";
        }
        /* if ($json['communicationSkillRating'] != "")
           $filter_query .= " and pd.communicationSkillRate ='" . $json['communicationSkillRating'] . "'"; */
        /* if ($json['isFeedbackPending'] != "") {
            if ($json['isFeedbackPending'] == 'no') {
                $having_query2 .= "  and numOfFeedbackDelivered > 0";
            } else if ($json['isFeedbackPending'] == 'yes') {
                $having_query2 .= "  and numOfFeedbackPending > 0";
            } else {
                $interview_query .= " and  (fr.review_status !='-4' and fr.candidateId = fr.createdBy)  OR ( fr.review_status = '-4' and fr.candidateId = fr.createdBy and fr.candidateId != fr.rejectedBy) ";
            }
        }
 */
        /*  if ($json['isWebinar'] != "") {
             if ($json['isWebinar'] == '1') {
                 $filter_query .= " and pd.webinarTopic is not null ";
             } else {
                 $filter_query .= " and pd.webinarTopic is null ";
             }
         } */
        /* if ($json['mentoringStatus'] != "") {
            if ($json['mentoringStatus'] == '1') {
                $filter_query .= " and pd.mentoringStatus ='1' ";
            } else {
                $filter_query .= " and pd.mentoringStatus ='0' ";
            }
        } */
        /*  if ($json['meetingStatus'] != "") {
             if ($json['meetingStatus'] == '1') {
                 $filter_query .= " and pd.contact_Date is not null ";
             } else if ($json['meetingStatus'] == '0') {
                 $filter_query .= " and DATEDIFF(pd.nextMeetingDate,CURDATE()) = 0 ";
             } else if ($json['meetingStatus'] == '-1') {
                 $filter_query .= " and DATEDIFF(pd.nextMeetingDate,CURDATE()) < 0 ";
             } else {
                 $filter_query .= " and DATEDIFF(pd.nextMeetingDate , CURDATE()) > 0 ";
             }
         }
         */ /* if ($json['isInterviewDate'] != "") {
     if ($json['isInterviewDate'] == "1") {
         if ($json['from_date'] != "" && $json['to_date'] == "")
  */            /*$filter_query.=" and fr.interviewSessionId >= '".strtotime($json['from_date'])."'";*/
        /* $interview_query .= " and m.interviewSessionId >= '" . strtotime($json['from_date']) . "'";

    if ($json['from_date'] == "" && $json['to_date'] != "") */
        /* $filter_query.=" and fr.interviewSessionId <= '".strtotime('+1 day', strtotime($json['to_date']))."'";*/
        /* $interview_query .= " and m.interviewSessionId <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";
    if ($json['from_date'] != "" && $json['to_date'] != "")
         *//*$filter_query.=" and fr.interviewSessionId >= '".strtotime($json['from_date'])."' and fr.interviewSessionId <= '".strtotime('+1 day', strtotime($json['to_date']))."'";*/
        /*  $interview_query .= " and m.interviewSessionId >= '" . strtotime($json['from_date']) . "' and m.interviewSessionId <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";
 } else {
     if ($json['from_date'] != "" && $json['to_date'] == "")
         $filter_query .= " and u.createdOn >= '" . strtotime($json['from_date']) . "'";
     if ($json['from_date'] == "" && $json['to_date'] != "")
         $filter_query .= " and u.createdOn <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";
     if ($json['from_date'] != "" && $json['to_date'] != "")
         $filter_query .= " and u.createdOn >= '" . strtotime($json['from_date']) . "' and u.createdOn <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";
 }
} else {
 if ($json['from_date'] != "" && $json['to_date'] == "")
     $filter_query .= " and u.createdOn >= '" . strtotime($json['from_date']) . "'";
 if ($json['from_date'] == "" && $json['to_date'] != "")
     $filter_query .= " and u.createdOn <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";
 if ($json['from_date'] != "" && $json['to_date'] != "")
     $filter_query .= " and u.createdOn >= '" . strtotime($json['from_date']) . "' and u.createdOn <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";
} */

        /* if ($json['sectorId'] != "") {
            $filter_query .= " AND ces.sectorId IN (".$json['sectorId'].")";
        }

        if ($json['emp_status'] != "") {
            $filter_query .= " AND ces.empstatus = '".$json['emp_status']."'";
        } */

        /* if ($json['student_aptitude'] != "" || $json['subject_name'] != "") {
            $rawData .= " LEFT OUTER JOIN  expert_review er ON er.candidateId = u.id LEFT OUTER JOIN feedback_request fr ON fr.id = er.feedback_request_id ";
            $rawData .= "  LEFT OUTER JOIN questions q ON q.id = er.questionId ";
        }
        if ($json['student_aptitude'] != "") {
            $filter_query .= " AND er.overallRating != 'videoIssue' AND er.overallRating IS NOT null AND fr.review_status = 2 ";

            if ($json['student_aptitude'] == 0)
            $having_query .= " AND AVG(er.overallRating) <= 4";
            if ($json['student_aptitude'] == 1)
            $having_query .= " AND AVG(er.overallRating) > 4 AND AVG(er.overallRating) < 7";
            if ($json['student_aptitude'] == 2)
            $having_query .= " AND AVG(er.overallRating) >= 7 ";
        } */

        /*  if ($json['subject_name'] != "") {
             $filter_query .= " AND q.subjectId IN (".$json['subject_name'].")";
         } */

        if ($userType == 'college') {
            $college_query = mysqli_query($databaseConnection, "select u1.* from users u1 where u1.id =" . $json['userId'] . " ");
            $college_result = mysqli_fetch_array($college_query, MYSQLI_ASSOC);
            $filter_query .= " and pd.college in (" . $college_result['college_id'] . ")";
            $collegeId = $college_result['college_id'];
            $rawData .= " inner join raw_data rd on rd.email_id = u.emailId ";
            /* if ($json['isTieUpStatus'] == 'Y') {
                $filter_query .= " and rd.isPaid = 'Y'";
            } elseif ($json['isTieUpStatus'] == 'F') {
                $filter_query .= " and rd.isPaid = 'F'";
            }elseif($json['isTieUpStatus'] == 'N') {
                $filter_query .= " and rd.isPaid = 'N'";
            }else{
                $filter_query .= " and rd.isPaid in('Y','F')";
            } */
        }
        if ($userType == 'mentor') {
            $filter_query .= " and pd.assignMentorId in (" . $json['userId'] . ")";
        }
        if ($userType == 'student') {
            $student_query = mysqli_query($databaseConnection, "select p.*, u.firstName as name from professionaldetails p inner join users u on u.id = p.candidateId where p.candidateId =" . $json['userId'] . " order by id limit 1");
            $student = mysqli_fetch_array($student_query, MYSQLI_ASSOC);
            $filter_query .= " and u.id=" . $userId;
            $collegeId = $student['college'];
            $specialization = $student['specialization'];
            $year = $student['year'];
            $name = $student['name'];
        }


        if ($json['observationId'] != '') {
            $skillQuery .= " left outer join feedback_request fr on fr.candidateId  = u.id left outer join expert_review er on er.candidateId = u.id left outer join  expert_review_observation_details erod on erod.expertReviewId = er.id left outer join observation_area oa on oa.id = erod.observationAreaId ";

            $skill_filter .= " and oa.key_skill != 0  and oa.mandatory = 0 and er.review_type='question' and er.overallRating != 'videoIssue' and erod.observationValueId is null  and  fr.id in (select max(id) from feedback_request where review_status = 2 and candidateId = u.id)  and erod.observationAreaId = '" . $json['observationId'] . "'  ";
        }

        // if($json['salesLead'] !=''){
        //     $filter_query .= " and pd.leadStatus in (".$json['salesLead'].")";
        // } 

        /*  if ($json['sMeetingStatus'] != "") {
             if ($json['sMeetingStatus'] == '0') {
                 $filter_query .= " and DATEDIFF(pd.s_nextcontact_date,CURDATE()) = 0 ";
             } else if ($json['sMeetingStatus'] == '-1') {
                 $filter_query .= " and DATEDIFF(pd.s_nextcontact_date,CURDATE()) < 0 ";
             } else if ($json['sMeetingStatus'] == '1') {
                 $filter_query .= " and DATEDIFF(pd.s_nextcontact_date,CURDATE()) > 0 ";
             }
         } */

        $data = "select temp.*, CASE WHEN m.interviewSessionId is not null THEN max(m.interviewSessionId) ELSE 'Not Taken' END  as lastInterviewDate, count(distinct m.interviewSessionId) as interviewsTaken,COUNT( Distinct (CASE WHEN fr.review_status = 2 THEN fr.id ELSE NULL END)) as numOfFeedbackDelivered, Count(Distinct (CASE WHEN fr.review_status = 1 OR fr.review_status = 0 OR fr.review_status = -2 OR fr.review_status = -3 THEN fr.id ELSE NULL END)) as numOfFeedbackPending,CASE WHEN i.name is not NULL THEN group_concat(DISTINCT i.name order by i.name SEPARATOR ', ') ElSE 'None'  END AS AttendedInterview ,CASE WHEN fv.favourite_subject is not null THEN group_concat(DISTINCT fv.favourite_subject order by fv.favourite_subject  SEPARATOR ', ') ELSE 'None' END  AS AreaOfInterview,CASE WHEN p.name is not NULL THEN group_concat(DISTINCT p.name order by p.name  SEPARATOR ', ')  ELSE 'None' END AS ProductName from (select u.id,u.createdOn as signUpDate, u.firstName as name, u.emailId, u.mobileNumber, st.stream as specialization,pd.webinarTopic as WebinarTopic,pd.contact_Date as MentoringDate,pd.year, pd.college as cl_id, pd.communicationSkillRate, pd.cgpa, pd.languages,pd.fav_subjects, pd.fav_programming_skill, pd.asp_companies, CASE WHEN pd.college='188' THEN CONCAT(cl.collegeName,'(',pd.otherCollege,')') ELSE cl.collegeName  END AS college, pd.specialization as str_id,CASE WHEN ces.sectorId is not null then (SELECT name as sectorName FROM sector where id = ces.sectorId) else null end as sectorName,CASE WHEN ces.empstatus is not null then ces.empstatus else 'Not Active' end as emp_status from users u left outer join professionaldetails pd on u.id = pd.candidateId left outer join stream st on pd.specialization=st.id left outer join colleges cl on cl.id=pd.college LEFT OUTER JOIN candidateEmp_status ces ON ces.candidateId = u.id  " . $skillQuery . $rawData . "  left outer join webinar_registration_details wrd on wrd.candidateId=u.id  where u.deleted_at is NULL " . $filter_query . $led_filter_query . $skill_filter . $group_query . $having_query . $order_query . " ) as temp left outer join mergedVideos m on m.candidateId = temp.id and m.interviewSessionId is not null  left outer join feedback_request fr on fr.interviewSessionId = m.interviewSessionId left outer join interview i on i.id=m.interviewId left outer join product p on i.productId=p.id left outer join favourite_subject fv on i.subject_id = fv.id " . $interview_query . "  GROUP by temp.id " . $having_query2 . " order by interviewsTaken desc";

        $query = mysqli_query($databaseConnection, $data . $limit_query);


        $countData = "select temp.id, CASE WHEN m.interviewSessionId is not null THEN max(m.interviewSessionId) ELSE 'Not Taken' END  as lastInterviewDate, count(distinct m.interviewSessionId) as interviewsTaken,COUNT( Distinct (CASE WHEN fr.review_status = 2 THEN fr.id ELSE NULL END)) as numOfFeedbackDelivered, Count(Distinct (CASE WHEN fr.review_status = 1 OR fr.review_status = 0 OR fr.review_status = -2 OR fr.review_status = -3 THEN fr.id ELSE NULL END)) as numOfFeedbackPending from (select u.id,u.createdOn as signUpDate from users u left outer join professionaldetails pd on u.id = pd.candidateId left outer join stream st on pd.specialization=st.id left outer join colleges cl on cl.id=pd.college LEFT OUTER JOIN candidateEmp_status ces ON ces.candidateId = u.id left outer join " . $skillQuery . $rawData . "  left outer join webinar_registration_details wrd on wrd.candidateId=u.id  where u.deleted_at is NULL " . $filter_query . $led_filter_query . $skill_filter . $group_query . $having_query . $order_query . " ) as temp left outer join mergedVideos m on m.candidateId = temp.id and m.interviewSessionId is not null  left outer join feedback_request fr on fr.interviewSessionId = m.interviewSessionId  left outer join interview i on i.id=m.interviewId left outer join product p on i.productId=p.id left outer join favourite_subject fv on i.subject_id = fv.id " . $interview_query . "  GROUP by temp.id " . $having_query2 . " order by temp.signUpDate desc";


        if (mysqli_num_rows($query) > 0) {
            $count_rows = mysqli_query($databaseConnection, $data);
            $total_data = mysqli_num_rows($count_rows);
            //$values = mysqli_fetch_all($query, MYSQLI_ASSOC);
            while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
                if ($row['interviewsTaken'] >= 1) {
                    $row['overallRatings'] = getOverallRatingsForAllInterviews($databaseConnection, $row['id']);
                } else {
                    $row['overallRatings'] = NULL;
                }

                $MentorLed = mysqli_query($databaseConnection, "select candidateId,studentIssue,contactDate from mentor_observations  where candidateId = '" . $row['id'] . "'");
                if (mysqli_num_rows($MentorLed) >= 1) {
                    $mentorLedResult = mysqli_fetch_all($MentorLed, MYSQLI_ASSOC);
                    $row['mentorLedResult'] = $mentorLedResult;
                } else {
                    $row['mentorLedResult'] = [];
                }

                $progSkillQuery = mysqli_query($databaseConnection, "SELECT pd.fav_programming_skill, group_concat(fps.fav_prog_skill SEPARATOR ', ') AS fav_programming_skill_name FROM professionaldetails pd, fav_prog_skill fps WHERE FIND_IN_SET(fps.id, pd.fav_programming_skill) and candidateId = '" . $row['id'] . "'");
                $progSkillResult = mysqli_fetch_array($progSkillQuery, MYSQLI_ASSOC);
                $row['fav_programming_skill_name'] = $progSkillResult['fav_programming_skill_name'];

                $favSubjectsQuery = mysqli_query($databaseConnection, "SELECT pd.fav_subjects, group_concat(fs.favourite_subject SEPARATOR ', ') AS fav_subjects_name FROM professionaldetails pd, favourite_subject fs WHERE FIND_IN_SET(fs.id, pd.fav_subjects) and candidateId = '" . $row['id'] . "'");
                $favSubjectsResult = mysqli_fetch_array($favSubjectsQuery, MYSQLI_ASSOC);
                $row['fav_subjects_name'] = $favSubjectsResult['fav_subjects_name'];

                $aspCompaniesQuery = mysqli_query($databaseConnection, "SELECT pd.asp_companies, group_concat(ac.name SEPARATOR ', ') AS asp_companies_name FROM professionaldetails pd, aspiration_company ac WHERE FIND_IN_SET(ac.id, pd.asp_companies) and candidateId = '" . $row['id'] . "'");
                $aspCompaniesResult = mysqli_fetch_array($aspCompaniesQuery, MYSQLI_ASSOC);
                $row['asp_companies_name'] = $aspCompaniesResult['asp_companies_name'];

                /*$favDomainQuery = mysqli_query($databaseConnection, "SELECT pd.fav_domain, group_concat(fd.name SEPARATOR ', ') AS fav_domain_name FROM professionaldetails pd, favourite_domain fd WHERE FIND_IN_SET(fd.id, pd.fav_domain) and candidateId = '".$row['id']."'");
                $favDomainResult = mysqli_fetch_array($favDomainQuery, MYSQLI_ASSOC);
                $row['fav_domain_name'] = $favDomainResult['fav_domain_name'];*/

                $languageQuery = mysqli_query($databaseConnection, "SELECT pd.languages, group_concat(l.name SEPARATOR ', ') AS languagesKnown FROM professionaldetails pd, language l WHERE FIND_IN_SET(l.id, pd.languages) and candidateId = '" . $row['id'] . "'");
                $languageResult = mysqli_fetch_array($languageQuery, MYSQLI_ASSOC);
                $row['languagesKnown'] = $languageResult['languagesKnown'];

                $stats = mysqli_query($databaseConnection, "SELECT round(sum(TIME_TO_SEC(temp.duration))/60)  as duration from (SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(m.totalTime)) + SUM(TIME_TO_SEC(vwd.prwatchDuration)) + SUM(TIME_TO_SEC(vwd.psWatchDuration)) + SUM(TIME_TO_SEC(vwd.gvWatchDuration))) as duration  FROM `mergedVideos` m inner join video_watched_details vwd on vwd.mergeId = m.mergeId WHERE m.candidateId = '" . $row['id'] . "' group by m.`interviewSessionId`) as temp;");
                $row['durationOfPractice'] = mysqli_fetch_assoc($stats);


                // if($json['emp_status'] == "" && $json['sectorId'] == "") {
                //     $emp_status = mysqli_query($databaseConnection, "SELECT t.*,GROUP_CONCAT(DISTINCT ifs.value) as `value`,GROUP_CONCAT(s.name) as s_name FROM (SELECT nfr.interviewId,AVG(nfr.skillScore) as score,i.name,i.sector_id,nfr.feedback_request_id FROM `newFeedbackReport` nfr LEFT OUTER JOIN interview i ON i.id = nfr.interviewId WHERE i.productId = 1 AND nfr.candidateId = '" . $row['id'] . "' GROUP BY nfr.feedback_request_id) as t JOIN ier_for_sector ifs ON FIND_IN_SET(ifs.sector_id,t.sector_id) AND ifs.score = ROUND(t.score) JOIN sector s ON s.id = ifs.sector_id GROUP BY t.feedback_request_id;");
                //     if (mysqli_num_rows($emp_status)>0) {
                //         $row['emp_status'] = mysqli_fetch_all($emp_status, MYSQLI_ASSOC)[0]['value'];
                //     }
                //     else {
                //         $row['emp_status'] = 'Not Active';
                //     }
                // }
                $attempted = mysqli_query($databaseConnection, "SELECT COUNT(DISTINCT mv.interviewId) as attempted FROM mergedVideos mv WHERE mv.candidateId = " . $row['id'] . ";");
                if (mysqli_num_rows($attempted) > 0) {
                    $row['uniAttempted'] = mysqli_fetch_all($attempted, MYSQLI_ASSOC)[0]['attempted'];
                } else {
                    $row['uniAttempted'] = 0;
                }

                $user_subscription = getSubsciptionDetails($databaseConnection, $row['id']);

                $amount = isset($user_subscription['amount']) ? $user_subscription['amount'] : 0;

                /* Change by Narayan If amount is zero means Free Trial */
                if ($amount != '0') {
                    $row['totalAllowedInterview'] = $user_subscription['behaviouralInterviewAllowed'] + $user_subscription['codingInterviewAllowed'] + $user_subscription['communicationInterviewAllowed'] + $user_subscription['mockInterviewAllowed'] + $user_subscription['problemsolvingInterviewAllowed'];

                } else {
                    $row['totalAllowedInterview'] = isset($user_subscription['freeTrialAllowed']) ? $user_subscription['freeTrialAllowed'] : 2;

                }


                array_push($values, $row);
            }
            $to_encode = array(
                'result' => "success",
                'status' => 1,
                'college' => $collegeId,
                'specialization' => $specialization,
                'year' => $year,
                'name' => $name,
                'data' => $values,
                'count' => $total_data,
                'query' => $data,
                'datalimit' => $data . $limit_query,

            );
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "in Error while retrieving Student information.",
                'qry' => $data . $limit_query
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving Student information"
        );
    }
    echo json_encode($to_encode);
}
// node-api
// this method is added by arun on 16/9/22 for getting details for connecttomentor dashboard
elseif (isset($_GET['getConnecttomentorData'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $filter_query = " ";
        $having_query = " ";
        $filter = " ";
        $rawData = " ";
        $limit = $json['limit'];
        $start = ($json['page'] - 1) * $limit;
        $limit_query = $limit == 0 ? "" : " limit " . $start . "," . $limit;
        $values = array();
        // $LeadStatus = '';
        $interest = '';
        // $subjectId = '';
        $tpmentorId = '';
        // $requestedDate = '';
        if ($userType == 'tpmentor') {
            $filter_query .= " and pd.assignMentorId in (" . $json['userId'] . ")";
            $tpmentorId .= " and pd.assignMentorId in (" . $json['userId'] . ")";
        }

        if ($json['candidate_search'] != "") {
            if (preg_match('/^[0-9]+$/', $json['candidate_search'])) {
                $filter_query .= " and u.id in(" . $json['candidate_search'] . ")";
                // }else if(filter_var($json['candidate_search'], FILTER_VALIDATE_EMAIL)){

            } else {
                $filter_query .= " and u.firstName like '%" . $json['candidate_search'] . "%'";
            }

        }


        if (!empty($json['signupfrom_date']) && empty($json['signupto_date'])) {
            $filter_query .= " AND DATE(FROM_UNIXTIME(u.createdOn / 1000)) >= '" . $json['signupfrom_date'] . "'";
        }

        if (empty($json['signupfrom_date']) && !empty($json['signupto_date'])) {
            $filter_query .= " AND DATE(FROM_UNIXTIME(u.createdOn / 1000)) <= '" . $json['signupto_date'] . "'";
        }

        if (!empty($json['signupfrom_date']) && !empty($json['signupto_date'])) {
            $filter_query .= " AND DATE(FROM_UNIXTIME(u.createdOn / 1000)) BETWEEN '" . $json['signupfrom_date'] . "' AND '" . $json['signupto_date'] . "'";
        }


        // $leadStatusSQL = "";

        // if (!empty($json['leadStatus']) && is_array($json['leadStatus'])) {

        //     $leadIds = implode(",", $json['leadStatus']);

        //     $leadStatusSQL = "
        //         AND EXISTS (
        //             SELECT 1
        //             FROM sales_observations sv_f
        //             WHERE
        //                 sv_f.candidateId = u.id
        //                 AND sv_f.leadStatus IN ($leadIds)
        //         )
        //     ";
        // }


        // if ($json['paymentStatus'] != "") {
        //     // todo
        //     if ($json['paymentStatus'] == 'paid') {
        //         $having_query .= " and paymentstatus in('Paid') ";
        //     } else if ($json['paymentStatus'] == 'checkout') {
        //         $having_query .= " and paymentstatus ='Checkout' ";
        //     } else if ($json['paymentStatus'] == 'download') {
        //         $having_query .= " and paymentstatus ='Download' ";
        //     } else if ($json['paymentStatus'] == 'viewed') {
        //         $having_query .= " and paymentstatus ='Viewed' ";
        //     } else if ($json['paymentStatus'] == 'notViewed') {
        //         $having_query .= " and paymentstatus ='Not Viewed' ";
        //     }
        // }

        if (!empty($json['interviewName']) && is_array($json['interviewName'])) {

            $preIds = implode(",", $json['interviewName']);
            $filter_query .= " and i.preInterviewId in ($preIds)";
        

            // $filter_query .= "
            //     AND (
            //         EXISTS (
            //             SELECT 1
            //             FROM feedback_request fbr_f
            //             INNER JOIN interview i_f ON i_f.id = fbr_f.interviewId
            //             WHERE
            //                 fbr_f.candidateId = u.id
            //                 AND i_f.preInterviewId IN ($preIds)
            //         )
            //         OR
            //         EXISTS (
            //             SELECT 1
            //             FROM candidateInterviewMapping cim_f
            //             INNER JOIN preInterview pi_f ON pi_f.id = cim_f.preInterviewId
            //             WHERE
            //                 cim_f.emailId = u.emailId
            //                 AND cim_f.preInterviewId IN ($preIds)
            //                 AND pi_f.interviewType = 'Practice'
            //         )
            //     )
            // ";
        }

        // Force Practice interview type only - no job data
      //  $serviceTypeSQL = " AND (latest_it.interviewType = 'Practice' OR latest_it.interviewType IS NULL)";

        // Add Lead Stage filter
        $leadStageSQL = "";
        if (!empty($json['leadStage']) && is_array($json['leadStage'])) {
            $stageConditions = [];
            foreach ($json['leadStage'] as $stage) {
                $stageConditions[] = (int)$stage;
            }
            if (!empty($stageConditions)) {
                $leadStageSQL = " AND lead_stage IN (" . implode(",", $stageConditions) . ")";
            }
        }

        $data = "SELECT
                u.id,
                u.firstName AS name,
                u.emailId,
                u.mobileNumber,
                u.createdOn AS signUpDate,
                pd.workExperience,
                pd.resume,
                sv.leadStatus,
                sl.statusValue AS leadStatusValue,
                last_active.lastActiveDate,

                CASE
					WHEN stage4.userId IS NOT NULL THEN 4
					WHEN stage3.userId IS NOT NULL THEN 3
					WHEN stage2.userId IS NOT NULL THEN 2
					ELSE 1
				END AS lead_stage,

                CASE
                    WHEN last_active.lastActiveDate IS NOT NULL THEN CONCAT(DATEDIFF(NOW(), last_active.lastActiveDate), ' Days')
                    ELSE 'N/A'
                END AS leadAge

            FROM users u
            LEFT JOIN professionaldetails pd ON u.id = pd.candidateId
            LEFT JOIN sales_observations sv ON sv.candidateId = pd.candidateId
            LEFT JOIN salesLeadActionStatus sl ON sl.id = sv.leadStatus

            LEFT JOIN (
                SELECT
                    uip.userId,
                    MAX(cl.logTime) AS lastActiveDate
                FROM (
                    SELECT userId, ip
                    FROM candidate_log
                    WHERE userId <> 0
                    AND ip IS NOT NULL
                    GROUP BY userId, ip
                ) uip
                JOIN candidate_log cl
                ON cl.ip = uip.ip
                GROUP BY uip.userId
            ) last_active ON last_active.userId = u.id

            LEFT JOIN (
				SELECT DISTINCT
					i.createdBy AS userId
				FROM detail_feedback_request dfr
				INNER JOIN interview i ON i.id = dfr.interviewId
				INNER JOIN preInterview pi ON pi.id = i.preInterviewId
				WHERE pi.interviewType = 'Practice'
				  AND dfr.viewedStatus IN ('Viewed', 'download')
			) stage4 ON stage4.userId = u.id
            LEFT JOIN (
                SELECT DISTINCT createdBy as userId FROM interview i
                INNER JOIN preInterview pi ON pi.id = i.preInterviewId
                WHERE pi.interviewType = 'Practice'
            ) stage3 ON stage3.userId = u.id
            LEFT JOIN (
                SELECT DISTINCT userId
                FROM candidate_log
                WHERE pageName = 'home'
                AND action = 'FREE_TRIAL_START'
            ) stage2 ON stage2.userId = u.id
            LEFT JOIN feedback_request fbr ON fbr.candidateId = u.id
            LEFT JOIN interview i ON i.id = fbr.interviewId
            LEFT JOIN preInterview pi ON pi.id = i.preInterviewId

            WHERE 1=1
            " . $filter_query . "

            GROUP BY u.id
            HAVING 1=1
            " . $having_query . "
            " . $leadStageSQL . "

            ORDER BY lead_stage DESC, lastActiveDate DESC
            " . $limit_query;

        $query = mysqli_query($databaseConnection, $data );

        if ($query === false) {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "Database query failed",
                'mysqlError' => mysqli_error($databaseConnection),
                'qry' => $data
            );
        } else {
            $values = array();
            $candidateIds = array();
            while ($row = mysqli_fetch_assoc($query)) {
                $values[] = $row;
                $candidateIds[] = $row['id'];
            }
            
            // If no results, return early
            if (empty($candidateIds)) {
                $to_encode = array(
                    'result' => "success",
                    'status' => 1,
                    'data' => array(),
                    'count' => 0
                );
                echo json_encode($to_encode);
                exit;
            }
    
            $candidateIdsStr = implode(',', $candidateIds);

            $interview_batch_sql = "
                SELECT 
                    fr.candidateId,
                    fr.id as fr_id,
                    fr.interviewId,
                    i.name as interviewName,
                    fr.review_status,
                    CASE
                        WHEN fr.review_status=2 THEN 'Completed'
                        WHEN fr.review_status=-4 THEN 'Rejected'
                        WHEN fr.review_status=1 THEN 'In Progress'
                        WHEN fr.review_status=0 THEN 'Assessment Open'
                        WHEN fr.review_status=-2 THEN 'Waiting For Internal review'
                    END as status,
                    CASE
                    WHEN r.relevance = 1 THEN 'Very relevant'
                    WHEN r.relevance = 2 THEN 'Somewhat relevant'
                    WHEN r.relevance = 3 THEN 'Not relevant'
                    ELSE NULL
                    END as relevance,
                    r.feedbackReason
                FROM feedback_request fr
                INNER JOIN interview i ON i.id=fr.interviewId
                LEFT JOIN preInterview pi ON pi.id=i.preInterviewId
                LEFT JOIN ratings r ON r.interviewId = fr.interviewId AND r.candidateId = fr.candidateId
                WHERE fr.candidateId IN ($candidateIdsStr)
                AND pi.interviewType = 'Practice'
                ORDER BY fr.requestDate DESC
            ";
            
            $interview_batch_result = mysqli_query($databaseConnection, $interview_batch_sql);
            
            $interviewsMap = array();
            while ($interview_row = mysqli_fetch_assoc($interview_batch_result)) {
                $cid = $interview_row['candidateId'];
                if (!isset($interviewsMap[$cid])) {
                    $interviewsMap[$cid] = array();
                }
                $interviewsMap[$cid][] = $interview_row;
            }

            $connecttomentor_batch_sql = "
                SELECT 
                    i.createdBy as candidateId,
                    i.id as interviewId,
                    dfr.interviewSessionId,
                    CASE 
                        WHEN pay.status = 'PAID' THEN 'Paid'
                        WHEN pay.status = 'CHECKOUT' THEN 'Checkout'
                        WHEN dfr.viewedStatus = 'pay' THEN 'Pay to Unlock'
                        WHEN dfr.viewedStatus = 'download' THEN 'Download'
                        WHEN dfr.viewedStatus = 'Viewed' THEN 'Viewed'
                        ELSE 'Not Viewed'
                    END AS paymentstatus,
                    i.name as interviewName
                FROM interview i
                INNER JOIN feedback_request fbr ON fbr.interviewId = i.id
                LEFT JOIN preInterview pi ON pi.id = i.preInterviewId
                LEFT JOIN detail_feedback_request dfr ON dfr.interviewId = i.id
                LEFT JOIN payment_transaction pay ON pay.interview_id = i.id
                WHERE fbr.review_status = '2'
                    AND i.createdBy IN ($candidateIdsStr)
                    AND pi.interviewType = 'Practice'
                ORDER BY i.id DESC
            ";
            
            $connecttomentor_batch_result = mysqli_query($databaseConnection, $connecttomentor_batch_sql);
   
            $connectMentorMap = array();
            while ($mentor_row = mysqli_fetch_assoc($connecttomentor_batch_result)) {
                $cid = $mentor_row['candidateId'];
                if (!isset($connectMentorMap[$cid])) {
                    $connectMentorMap[$cid] = array();
                }
                $connectMentorMap[$cid][] = $mentor_row;
            }

            foreach ($values as &$row) {
                $cid = $row['id'];
                $row['attendedInterviews'] = isset($interviewsMap[$cid]) ? $interviewsMap[$cid] : array();
                $row['connect_mentor_data'] = isset($connectMentorMap[$cid]) ? $connectMentorMap[$cid] : array();
            }
            unset($row); // Break reference

            // COUNT QUERY
            $count_sql = "SELECT 
                COUNT(id) AS total
                FROM users";

            $count_rows = mysqli_query($databaseConnection, $count_sql);
            $count_result = $count_rows ? mysqli_fetch_assoc($count_rows) : null;
            $total_data = $count_result ? (int)$count_result['total'] : 0;

            $to_encode = array(
                'result' => "success",
                'status' => 1,
                'data' => $values,
                'count' => $total_data
            );
        }

    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving Student information"
        );
    }
    echo json_encode($to_encode);
}
// node-api
elseif (isset($_GET['updateLeadStatus'])) {
    /* this method is used for adding and updating mentor leadstatus for a candidate */
    $to_encode = array(
        'result' => "error",
        'message' => "Error while changing lead status.",
        'status' => 0,
    );
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $usertype = $json['userType'];
        $candidateQuery = mysqli_query($databaseConnection, "select emailId as candidateEmail,firstName as candidateName from users where id = '" . $json['candidateId'] . "';");
        if (mysqli_num_rows($candidateQuery) > 0) {
            $candidateDetails = mysqli_fetch_all($candidateQuery, MYSQLI_ASSOC);

            $soQuery = mysqli_query($databaseConnection, "select * from sales_observations where candidateId = '" . $json['candidateId'] . "';");

            if (mysqli_num_rows($soQuery) > 0) {
                $updateSql = "UPDATE `sales_observations` SET `contactDate`=CURDATE(), `nextFollowupDate`= NULL,`leadStatus` = '" . $json['leadStatus'] . "' WHERE candidateId = '" . $json['candidateId'] . "';";
                $update = mysqli_query($databaseConnection, $updateSql);

                $to_encode = array(
                    'result' => "Success",
                    'message' => "lead status updated.",
                    'status' => 1

                );

            } else {
                $sql = "INSERT INTO `sales_observations`( `candidateId`, `contactDate`, `leadStatus`, `approxTime`) VALUE('" . $json['candidateId'] . "',CURDATE(), '" . $json['leadStatus'] . "' ,'0');";
                $insert = mysqli_query($databaseConnection, $sql);

                $to_encode = array(
                    'result' => "Success",
                    'message' => "lead status inserted.",
                    'status' => 1

                );
            }

        } else {
            $to_encode = array(
                'result' => "error",
                'errorCode' => "User Id is incorrect.",
                'status' => -1
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "Adding Observation failed.",
            'status' => -1
        );
    }
    echo json_encode($to_encode);
}
elseif (isset($_GET['getCurrentStudentActivityData'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $filter_query = "";

        $data = '';
        $query = "select 
            u.id,
            m.interviewSessionId as sessionId, i.id as intId,
            i.name as interview_name ,
            cat.name as category,
            if(fbr.review_status is NULL,'-1', fbr.review_status) as fbr_status ,
            COUNT(m.questionId) as QA,  
            CASE WHEN i.categoryType = 9 THEN  (SELECT COUNT( CASE WHEN iqt.attemptStatus is not NULL THEN iqt.questionId ELSE NULL END) FROM interview_questions_transection iqt inner join questions qs on qs.id = iqt.questionId WHERE iqt.interviewId=m.interviewId and qs.deleted_at is null and iqt.deleted_at is null and iqt.deleted_at is null) ELSE      (SELECT COUNT(iqt.questionId) FROM interview_questions_transection iqt inner join questions qs on qs.id = iqt.questionId WHERE iqt.interviewId=m.interviewId and qs.deleted_at is null and iqt.deleted_at is null) -1 END  as QT ,
            'merged' as activity_col
            from interview i, category as cat, mergedVideos m left outer join feedback_request fbr on fbr.interviewSessionId=m.interviewSessionId inner join users u on u.id=m.candidateId
            where m.interviewId=i.id and cat.id=i.categoryType and u.active='Y' and u.deleted_at is null and u.id=" . $json['currentStudentId'] . "
            group by m.interviewSessionId
            UNION
            select 
            u.id,
            pt.watchingTime as sessionId, null as intId,
            pr.name as interview_name ,
            'Peer Response' as category,
            5 as fbr_status ,
            0 as QA,  
            0 as QT,
            pt.isWatchedFull as activity_col
            from peer_transection pt,peer_response pr,users u
            where u.id=pt.userId and pt.peerId=pr.id and u.active='Y' and u.deleted_at is null and u.id=" . $json['currentStudentId'];


        $data = $query . " order by sessionId desc";
        if ($data != '') {
            $query = mysqli_query($databaseConnection, $data);
            if (mysqli_num_rows($query) > 0) {
                $total_data['data'] = mysqli_fetch_all($query, MYSQLI_ASSOC);
                $total_data['count'] = mysqli_num_rows($query);
                $to_encode = $total_data;
            } else {
                $to_encode = array(
                    'result' => "error",
                    'status' => 0,
                    'message' => "no data avaialble",
                    'data' => $data
                );
            }
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "in Error You are not having access this page."
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving Student information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getStudentActivityFilters'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $collegeQuery = '';

        if ($userType == 'college') {
            $collegeQuery = "select id,collegeName as college from colleges where FIND_IN_SET(id, (select college_id from users where id = '" . $userId . "')) order by id=188,collegeName";
        } elseif ($userType == 'mentor') {
            $collegeQuery = "select id,collegeName as college from colleges where id in (select college from professionaldetails where assignMentorId = '" . $userId . "') order by id=188,collegeName";
        } elseif ($userType == 'student') {
            $collegeQuery = "select id,collegeName as college from colleges where id in (select college from professionaldetails where candidateId = '" . $userId . "') order by id=188,collegeName";
        } else {
            $collegeQuery = "select id,collegeName as college from colleges order by id=188,collegeName";
        }
        $college_query = mysqli_query($databaseConnection, $collegeQuery);

        $stream_query = mysqli_query($databaseConnection, "select * from stream where isActive = 'Y' order by id=11,stream");

        $interview_query = "select ac.name,ac.id from aspiration_company ac inner join scps_transaction scps on scps.company=ac.id group by scps.company";
        $interview_queryResult = mysqli_query($databaseConnection, $interview_query);

        $values['specialization'] = mysqli_fetch_all($stream_query, MYSQLI_ASSOC);
        $values['college'] = mysqli_fetch_all($college_query, MYSQLI_ASSOC);
        $values['interviewname'] = mysqli_fetch_all($interview_queryResult, MYSQLI_ASSOC);
        $to_encode = $values;
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving Student information"
        );
    }
    echo json_encode($to_encode);
}
elseif (isset($_GET['getHomepageFilters'])) {

    $stream_query = mysqli_query($databaseConnection, "select * from stream where isActive = 'Y' order by id=11,stream");
    $values['specialization'] = mysqli_fetch_all($stream_query, MYSQLI_ASSOC);


    $college_query = mysqli_query($databaseConnection, "select id,collegeName as college from colleges order by id=188,collegeName");
    $values['college'] = mysqli_fetch_all($college_query, MYSQLI_ASSOC);

    $connecttomentor = mysqli_query($databaseConnection, "select * from areasofinterest WHERE id not in (2,5,6,8,12,13) and active='Y' order by id ASC");
    $values['connecttomentor'] = mysqli_fetch_all($connecttomentor, MYSQLI_ASSOC);

    $role = "SELECT * FROM relavant_role WHERE active = 'Y' ORDER BY id DESC";
    $roleResult = mysqli_query($databaseConnection, $role);
    $values['roleNames'] = mysqli_fetch_all($roleResult, MYSQLI_ASSOC);

    $competencySubject = "SELECT DISTINCT skill.id, role.id as roleId, skill.favourite_subject AS name, CASE WHEN role.id is null then 'Other' ELSE role.name END as role
    FROM favourite_subject skill
    LEFT JOIN role_subject map ON map.subjectId = skill.id
    LEFT JOIN relavant_role role ON role.id = map.roleId
    WHERE skill.subjectType = 'competency' AND skill.active = 'Y'
    order by skill.id";

    $competencySubjectResult = mysqli_query($databaseConnection, $competencySubject);
    $values['competencySubject'] = mysqli_fetch_all($competencySubjectResult, MYSQLI_ASSOC);

    echo json_encode($values);
}
elseif (isset($_GET['getDashboardFilters'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    $userId = $json['userId'] != '' ? $json['userId'] : -1;


    // user's distinct subjects
    $userSubjectQuery = "SELECT DISTINCT st.subject
        FROM scps_transaction st
        LEFT JOIN candidateInterviewMapping cim ON cim.preInterviewId = st.preInterviewId
        LEFT JOIN users u ON u.emailId = cim.emailId
        WHERE u.id = $userId
          AND st.subject IS NOT NULL
          AND st.subject <> 0;   
    ";

    $userSubjectResult = mysqli_query($databaseConnection, $userSubjectQuery);
    $userSubjects = [];

    if ($userSubjectResult) {
        while ($row = mysqli_fetch_assoc($userSubjectResult)) {
            $userSubjects[] = intval($row['subject']);
        }
    }

   
    if (count($userSubjects) === 0) {

        //fallback to 50 subjects
        $fallbackQuery = "SELECT subject
            FROM scps_transaction
            WHERE subject IS NOT NULL AND subject <> 0
            GROUP BY subject
            ORDER BY COUNT(*) DESC
            LIMIT 50;
        ";

        $fallbackResult = mysqli_query($databaseConnection, $fallbackQuery);

        if ($fallbackResult) {
            while ($row = mysqli_fetch_assoc($fallbackResult)) {
                $userSubjects[] = intval($row['subject']);
            }
        }
    }

    if (count($userSubjects) === 0) {
        $values['competencySubject'] = [];
        echo json_encode($values);
        return;
    }

    $subjectList = implode(',', $userSubjects);
    
    // Learn from peers
    $competencySubject = "SELECT 
            skill.id, 
            role.id AS roleId, 
            skill.favourite_subject AS name, 
            COALESCE(role.name, 'Other') AS role,
            cnt.count AS count
        FROM favourite_subject skill
        LEFT JOIN role_subject map ON map.subjectId = skill.id
        LEFT JOIN relavant_role role ON role.id = map.roleId
        LEFT JOIN (
			SELECT 
				st2.subject,
				COUNT(DISTINCT isc2.id) AS count
			FROM scps_transaction st2
			LEFT JOIN interviewSchedule isc2
				ON isc2.preInterviewId = st2.preInterviewId
				AND isc2.interviewId IS NOT NULL
			GROUP BY st2.subject
		) cnt 
			ON cnt.subject = skill.id
        WHERE skill.subjectType = 'competency'
        AND role.active = 'Y'
        AND skill.id IN ($subjectList) 
        ORDER BY skill.id;";


    $competencySubjectResult = mysqli_query($databaseConnection, $competencySubject);
    if (!$competencySubjectResult) {
        $values['competencySubject'] = [];
        $values['error'] = mysqli_error($databaseConnection);
        echo json_encode($values);
        return;
    }
    $values['competencySubject'] = mysqli_fetch_all($competencySubjectResult, MYSQLI_ASSOC);

    echo json_encode($values);
}
elseif (isset($_GET['getUsersFilters'])) {

    $company_query = mysqli_query($databaseConnection, "select id,name as company from aspiration_company order by name");
    $values['company'] = mysqli_fetch_all($company_query, MYSQLI_ASSOC);


    $location_query = mysqli_query($databaseConnection, "select id,cityName as location from locations order by cityName");
    $values['location'] = mysqli_fetch_all($location_query, MYSQLI_ASSOC);


    $subjectrole_query = mysqli_query($databaseConnection, "SELECT 
    fs.id AS id,
    fs.favourite_subject AS subject,
    GROUP_CONCAT(rr.id) AS roleId,
    GROUP_CONCAT(rr.name) AS role,
    fs.active AS active
    FROM 
        favourite_subject fs 
    left JOIN 
        role_subject rs ON rs.subjectId = fs.id 
    left JOIN 
        relavant_role rr ON rr.id = rs.roleId 
    GROUP BY
        fs.id, fs.favourite_subject;");
    $values['subjectrole'] = mysqli_fetch_all($subjectrole_query, MYSQLI_ASSOC);

    $role_query = mysqli_query($databaseConnection, "SELECT  id,name from relavant_role order by name ;");
    $values['role'] = mysqli_fetch_all($role_query, MYSQLI_ASSOC);

    echo json_encode($values);
} elseif (isset($_GET['getWebinarData'])) {
    /* this method is added for get all webinar details 16-oct-2021 */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    $values = array();
    if (isset($json)) {
        $candidateId = $json['userId'];
        $query = "select *,DATE_ADD(startAt,interval 2 hour) as endsAt ,CASE WHEN vimeoId is null  && TIMEDIFF(DATE_ADD(now(), interval 330 minute) , DATE_ADD(startAt,interval 2 hour))  < 0
         Then 'Upcoming' ELSE 'Past' END AS WebinarCategory  from webinar_details order by startAt desc";
        $queryResult = mysqli_query($databaseConnection, $query);
        if (mysqli_num_rows($queryResult) > 0) {
            while ($row = mysqli_fetch_array($queryResult, MYSQLI_ASSOC)) {
                $userStatus = mysqli_query($databaseConnection, "select attend,certificatePdf,candidateId  from webinar_registration_details  where webinarId = '" . $row['id'] . "' and candidateId='" . $candidateId . "' ");
                if (mysqli_num_rows($userStatus) > 0) {
                    $userWebinarResult = mysqli_fetch_assoc($userStatus);
                    $row['userWebinarStatus'] = $userWebinarResult['attend'];
                    $row['userCertificate'] = $userWebinarResult['certificatePdf'];
                    $row['candidateId'] = $userWebinarResult['candidateId'];
                } else {
                    $row['userWebinarStatus'] = '';
                    $row['userCertificate'] = '';
                    $row['candidateId'] = '';
                }

                array_push($values, $row);
            }
            $to_encode = array(
                'status' => 1,
                'result' => $values,
                'msg' => "success"
            );
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "NO RECORD FOUND",
                'errorCode' => "out Error while retrieving WEBINAR information"
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while retrieving WEBINAR information"
        );

    }
    echo json_encode($to_encode);

} elseif (isset($_GET['getRegisterFilters'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    $candidateId = $json['userId'] != '' ? $json['userId'] : -1;

    $role_query = mysqli_query($databaseConnection, "SELECT DISTINCT rr.id, rr.name AS role FROM relavant_role rr INNER JOIN role_subject rs ON rr.id = rs.roleId WHERE rr.active = 'Y' order by rr.id;");

    $values['role'] = mysqli_fetch_all($role_query, MYSQLI_ASSOC);


    $competencySkill_query = mysqli_query($databaseConnection, "SELECT DISTINCT skill.id, role.id as roleId, skill.favourite_subject AS name, CASE WHEN role.id is null then 'Other' ELSE role.name END as role
            FROM favourite_subject skill
            LEFT JOIN role_subject map ON map.subjectId = skill.id
            LEFT JOIN relavant_role role ON role.id = map.roleId
            WHERE skill.subjectType = 'competency' AND skill.active = 'Y'
            order by skill.id");

    $values['competencySkill'] = mysqli_fetch_all($competencySkill_query, MYSQLI_ASSOC);
    // commented for deploymemnt
    // $data2 = "select id,waitingList from candidateInterviewMapping where candidateId ='" . $candidateId . "' and waitingList ='Y';";
    // $query2 = mysqli_query($databaseConnection, $data2);
    // if (mysqli_num_rows($query2) >= 1) {
    //     $row2 = mysqli_fetch_assoc($query2);  
    //     $values['waitingList_updated'] = $row2['waitingList'];
    // }else{
    //     $values['waitingList_updated'] = 'N';
    // }


    $topics_sql = "select DISTINCT t.id as topicId, 
    t.name as topicName from questions q inner join topic t on t.id=q.topic_id where q.isActive = 'Y' and q.deleted_at is null group by q.topic_id order by q.subjectId; ";
    $topic_query = mysqli_query($databaseConnection, $topics_sql);

    $values['topics'] = mysqli_fetch_all($topic_query, MYSQLI_ASSOC);

    $data3 = "select id,firstname,emailId,mobileNumber from users where id ='" . $candidateId . "';";
    $query3 = mysqli_query($databaseConnection, $data3);
    // echo $data3;
    $values['userdetails'] = mysqli_fetch_all($query3, MYSQLI_ASSOC);

    echo json_encode($values);
} elseif (isset($_GET['getRegisterSubjects'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    if (!empty($json['roleId'])) {
        if (is_array($json['roleId'])) {
            $roleId = implode(',', $json['roleId']);
        } else {
            $roleId = $json['roleId'];
        }
    } else {
        $roleId = null;
    }


    // $sql = "SELECT DISTINCT subjectId, favourite_subject FROM role_subject  
    // LEFT JOIN favourite_subject ON subjectId = favourite_subject.id 
    // WHERE roleId IN (" . $roleId . ") ";
    $sql = "SELECT rs.subjectId, fs.favourite_subject FROM role_subject rs 
        LEFT JOIN favourite_subject fs ON rs.subjectId = fs.id 
        inner join questions q on q.subjectId= rs.subjectId
        WHERE rs.roleId IN (" . $roleId . ") 
        group by rs.subjectId; ";

    // Execute the query
    $subject_query = mysqli_query($databaseConnection, $sql);
    $values = array();
    if ($subject_query) {
        if (mysqli_num_rows($subject_query) > 0) {
            $values['subject'] = mysqli_fetch_all($subject_query, MYSQLI_ASSOC);
        } else {
            $to_encode = array(
                'result' => 'success',
                'status' => 0,
                'message' => 'no data found',
            );
        }
    }
    echo json_encode($values);
} elseif (isset($_GET['getRegisterTopics'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    if (!empty($json['subjectId'])) {
        if (is_array($json['subjectId'])) {
            $subjectId = implode(',', $json['subjectId']);
        } else {
            $subjectId = $json['subjectId'];
        }
    } else {
        $subjectId = null;
    }

    $query = "
            SELECT DISTINCT t.id AS id, t.name AS name
            FROM questions q
            JOIN topic t ON q.topic_id = t.id
            WHERE q.deleted_at IS NULL
            AND q.subjectId = '$subjectId'
            ORDER BY t.id ASC
        ";

    $topics_query = mysqli_query($databaseConnection, $query);

    // Check for query errors
    if (!$topics_query) {
        die("MySQL error: " . mysqli_error($databaseConnection));
    }

    $topics = [];

    while ($row = mysqli_fetch_assoc($topics_query)) {
        $topics[] = $row;
    }


    $to_encode = array(
        'result' => 'success',
        'status' => 0,
        'topics' => $topics,
    );


    echo json_encode($to_encode);
} elseif (isset($_GET['registerUserWebinar'])) {
    /* this method is added for user registration for webinar 16-oct-2021 By Anuj */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $webId = $json['webId'];
        $candidateId = $json['candidateId'];
        $checkQuery = "SELECT `webinarid`, `candidateid` FROM `webinar_registration_details` WHERE webinarid = '" . $webId . "' and candidateid = '" . $candidateId . "'";
        $checkResult = mysqli_query($databaseConnection, $checkQuery);
        if (mysqli_num_rows($checkResult) > 0) {
            $to_encode = 'User_already_registered';
        } else {
            $registerQuery = "INSERT INTO `webinar_registration_details`(`webinarid`, `candidateid`) VALUES ('" . $webId . "','" . $candidateId . "')";
            $registerResult = mysqli_query($databaseConnection, $registerQuery);
            if ($registerResult) {
                $to_encode = 'Registration_success';
            } else {
                $to_encode = 'error occured while registering';
            }
        }

    }
    echo json_encode($to_encode);
} elseif (isset($_GET['markAttendanceForWebinar'])) {
    /* this method is added for webinar attandence at 16-oct-2021 By Anuj  */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $webId = $json['webId'];
        $candidateId = $json['candidateId'];
        $Query = "UPDATE `webinar_registration_details` SET `attend`='Y' WHERE webinarId = '" . $webId . "' AND candidateId = '" . $candidateId . "'";
        $Result = mysqli_query($databaseConnection, $Query);
        if ($Result) {
            $to_encode = array(
                'result' => "Success",
                'message' => "User Attendance Updated",
                'status' => 1
            );
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "Error while Updating."
            );
        }

    } else {
        $to_encode = array(
            'result' => "error",
            'status' => -1,
            'errorCode' => "Data is not json format."
        );
    }
    echo json_encode($to_encode);
}
elseif (isset($_GET['getFeedbackDashboardData'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $filter_query = " ";
        $activity_filter_query = " ";
        $limit = $json['limit'];
        $start = ($json['page'] - 1) * $limit;
        $order_query = "";
        $limit_query = $limit == 0 ? "" : " limit " . $start . "," . $limit;
        $result = array();
        $having_query = " having 1 ";
        $rawData = " ";
        $subData = " ";
        if ($json['college'] != "")
            $filter_query .= " and pd.college in ('" . implode("', '", array_map("addSlashToString", $json['college'])) . "')";
        // $filter_query .= " and pd.college in (" . $json['college'] . ")";
        if ($json['stream'] != "")
            //$filter_query.=" and pd.specialization in ('".implode("', '", $json['stream'])."')";
            $filter_query .= " and pd.specialization in ('" . $json['stream'] . "')";
        if ($json['menu'] != "")
            $filter_query .= " and i.productId ='" . $json['menu'] . "'";
        if ($json['category'] != "")
            $filter_query .= " and i.categoryType = '" . $json['category'] . "'";
        if ($json['feedbackStatus'] != "") {
            if ($json['feedbackStatus'] == "-1") {
                $filter_query .= " and fbr.review_status is NULL";
            } else {
                $filter_query .= " and fbr.review_status ='" . $json['feedbackStatus'] . "'";
            }
        }
        if ($json['yop'] != "") {
            $filter_query .= " and pd.year in (" . $json['yop'] . ")";
        }
        // if ($json['interviewPriority'] != "") {
        //     $filter_query .= " and fbr.priority ='" . $json['interviewPriority'] . "'";
        // }
        if ($json['isTieUpStatus'] != "") {
            $rawData .= " inner join raw_data rd on rd.email_id = u.emailId ";

            if ($json['isTieUpStatus'] == 'Y') {
                $filter_query .= " and rd.isPaid = 'Y'";
            } elseif ($json['isTieUpStatus'] == 'F') {
                $filter_query .= " and rd.isPaid = 'F'";
            } else {
                $filter_query .= " and rd.isPaid = 'N'";
            }
        }
        if ($json['btwocPaid'] != "") {
            $subData .= " inner join subscription sb on sb.candidateId = u.id ";
            if ($json['btwocPaid'] == 'Y') {
                $filter_query .= " and  sb.amount !='0' and DATEDIFF(sb.endDate,CURDATE()) >=0 ";
            } else if ($json['btwocPaid'] == 'T') {
                $filter_query .= " and  sb.amount ='0' and DATEDIFF(sb.endDate,CURDATE()) >=0 ";
            } else {
                $filter_query .= " and  sb.amount ='0' and DATEDIFF(sb.endDate,CURDATE()) < 0 ";
            }
        }
        if ($json['candidate_name'] != "")
            $filter_query .= " and u.firstName like '%" . $json['candidate_name'] . "%'";
        if ($json['from_date'] != "" && $json['to_date'] == "")
            $filter_query .= " and fbr.interviewSessionId >= '" . strtotime($json['from_date']) . "'";
        if ($json['from_date'] == "" && $json['to_date'] != "")
            $filter_query .= " and fbr.interviewSessionId <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";
        if ($json['from_date'] != "" && $json['to_date'] != "")
            $filter_query .= " and fbr.interviewSessionId >= '" . strtotime($json['from_date']) . "' and fbr.interviewSessionId <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";

        // if ($json['dfrom_date'] != "" && $json['dto_date'] == "")
        //     $filter_query .= " and fbr.requestDate >= '" . $json['dfrom_date'] . "'";
        // if ($json['dfrom_date'] == "" && $json['dto_date'] != "")
        //     $filter_query .= " and fbr.requestDate <= '" .$json['dto_date']. "'";
        // if ($json['dfrom_date'] != "" && $json['dto_date'] != "")
        //     $filter_query .= " and fbr.requestDate >= '" . $json['dfrom_date'] . "' and fbr.requestDate <= '" . $json['dto_date'] . "'";

        if ($json['assessment_from'] != "" && $json['assessment_to'] != "") {
            $filter_query .= " and fbr.review_status=2";
        }

        if ($json['assessment_from'] != "" && $json['assessment_to'] == "")
            $filter_query .= " and fbr.updatedAt >= '" . $json['assessment_from'] . "'";
        if ($json['assessment_from'] == "" && $json['assessment_to'] != "")
            $filter_query .= " and fbr.updatedAt <= '" . $json['assessment_to'] . "'";
        if ($json['assessment_from'] != "" && $json['assessment_to'] != "")
            $filter_query .= " and fbr.updatedAt >= '" . $json['assessment_from'] . "' and fbr.updatedAt <= '" . $json['assessment_to'] . "'";


        // if ($json['activity'] != "") {
        //     if ($json['activity'] == 'full') {
        //         $having_query .= " and QA = (QT-1) ";
        //     } else {
        //         $having_query .= " and QA < (QT-1)";
        //     }
        // }
        // if ($json['noOfGuidanceVideo'] != "") {
        //     if ($json['noOfGuidanceVideo'] == 'full') {
        //         $having_query .= " and  GV = (QT-1) and GV > 0 ";
        //     } else {
        //         $having_query .= " and  GV ='" . $json['noOfGuidanceVideo'] . "'";
        //     }
        // }


        if ($json['activity'] != "") {
            if ($json['activity'] == 'full') {
                $filter_query .= " and cit.completion_status = 1 and cit.totalRespond >=1 ";
            } else {
                $filter_query .= " and cit.completion_status = 0 ";
            }
        }


        if ($json['interviewname'] != "")
            $filter_query .= " and i.preInterviewId in (" . implode(",", $json['interviewname']) . ") ";

        // sibin candidate id filter 18 Nov 2022
        if ($json['candidate_id'] != "")
            $filter_query .= " and u.id in (" . $json['candidate_id'] . ")";

        if ($json['redirect'] == 'interviewIssue') {
            $filter_query .= " and fbr.reasonOfRejection in ('technicalIssue','incompleteInterview') ";
        }

        if ($json['redirect'] == 'deadInterviews') {
            $filter_query .= " and fbr.reasonOfRejection in ('duplicateAttempt','unauthorizedUser','limitedFreeAssessment') ";
        }




        /* if ($json['noOfGuidanceVideo'] != "") {
             if ($json['noOfGuidanceVideo'] == 'full') {
                 $having_query .= " and  GV = QT and GV > 0 ";
             } else {
                 $having_query .= " and  GV ='" . $json['noOfGuidanceVideo'] . "'";
             }
         }

         CASE WHEN i.categoryType = 9 THEN  (SELECT COUNT( CASE WHEN iqt.attemptStatus = 'Respond' THEN iqt.questionId ELSE NULL END) FROM interview_questions_transection iqt inner join questions qs on qs.id = iqt.questionId WHERE iqt.interviewId=m.interviewId and qs.deleted_at is null  and iqt.deleted_at is null and qs.expertAdvice is not null) ELSE  (SELECT COUNT(iqt.questionId) FROM interview_questions_transection iqt inner join questions qs on qs.id = iqt.questionId WHERE iqt.interviewId=m.interviewId and qs.deleted_at is null and iqt.deleted_at is null and qs.expertAdvice is not null) END as GV, 
         CASE WHEN i.categoryType = 9 THEN   (SELECT SUM(CASE WHEN qs.peerResponseVideo is not null THEN 1 WHEN (qs.peerResponseVideo is null and qs.mbr_id != 0) THEN 1 ELSE 0 END) FROM interview_questions_transection iqt inner join questions qs on qs.id = iqt.questionId WHERE iqt.interviewId=m.interviewId and qs.deleted_at is null and iqt.deleted_at is null and iqt.attemptStatus = 'Respond')  ELSE (SELECT SUM(CASE WHEN qs.peerResponseVideo is not null THEN 1 WHEN (qs.peerResponseVideo is null and qs.mbr_id != 0) THEN 1 ELSE 0 END) FROM interview_questions_transection iqt inner join questions qs on qs.id = iqt.questionId WHERE iqt.interviewId=m.interviewId and qs.deleted_at is null and iqt.deleted_at is null)  END as PRV,

         COUNT(distinct m.questionId) as QA, CASE WHEN i.categoryType = 9 THEN  (SELECT COUNT( CASE WHEN iqt.attemptStatus is not null THEN iqt.questionId ELSE NULL END) FROM interview_questions_transection iqt inner join questions qs on qs.id = iqt.questionId WHERE iqt.interviewId=m.interviewId and qs.deleted_at is null  and iqt.deleted_at is null) ELSE (SELECT COUNT(iqt.questionId) FROM interview_questions_transection iqt inner join questions qs on qs.id = iqt.questionId WHERE iqt.interviewId=m.interviewId and qs.deleted_at is null and iqt.deleted_at is null and iqt.deleted_at is null) -1 END 
         as QT*/
        $order_query = " order by fbr.interviewSessionId desc ";
        $main_query = "SELECT u.id, concat(u.firstName,u.lastName) as name,i.assessmenttype as currentAssessmentType,u.emailId, u.mobileNumber, fbr.updatedAt as AssessmentStatusDate,CASE WHEN fbr.id is not null THEN YEAR(fbr.updatedAt) ELSE NULL END AS AssessmentStatusYear, CASE WHEN fbr.id is not null THEN MONTH(fbr.updatedAt) ELSE NULL END AS AssessmentStatusMonth
        , st.id as streamId, st.stream, cl.id as collegeId, cl.collegeName, fbr.interviewSessionId as sessionId, i.name as interview_name, fv.favourite_subject as areaOfInterview, i.productId, prod.name as productName, i.id as intId, i.productId as menuId, i.subject_id as subjectId, cat.name as category, fbr.id as fbr_id, fbr.review_status as fbr_status, fbr.delegationId as fbr_delegate, pn.name as delegatedExpert, fbr.fbDeliveryDate as fbDeliveryDate, fbr.priority as interviewPriority, fbr.rejectedBy,
        CASE WHEN fbr.review_status = -4 THEN (select ut.firstName from users ut where ut.id = fbr.rejectedBy ) ELSE NULL END AS RejectedByWhom, fbr.reasonOfRejection, pn.name as delegatedName,CASE WHEN cit.completion_status is not NULL THEN cit.completion_status ELSE 'Incomplete' END AS completion_status,
        CASE WHEN cit.totalRespond is not NULL THEN cit.totalRespond 
            ELSE (CASE  WHEN i.categoryType = 9 THEN (Select count(questionId) from interview_questions_transection WHERE attemptStatus = 'Respond' and interviewId = fbr.interviewId ) ELSE (Select count(interviewSessionId) from mergedVideos  WHERE interviewSessionId is not NULL and interviewSessionId = fbr.interviewSessionId and interviewId = fbr.interviewId and candidateId = fbr.candidateId) END )  END as  totalRespondOld,
        (Select count(questionId) from interview_questions_transection WHERE attemptStatus IN('Respond','Respond1','Respond2','Idk','Idk1','Idk2') and interviewId = fbr.interviewId) as totalRespond,
        CASE WHEN cit.totalSkip is not NULL THEN cit.totalSkip ELSE (CASE  WHEN i.categoryType = 9 THEN (Select count(questionId) from interview_questions_transection WHERE attemptStatus = 'Skip' and interviewId = fbr.interviewId ) ELSE 0 END )  END as  totalSkip,
        (SELECT 
        (SELECT COUNT(questionId) 
        FROM interview_questions_transection 
        WHERE attemptStatus IS NOT NULL AND interviewId = fbr.interviewId)) AS totalQuestion,
        pd.year as YearOfPasssing from feedback_request fbr left outer join candidate_interview_transection cit on cit.interviewSessionId = fbr.interviewSessionId and cit.interviewId = fbr.interviewId and cit.candidateId = fbr.candidateId left outer join feedback_status_question fsq on fsq.feedbackRequestId = fbr.id   left outer join interview i  on fbr.interviewId = i.id left outer join product prod on prod.id = i.productId left outer join favourite_subject fv on fv.id = i.subject_id left outer join category cat on i.categoryType = cat.id left outer join users u on u.id = fbr.candidateId " . $rawData . " " . $subData . " left outer join professionaldetails pd on pd.candidateId=u.id left outer join stream st on pd.specialization = st.id left outer join colleges cl on cl.id=pd.college left outer join  panel pn on fsq.expertId = pn.id where fbr.interviewSessionId is not null " . $filter_query . " group by fbr.interviewSessionId " . $having_query . " " . $order_query;
        // echo $main_query;
        $data = $main_query . $limit_query;

        $cquery = "SELECT   u.id
       FROM feedback_request fbr
       LEFT OUTER JOIN users u ON u.id = fbr.candidateId
       LEFT OUTER JOIN professionaldetails pd ON pd.candidateId = u.id
       LEFT OUTER JOIN colleges cl ON cl.id = pd.college
       left outer join interview i on fbr.interviewId = i.id
       left outer join candidate_interview_transection cit on cit.interviewSessionId = fbr.interviewSessionId and cit.interviewId = fbr.interviewId and cit.candidateId = fbr.candidateId 
       " . $rawData . " " . $subData . "
       where
       fbr.interviewSessionId IS NOT NULL " . $filter_query . "
       GROUP BY fbr.interviewSessionId
       " . $having_query . " "
            . $order_query;

        $count_query = mysqli_query($databaseConnection, $cquery);
        $count_rows = mysqli_num_rows($count_query);

        // echo $data ;
        $query = mysqli_query($databaseConnection, $data);
        $rows = mysqli_fetch_all($query, MYSQLI_ASSOC);

        // if (mysqli_num_rows($query) > 0) {
        //$total_data['data'] = mysqli_fetch_all($query,MYSQLI_ASSOC);
        foreach ($rows as &$row) {

            $collegeInterviewStatus = mysqli_query($databaseConnection, "Select count(fr.id)  as TotalInterview , count(CASE WHEN fr.review_status != -4 and fr.review_status != -2  THEN fr.id ELSE NULL END)  as TotalApproved from feedback_request fr inner join professionaldetails pd on pd.candidateId =  fr.candidateId where  pd.college = '" . $row['collegeId'] . "' and pd.year ='" . $row['YearOfPasssing'] . "'");


            $collegeInterviewResult = mysqli_fetch_assoc($collegeInterviewStatus);
            $row['TotalInterviewForCollege'] = $collegeInterviewResult['TotalInterview'];
            $row['TotalApprovedForCollege'] = $collegeInterviewResult['TotalApproved'];


            // $erTaggedCount = mysqli_query($databaseConnection,"select count(distinct(questionId)) as totalQns from expert_review where feedback_request_id=".$row['fbr_id']." and overallRating='videoIssue' order by questionId;");

            // $erodTaggedCount = mysqli_query($databaseConnection,"select count(distinct(questionId)) as totalQns from expert_review_observation_details where feedback_request_id=".$row['fbr_id']." and questionId is not null order by questionId;");


            // $ertaggedResult = mysqli_fetch_assoc($erTaggedCount);
            // $erodtaggedResult = mysqli_fetch_assoc($erodTaggedCount);
            // $row['ertotalTagged'] = $ertaggedResult['totalQns'];
            // $row['erodtotalTagged'] = $erodtaggedResult['totalQns'];




            /*$subjectForReview = array();
            $subject_query = mysqli_query($databaseConnection, "select * from (SELECT q.subjectId, fs.favourite_subject FROM interview_questions_transection iqt inner join questions q on q.id = iqt.questionId inner join favourite_subject fs on fs.id = q.subjectId where q.deleted_at is null and iqt.deleted_at is null and iqt.interviewId = '".$row['intId']."' order by iqt.sequence DESC LIMIT 100 OFFSET 1) temp group by subjectId");
            if (mysqli_num_rows($subject_query)>0) {
                //$subjectRes = mysqli_fetch_all($subject_query, MYSQLI_ASSOC);
                $eligibleInterviewForReview = array();
                while ($subjectForReview = mysqli_fetch_array($subject_query, MYSQLI_ASSOC)) {
                    $qry = "select id, name, emailId, phonenumber, eligibleInterviewForReview, areaOfExpertiseId from `panel` where isAssessmentApproved = 'Y' and deleted_at is null and Find_In_Set(".$subjectForReview['subjectId'].", areaOfExpertiseId)";
                    $panel_query = mysqli_query($databaseConnection, $qry);
                    if (mysqli_num_rows($panel_query)>0) {
                        $expertList = mysqli_fetch_all($panel_query, MYSQLI_ASSOC);
                    } else {
                        $expertList = [];
                    }
                    $subjectForReview['eligibleExpertsForReview'] = $expertList;
                    array_push($eligibleInterviewForReview, $subjectForReview);
                }
                $row['subjects'] = $eligibleInterviewForReview;
            } else {
                $row['subjects'] = [];
            }*/
            // if ($row['QA'] == $row['QT']) {
            //     $row['activity'] = 'Full';
            // } else {
            //     $row['activity'] = $row['QA'] . '/' . $row['QT'];
            // }

            // if ($row['QA'] == ($row['QT'] - 1)) {
            //     $row['activity'] = 'Full';
            // } else {
            //     $row['activity'] = $row['QA'] . '/' . ($row['QT'] - 1);
            // }

            $activeExpertDetails = array();
            if ($row['fbr_status'] == 0 || $row['fbr_status'] == 1 || $row['fbr_status'] == 2) {
                $activeExpertQry = mysqli_query($databaseConnection, "select id, name, emailId, phonenumber, eligibleInterviewForReview, areaOfExpertiseId from `panel` where id in (select expertId from feedback_status_question where expertId is not null and feedbackRequestId = '" . $row['fbr_id'] . "' group by expertId) ");
                if (mysqli_num_rows($activeExpertQry) > 0) {
                    $activeExpertDetails = mysqli_fetch_all($activeExpertQry, MYSQLI_ASSOC);
                }
            }

            $row['activeExpertDetails'] = $activeExpertDetails;
            unset($activeExpertDetails);
            $activeExpertDetails = array();

            $workingExpertDetails = array();
            if ($row['fbr_status'] == 1 || $row['fbr_status'] == 2) {
                $workingExpertQry = mysqli_query($databaseConnection, "SELECT COUNT(fsq.id) as questionLocked,CASE WHEN MIN(fsq.review_status) = 0 THEN 'Open' WHEN MIN(fsq.review_status) = 1 THEN 'InProgress' WHEN MIN(fsq.review_status) = 2 THEN 'Submitted' WHEN MIN(fsq.review_status) = 9 THEN 'Stepper Rejected' END as workStatus,p.id,CASE WHEN p.name IS NULL THEN '' ELSE p.name END as expertName,p.emailId,p.phonenumber FROM feedback_status_question fsq LEFT JOIN panel p ON fsq.expertId = p.id WHERE fsq.feedbackRequestId = '" . $row['fbr_id'] . "' GROUP BY fsq.expertId;");
                if (mysqli_num_rows($workingExpertQry) > 0) {
                    $workingExpertDetails = mysqli_fetch_all($workingExpertQry, MYSQLI_ASSOC);
                }
            }

            $row['workingExpertDetails'] = $workingExpertDetails;
            $row['workingExpertDetailsQry'] = "SELECT COUNT(fsq.id) as questionLocked,CASE WHEN MIN(fsq.review_status) = 0 THEN 'Open' WHEN MIN(fsq.review_status) = 1 THEN 'InProgress' WHEN MIN(fsq.review_status) = 2 THEN 'Submitted' END as workStatus,p.id,CASE WHEN p.name IS NULL THEN '' ELSE p.name END as expertName,p.emailId,p.phonenumber FROM feedback_status_question fsq LEFT JOIN panel p ON fsq.expertId = p.id WHERE fsq.feedbackRequestId = '" . $row['fbr_id'] . "' GROUP BY fsq.expertId;";
            unset($workingExpertDetails);
            $workingExpertDetails = array();


            $userSubscriptionDetails = getSubsciptionDetailsOnAssessment($databaseConnection, $row['id']);
            $row['amount'] = $userSubscriptionDetails['amount'];
            $row['endDate'] = $userSubscriptionDetails['endDate'];
            $row['s_endDifference'] = $userSubscriptionDetails['s_endDifference'];

            $duplicateAttempt = mysqli_query($databaseConnection, "SELECT count(Distinct fr.interviewSessionId) as TotalAttempt , count(Distinct (CASE WHEN fr.review_status='2' THEN fr.id WHEN fr.review_status='-3' THEN fr.id  WHEN fr.review_status = '0' THEN fr.id WHEN fr.review_status='1' THEN fr.id ELSE NULL END)) as ApprovedAttempt from feedback_request fr  WHERE fr.interviewId = '" . $row['intId'] . "' and fr.candidateId = '" . $row['id'] . "';");
            $duplicateRes = mysqli_fetch_assoc($duplicateAttempt);
            $row['TotalAttempt'] = $duplicateRes['TotalAttempt'];
            $row['ApprovedAttempt'] = $duplicateRes['ApprovedAttempt'];

            $malpracticeCount = mysqli_query($databaseConnection, "select count(er.feedback_request_id) as malpractcount,er.candidateId,ov.observation_values,er.feedback_request_id from expert_review er inner join expert_review_observation_details erod on erod.expertReviewId=er.id inner join observation_values ov on ov.id=erod.observationValueId where erod.observationValueId in (308,442,443) and er.feedback_request_id = '" . $row['fbr_id'] . "' group by er.candidateId;");
            $malpracticeRes = mysqli_fetch_assoc($malpracticeCount);
            if (mysqli_num_rows($malpracticeCount) > 0) {
                $row['malpractcount'] = $malpracticeRes['malpractcount'];
            } else {
                $row['malpractcount'] = '';
            }


            $durationOfPracticeQry = mysqli_query($databaseConnection, "SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(m.totalTime)) + SUM(TIME_TO_SEC(vwd.prwatchDuration)) + SUM(TIME_TO_SEC(vwd.psWatchDuration)) + SUM(TIME_TO_SEC(vwd.gvWatchDuration))) as duration FROM `mergedVideos` m inner join video_watched_details vwd on vwd.mergeId = m.mergeId WHERE m.`interviewSessionId` LIKE '" . $row['sessionId'] . "' group by m.`interviewSessionId`;");
            if (mysqli_num_rows($durationOfPracticeQry) > 0) {
                $durationOfPracticeRes = mysqli_fetch_assoc($durationOfPracticeQry);
                $row['durationOfPractice'] = $durationOfPracticeRes['duration'];
            } else {
                $row['durationOfPractice'] = "00:00:00";
            }


            $durationOfPracticeProductQry = mysqli_query($databaseConnection, "SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(m.totalTime)) + SUM(TIME_TO_SEC(vwd.prwatchDuration)) + SUM(TIME_TO_SEC(vwd.psWatchDuration)) + SUM(TIME_TO_SEC(vwd.gvWatchDuration))) as durationSubject FROM `mergedVideos` m inner join video_watched_details vwd on vwd.mergeId = m.mergeId inner join interview i on i.id = m.interviewId WHERE i.productId = '" . $row['productId'] . "' and m.candidateId = '" . $row['id'] . "';");
            $durationOfPracticeProductRes = mysqli_fetch_assoc($durationOfPracticeProductQry);
            $row['durationOfPracticeProduct'] = $durationOfPracticeProductRes['durationSubject'];
            /*video verification is not count as FeedbackPending  review_status =-2 change by Naraayn  6/9/2021*/
            // $feedbackPendingQuery = mysqli_query($databaseConnection, "select count(distinct (CASE WHEN fr.review_status = '2' THEN fr.id ELSE NULL END)) as numOfFeedbackDelivered, count(distinct (CASE WHEN fr.review_status = '0' THEN fr.id WHEN fr.review_status = '1' THEN fr.id WHEN fr.review_status = '-3' THEN fr.id ELSE NULL END)) as numOfFeedbackPending,count(distinct fr.interviewSessionId) as TotalInterViewTakenProductWise from feedback_request fr inner join interview i on i.id = fr.interviewId  WHERE i.productId = '" . $row['productId'] . "' and fr.candidateId = '" . $row['id'] . "';");
            // $feedbackPendingResult = mysqli_fetch_assoc($feedbackPendingQuery);
            // $row['NumOfFeedbackDelivered'] = $feedbackPendingResult['numOfFeedbackDelivered'];
            // $row['NumOfFeedbackPending'] = $feedbackPendingResult['numOfFeedbackPending'];
            // $row['NumOfInterviewTaken'] = $feedbackPendingResult['TotalInterViewTakenProductWise'];

            $lastFeedbackQuery = mysqli_query($databaseConnection, "select max(fr.updatedAt) as lastFeedbackDate from feedback_request fr where fr.review_status = '2' and fr.candidateId = '" . $row['id'] . "';");
            $lastFeedbackResult = mysqli_fetch_assoc($lastFeedbackQuery);
            $row['lastFeedbackDate'] = $lastFeedbackResult['lastFeedbackDate'];

            // if ($row['fbr_status'] == -3 || $row['fbr_status'] == 2) {
            //     $numOfPersonalizedVideoQuery = mysqli_query($databaseConnection, "SELECT COUNT(feedbackVideoURL) AS numOfPersonalizedVideo FROM expert_review WHERE feedback_request_id = '" . $row['fbr_id'] . "';");
            //     $numOfPersonalizedVideoResult = mysqli_fetch_assoc($numOfPersonalizedVideoQuery);
            //     $row['numOfPersonalizedVideo'] = $numOfPersonalizedVideoResult['numOfPersonalizedVideo'];
            // } else {
            //     $row['numOfPersonalizedVideo'] = NULL;
            // }

            array_push($result, $row);
        }
        $total_data['data'] = $result;
        $total_data['count'] = $count_rows;
        $to_encode = $total_data;

    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving Student information"
        );
    }
    echo json_encode($to_encode);
}
elseif (isset($_GET['getfeedbackDashboardFilters'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $filter = " Where 1 ";
        $collegeQuery = '';

        if ($userType == 'college') {
            $collegeQuery = "select id,collegeName as college from colleges where FIND_IN_SET(id, (select college_id from users where id = '" . $userId . "')) order by id=188,collegeName";
        } elseif ($userType == 'mentor') {
            $collegeQuery = "select id,collegeName as college from colleges where id in (select college from professionaldetails where assignMentorId = '" . $userId . "') order by id=188,collegeName";
        } elseif ($userType == 'student') {
            $collegeQuery = "select id,collegeName as college from colleges where id in (select college from professionaldetails where candidateId = '" . $userId . "') order by id=188,collegeName";
        } else {
            $collegeQuery = "select id,collegeName as college from colleges order by id=188,collegeName";
        }
        $college_query = mysqli_query($databaseConnection, $collegeQuery);

        $cat_query = mysqli_query($databaseConnection, "select * from category");
        $values['categories'] = mysqli_fetch_all($cat_query, MYSQLI_ASSOC);
        if ($json['cat'] != "")
            $filter = "  and categoryType=" . $json['cat'];
        $int_query = mysqli_query($databaseConnection, "select id,name from interview " . $filter . "  and categoryType !='9'  ORDER BY name");
        $stream_query = mysqli_query($databaseConnection, "select * from stream where isActive = 'Y' order by id=11,stream");
        $menu_query = mysqli_query($databaseConnection, "select * from menu");

        $employability_status = mysqli_query($databaseConnection, "SELECT empstatus as `name` FROM `candidateEmp_status` GROUP BY empstatus;");


        $filter4 = "SELECT fs.favourite_subject as subjectName,fs.id  FROM favourite_subject fs LEFT JOIN fav_prog_skill fps ON fps.fav_prog_skill LIKE CONCAT('%',fs.favourite_subject,'%') LEFT OUTER JOIN questions q ON q.subjectId = fs.id  WHERE fps.id IS null AND fs.id NOT IN (178) GROUP BY fs.favourite_subject ORDER BY fs.favourite_subject ASC;";
        $filter4Result = mysqli_query($databaseConnection, $filter4);

        $filter6 = "SELECT fs.favourite_subject as subjectName,fs.id  FROM favourite_subject fs LEFT JOIN fav_prog_skill fps ON fps.fav_prog_skill LIKE CONCAT('%',fs.favourite_subject,'%') LEFT OUTER JOIN questions q ON q.subjectId = fs.id  WHERE fps.id IS NOT null GROUP BY fs.favourite_subject ORDER BY fs.favourite_subject ASC;";
        $filter6Result = mysqli_query($databaseConnection, $filter6);

        $filter5 = "SELECT fs.favourite_subject as subjectName,fs.id  FROM favourite_subject fs LEFT JOIN fav_prog_skill fps ON fps.fav_prog_skill LIKE CONCAT('%',fs.favourite_subject,'%') LEFT OUTER JOIN questions q ON q.subjectId = fs.id  WHERE fps.id IS null AND fs.id IN (178) GROUP BY fs.favourite_subject ORDER BY fs.favourite_subject ASC;";
        $filter5Result = mysqli_query($databaseConnection, $filter5);

        $filter8 = "SELECT * FROM `sector`";
        $filter8Result = mysqli_query($databaseConnection, $filter8);

        $filter9 = "Select distinct(st.company) as company,case when pr.interviewName is null then ac.name else pr.interviewName End as name,st.preInterviewId as id from scps_transaction st inner join aspiration_company ac on ac.id=st.company inner join preInterview pr on pr.id=st.preInterviewId where st.company!=0 ORDER BY pr.id DESC";
        $filter9Result = mysqli_query($databaseConnection, $filter9);


        $values['college'] = mysqli_fetch_all($college_query, MYSQLI_ASSOC);
        $values['specialization'] = mysqli_fetch_all($stream_query, MYSQLI_ASSOC);
        $values['interviews'] = mysqli_fetch_all($int_query, MYSQLI_ASSOC);
        $values['menu'] = mysqli_fetch_all($menu_query, MYSQLI_ASSOC);
        $values['empStatus'] = mysqli_fetch_all($employability_status, MYSQLI_ASSOC);

        $values['cognitiveSubjects'] = mysqli_fetch_all($filter4Result, MYSQLI_ASSOC);
        $values['programmingSubjects'] = mysqli_fetch_all($filter6Result, MYSQLI_ASSOC);
        $values['behavioralSubjects'] = mysqli_fetch_all($filter5Result, MYSQLI_ASSOC);
        $values['sectors'] = mysqli_fetch_all($filter8Result, MYSQLI_ASSOC);
        $values['interviewname'] = mysqli_fetch_all($filter9Result, MYSQLI_ASSOC);


        $to_encode = $values;
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving Student information"
        );
    }
    echo json_encode($to_encode);
}
elseif (isset($_GET['getFeedbackSummaryData'])) {
    /* this method is updated by Narayan in Jan 2022 */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $filter_query = " ";
        $limit = $json['limit'];
        $start = ($json['page'] - 1) * $limit;
        $limit_query = $limit == 0 ? "" : " limit " . $start . "," . $limit;
        $alldata = array();
        $values = array();
        $collegeId = '';
        $order_query = "order by fbr.interviewSessionId desc,fr.aptitudeScore desc";
        $rawData = " ";
        $subjectquery = " ";


        if ($json['college'] != "" and sizeof($json['college']) > 0)
            $filter_query .= " and pd.college in ('" . implode("', '", array_map("addSlashToString", $json['college'])) . "')";




        if ($json['overallRatings'] != "")
            $filter_query .= " and fr.finalOpinion = '" . $json['overallRatings'] . "'";

        //    if ($json['communicationSkill'] != "") {
        //        if ($json['communicationSkill'] === 'good') {
        //           $filter_query .= " and fr.communicationSkill >= 7";
        //        } elseif ($json['communicationSkill'] === 'acceptable') {
        //            $filter_query .= " and fr.communicationSkill < 7 and fr.communicationSkill > 4";
        //        } else {
        //           $filter_query .= " and fr.communicationSkill <= 4";
        //        }
        //    }

        if ($json['communicationSkill'] != "") {
            if ($json['communicationSkill'] === 'insufficientData') {
                $filter_query .= " and fr.communicationSkill < 2";
            } elseif ($json['communicationSkill'] === 'belowIndustryStandard') {
                $filter_query .= " and fr.communicationSkill >= 2 and fr.communicationSkill < 4";
            } elseif ($json['communicationSkill'] === 'average') {
                $filter_query .= " and fr.communicationSkill >= 4 and fr.communicationSkill < 6";
            } elseif ($json['communicationSkill'] === 'satisfactory') {
                $filter_query .= " and fr.communicationSkill >= 6 and fr.communicationSkill < 8";
            } elseif ($json['communicationSkill'] === 'good') {
                $filter_query .= " and fr.communicationSkill >= 8 and fr.communicationSkill < 9";
            } else if ($json['communicationSkill'] === 'master') {
                $filter_query .= " and fr.communicationSkill == 10";
            }
        }

        // sibin




        if ($json['sectors'] != "" and sizeof($json['sectors']) > 0) {
            $filter_query .= " AND s.id IN (" . implode(",", $json['sectors']) . ") ";
        }

        if ($json['cognitiveSubjects'] != '') {
            $subjectquery .= "inner join expert_review er on er.candidateId=pd.candidateId LEFT OUTER JOIN questions qs ON er.questionId = qs.id";
            $filter_query .= " AND qs.subjectId IN (" . implode(",", $json['cognitiveSubjects']) . ") ";
            if ($json['cognitiveSubjectsAptLevel'] != '') {
                if ($json['cognitiveSubjectsAptLevel'] === 'good') {
                    $filter_query .= " and er.overallRating >= 7";
                } elseif ($json['cognitiveSubjectsAptLevel'] === 'acceptable') {
                    $filter_query .= " and er.overallRating < 7 and er.overallRating > 4";
                } else {
                    $filter_query .= " and er.overallRating <= 4";
                }
            }
        }

        if ($json['behavioralSubjects'] != '') {
            $subjectquery .= "inner join expert_review er on er.candidateId=pd.candidateId LEFT OUTER JOIN questions qs ON er.questionId = qs.id";
            $filter_query .= " AND qs.subjectId IN (" . implode(",", $json['behavioralSubjects']) . ") ";
            if ($json['behaviouralSkill'] != '') {
                if ($json['behaviouralSkill'] === 'good') {
                    $filter_query .= " and er.overallRating >= 7";
                } elseif ($json['behaviouralSkill'] === 'acceptable') {
                    $filter_query .= " and er.overallRating < 7 and er.overallRating > 4";
                } else {
                    $filter_query .= " and er.overallRating <= 4";
                }
            }
        }


        if ($json['progSubjects'] != '') {
            $subjectquery .= "inner join expert_review er on er.candidateId=pd.candidateId LEFT OUTER JOIN questions qs ON er.questionId = qs.id";
            $filter_query .= " AND qs.subjectId IN (" . implode(",", $json['progSubjects']) . ") ";
            if ($json['codingSkill'] != '') {

                if ($json['codingSkill'] === 'good') {
                    $filter_query .= " and er.overallRating >= 7";
                } elseif ($json['codingSkill'] === 'acceptable') {
                    $filter_query .= " and er.overallRating < 7 and er.overallRating > 4";
                } else {
                    $filter_query .= " and er.overallRating <= 4";
                }
            }
        }


        // sibin
        if ($json['redirect'] != '') {
            if ($json['redirect'] === '7') {
                $filter_query .= " and fr.problemSolvingSkill >= 7";
            } elseif ($json['redirect'] === '8') {
                $filter_query .= " and fr.problemSolvingSkill < 7 and fr.problemSolvingSkill > 4";
            } elseif ($json['redirect'] === '9') {
                $filter_query .= " and fr.problemSolvingSkill <= 4";
            } elseif ($json['redirect'] === '10') {
                $filter_query .= " and fr.behaviouralSkill >= 7";
            } elseif ($json['redirect'] === '11') {
                $filter_query .= " and fr.behaviouralSkill < 7 and fr.behaviouralSkill > 4";
            } elseif ($json['redirect'] === '12') {
                $filter_query .= " and fr.behaviouralSkill <= 4";
            } elseif ($json['redirect'] === '13') {
                $filter_query .= " and fr.codingSkill >= 7";
            } elseif ($json['redirect'] === '14') {
                $filter_query .= " and fr.codingSkill < 7 and fr.codingSkill > 4";
            } elseif ($json['redirect'] === '15') {
                $filter_query .= " and fr.codingSkill <= 4";
            }

        }


        //    if ($json['problemSolvingSkill'] != "") {
        //        if ($json['problemSolvingSkill'] === 'good') {
        //            $filter_query .= " and fr.problemSolvingSkill >= 7";
        //        } elseif ($json['problemSolvingSkill'] === 'acceptable') {
        //            $filter_query .= " and fr.problemSolvingSkill < 7 and fr.problemSolvingSkill > 4";
        //        } else {
        //            $filter_query .= " and fr.problemSolvingSkill <= 4";
        //        }
        //    }

        //    if ($json['aptitudeScore'] != "") {
        //     if ($json['aptitudeScore'] === 'good') {
        //         $filter_query .= " and fr.aptitudeScore >= 7";
        //     } elseif ($json['aptitudeScore'] === 'acceptable') {
        //         $filter_query .= " and fr.aptitudeScore < 7 and fr.aptitudeScore > 4";
        //     } else {
        //         $filter_query .= " and fr.aptitudeScore <= 4";
        //     }
        // }


        //    if ($json['behaviouralSkill'] != "") {
        //        if ($json['behaviouralSkill'] === 'good') {
        //            $filter_query .= " and fr.behaviouralSkill >= 7";
        //        } elseif ($json['behaviouralSkill'] === 'acceptable') {
        //            $filter_query .= " and fr.behaviouralSkill < 7 and fr.behaviouralSkill > 4";
        //        } else {
        //            $filter_query .= " and fr.behaviouralSkill <= 4";
        //        }
        //    }


        if ($json['empStatus'] != "") {
            $filter_query .= " AND ces.empStatus = '" . $json['empStatus'] . "'";
        }

        //     if ($json['empStatus'] != "") {
        //         if ($json['empStatus'] === "Possible Fit") {
        //         $filter_query .= " AND fr.aptitudeScore > 4 and fr.aptitudeScore < 7 ";
        //         }elseif ($json['empStatus'] === "Best Fit") {
        //             $filter_query .= " AND fr.aptitudeScore > 7";
        //         }elseif ($json['empStatus'] === "Not Fit") {
        //             $filter_query .= " AND fr.aptitudeScore < 4";
        //         }
        // } 

        if ($json['cgpa'] != "") {
            $filter_query .= " AND pd.cgpa >= '" . $json['cgpa'] . "'";
        }
        if ($json['confidence'] != "") {
            if ($json['confidence'] === 'good') {
                $filter_query .= " and fr.confidence >= 7";
            } elseif ($json['confidence'] === 'acceptable') {
                $filter_query .= " and fr.confidence < 7 and fr.confidence > 4";
            } else {
                $filter_query .= " and fr.confidence <= 4";
            }
        }

        //    if ($json['isTieUpStatus'] != "") {

        //        if($userType != 'college'){
        //             $rawData .= " inner join raw_data rd on rd.email_id = u.emailId ";

        //             if ($json['isTieUpStatus'] == 'Y') {
        //                 $filter_query .= " and rd.isPaid = 'Y'";
        //             }elseif ($json['isTieUpStatus'] == 'F') {
        //                 $filter_query .= " and rd.isPaid = 'F'";
        //             } else {
        //                 $filter_query .= " and rd.isPaid = 'N'";
        //             }

        //         }
        //    }
        if ($json['stream'] != "" and sizeof($json['stream']) > 0) {
            $filter_query .= " and pd.specialization in ('" . implode("', '", $json['stream']) . "')";
        }


        if ($json['interviews'] != "" and sizeof($json['interviews']) > 0) {
            $filter_query .= " and i.id in ('" . implode("', '", $json['interviews']) . "')";
        }



        if ($json['feedbackStatus'] != "") {
            if ($json['feedbackStatus'] == "-1") {
                $filter_query .= " and fbr.review_status is NULL";
            } else {
                $filter_query .= " and fbr.review_status ='" . $json['feedbackStatus'] . "'";
            }
        }


        if ($json['yop'] != "")
            $filter_query .= " and pd.year in (" . $json['yop'] . ")";




        if ($json['name'] != "")
            $filter_query .= " and u.firstName like '%" . $json['name'] . "%'";
        if ($json['from_date'] != "" && $json['to_date'] == "")
            $filter_query .= " and fbr.interviewSessionId >= '" . strtotime($json['from_date']) . "'";
        if ($json['from_date'] == "" && $json['to_date'] != "")
            $filter_query .= " and fbr.interviewSessionId <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";
        if ($json['from_date'] != "" && $json['to_date'] != "")
            $filter_query .= " and fbr.interviewSessionId >= '" . strtotime($json['from_date']) . "' and fbr.interviewSessionId <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";
        if ($userType == 'college') {
            $college_query = mysqli_query($databaseConnection, "select u1.* from users u1 where u1.id =" . $json['userId'] . " ");
            $college_result = mysqli_fetch_array($college_query, MYSQLI_ASSOC);
            $filter_query .= " and pd.college in (" . $college_result['college_id'] . ") ";
            $filter_query .= " and (fbr.review_status not in (-6,-7) OR (fbr.review_status not in (-6,-7) AND  fbr.review_status is not null AND i.name ='Video Resume' )) ";
            $rawData .= " inner join raw_data rd on rd.email_id = u.emailId ";

            if ($json['isTieUpStatus'] == 'Y') {
                $filter_query .= " and rd.isPaid = 'Y'";
            } elseif ($json['isTieUpStatus'] == 'F') {
                $filter_query .= " and rd.isPaid = 'F'";
            } elseif ($json['isTieUpStatus'] == 'N') {
                $filter_query .= " and rd.isPaid = 'N'";
            } else {
                $filter_query .= " and rd.isPaid in('Y','F')";
            }

        }

        //    $query = "select u.id,fr.aptitudeScore,pd.cgpa,st.stream,concat(u.firstName,u.lastName) as name, u.emailId, u.mobileNumber, pd.college as cl_id, cl.collegeName as college, st.stream as specialization, pd.year, concat('https://goprac.com/review?i=',fbr.interviewId,'&c=',fbr.candidateId ,'&s=',fbr.interviewSessionId) as VideoResumeLink,pd.specialization as str_id, m.interviewSessionId as sessionId, i.name as interview_name, i.id as intId, fbr.id as fbr_id, fbr.review_status as fbr_status,COUNT(m.questionId) as QA, CASE WHEN i.categoryType = 9 THEN  (SELECT COUNT( CASE WHEN iqt.AttemptStatus is not NULL THEN iqt.questionId ELSE NULL END) FROM interview_questions_transection iqt inner join questions qs on qs.id = iqt.questionId WHERE iqt.interviewId=m.interviewId and qs.deleted_at is null and iqt.deleted_at is null) ELSE (SELECT COUNT(iqt.questionId) FROM interview_questions_transection iqt inner join questions qs on qs.id = iqt.questionId WHERE iqt.interviewId=m.interviewId and qs.deleted_at is null and iqt.deleted_at is null) -1 END as QT, CASE WHEN fbr.review_status is NULL THEN 'Assessment not Requested' WHEN fbr.review_status = 3 THEN 'Video Resume Approved' WHEN fbr.review_status = 2 THEN 'Assessemnt Completed' WHEN fbr.review_status = 1 THEN 'Assessment in-progess' WHEN fbr.review_status = 0 THEN 'Assessment is Open' WHEN fbr.review_status = -2 THEN 'Internal Review' WHEN fbr.review_status = -3 THEN 'Assessment Verification' WHEN fbr.review_status = -4 THEN 'Assessemnt Rejected' ELSE NULL END as fbr_status_text,fbr.viewAssessment,fr.finalOpinion, fr.communicationSkill, fr.problemSolvingSkill, fr.behaviouralSkill, fr.confidence, fr.codingSkill, fr.readingSkill, fr.listeningSkill, fr.rComprehensionSkill, fr.presentationSkill, fr.grammerSkill, fr.expertAdvice,
        //    CASE WHEN (i.productId = 1 OR i.productId = 6) AND ces.empstatus IS NOT NULL THEN ces.empstatus ELSE 'Not Active' END  as empStatus
        //    from interview i, mergedVideos m inner join users u on u.id = m.candidateId inner join professionaldetails pd on pd.candidateId=u.id left outer join stream st on pd.specialization = st.id left outer join colleges cl on cl.id = pd.college left outer join feedback_request fbr on fbr.interviewSessionId=m.interviewSessionId left outer join feedback_report fr on fr.feedbackRequestId = fbr.id LEFT JOIN candidateEmp_status ces ON ces.candidateId = pd.candidateId " . $subjectquery . " left outer join sector s on s.id=ces.sectorId " . $rawData . " where m.interviewId = i.id and u.active = 'Y' and u.deleted_at is null and m.interviewSessionId is not null ";
        //    $data = ' ';

        $data = ' ';

        $query = "select u.id,case when fr.aptitudeScore=-998 then 'Partially Assessed' when fr.aptitudeScore=-996 then 'Stepper Rejected' else fr.aptitudeScore end as aptitudeScore,pd.cgpa,st.stream,concat(u.firstName,u.lastName) as name, u.emailId, u.mobileNumber,pd.college as cl_id, cl.collegeName as college, st.stream as specialization, pd.year,pd.specialization as str_id, fbr.interviewSessionId as sessionId, i.name as interview_name, i.id as intId, fbr.id as fbr_id,CASE WHEN fbr.review_status is NULL THEN 'Assessment not Requested' WHEN fbr.review_status = 3 THEN 'Video Resume Approved' WHEN fbr.review_status = 2 THEN 'Assessemnt Completed' WHEN fbr.review_status = 1 THEN 'Assessment in-progess' WHEN fbr.review_status = 0 THEN 'Assessment is Open' WHEN fbr.review_status = -2 THEN 'Internal Review' WHEN fbr.review_status = -3 THEN 'Assessment Verification' WHEN fbr.review_status = -4 THEN 'Assessemnt Rejected' ELSE NULL END as fbr_status_text,fbr.viewAssessment,fr.finalOpinion, fr.communicationSkill, fr.problemSolvingSkill,fr.behaviouralSkill, fr.confidence, fr.codingSkill, fr.readingSkill, fr.listeningSkill, fr.rComprehensionSkill,fr.presentationSkill, fr.grammerSkill, fr.expertAdvice,CASE WHEN (i.productId = 1 OR i.productId = 6) AND ces.empstatus IS NOT NULL THEN ces.empstatus ELSE 'Not Active' END as empStatus from feedback_request fbr left outer JOIN candidateEmp_status ces ON ces.interviewSessionId = fbr.interviewSessionId left outer join feedback_report fr on fr.feedbackRequestId = fbr.id left outer join sector s on s.id=ces.sectorId inner join users u on u.id = fbr.candidateId inner join professionaldetails pd on pd.candidateId = fbr.candidateId" . $subjectquery . $rawData . " inner join interview i on i.id = fbr.interviewId  inner join stream st on st.id = pd.specialization inner join colleges cl on cl.id = pd.college where u.active = 'Y' and u.deleted_at is null and fbr.interviewSessionId is not null ";


        if ($userType == 'mentor') {
            $filter_query .= " and pd.assignMentorId in (" . $json['userId'] . ")";
        }
        if ($userType == 'student') {
            $student_query = mysqli_query($databaseConnection, "select p.*, u.firstName as name from professionaldetails p inner join users u on u.id = p.candidateId where p.candidateId =" . $json['userId'] . " order by id limit 1 ");
            $student = mysqli_fetch_array($student_query, MYSQLI_ASSOC);
            $filter_query .= " and u.id=" . $json['userId'];
            $collegeId = $student['college'];
        }
        $data = $query . $filter_query . " group by fbr.interviewSessionId " . $order_query;

        /* echo $data . ' ';  */
        $totalcount = mysqli_query($databaseConnection, $data);


        //    $countQuery = "SELECT m.interviewSessionId from interview i, mergedVideos m inner join users u on u.id = m.candidateId inner join professionaldetails pd on pd.candidateId=u.id left outer join stream st on pd.specialization = st.id left outer join colleges cl on cl.id = pd.college left outer join feedback_request fbr on fbr.interviewSessionId=m.interviewSessionId left outer join feedback_report fr on fr.feedbackRequestId = fbr.id LEFT JOIN candidateEmp_status ces ON ces.candidateId = pd.candidateId left join expert_review er on er.candidateId=pd.candidateId LEFT OUTER JOIN questions qs ON er.questionId = qs.id inner join sector s on s.id=ces.sectorId" . $rawData . " where m.interviewId = i.id and u.active = 'Y' and u.deleted_at is null and m.interviewSessionId is not null ";

        if ($data != '') {
            //    $count_query = mysqli_query($databaseConnection, $countData);
            $query = mysqli_query($databaseConnection, $data . $limit_query);

            $synchQuery = mysqli_query($databaseConnection, "select synched_at from synch_log where table_name = 'feedback_report' order by id desc limit 0,1");
            $synchResult = mysqli_fetch_assoc($synchQuery);
            if (mysqli_num_rows($query) > 0) {
                $total_data['data'] = mysqli_fetch_all($query, MYSQLI_ASSOC);
                //    $total_data['count'] = mysqli_num_rows($count_query);
                $total_data['count'] = mysqli_num_rows($totalcount);
                $total_data['synched_at'] = timeAgo($synchResult['synched_at']);
                $total_data['college'] = $collegeId;
                $to_encode = $total_data;
            } else {
                $to_encode = array(
                    'result' => "error",
                    'status' => 0,
                    'errorCode' => "in Error while retrieving Student information."
                );
            }
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "in Error You are not having access this page."
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving Student information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getFeedbackReportData'])) {
    /* this method is updated by narayan Jan 2022 */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $filter_query = "";
        $college = array();
        $rawData = " ";

        if ($json['stream'] != "" && sizeof($json['stream']) > 0)
            $filter_query .= " and pd.specialization in ('" . implode("', '", $json['stream']) . "')";
        if ($json['yop'] != "")
            $filter_query .= " and pd.year in (" . $json['yop'] . ")";
        if ($json['from_date'] != "" && $json['to_date'] == "")
            $filter_query .= " and fbr.interviewSessionId >= '" . strtotime($json['from_date']) . "'";
        if ($json['from_date'] == "" && $json['to_date'] != "")
            $filter_query .= " and fbr.interviewSessionId <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";
        if ($json['from_date'] != "" && $json['to_date'] != "")
            $filter_query .= " and fbr.interviewSessionId >= '" . strtotime($json['from_date']) . "' and fbr.interviewSessionId <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";
        if ($json['isTieUpStatus'] != "") {
            $rawData .= " inner join raw_data rd on rd.email_id = u.emailId ";
            if ($json['isTieUpStatus'] == 'Y') {
                $filter_query .= " and rd.isPaid = 'Y'";
            } else {
                $filter_query .= " and rd.isPaid = 'N'";
            }
        }
        if ($userType == 'college') {
            $college_query = mysqli_query($databaseConnection, "select u1.* from users u1 where u1.id =" . $json['userId'] . " ");
            $college_result = mysqli_fetch_array($college_query, MYSQLI_ASSOC);
            $filter_query .= " and pd.college in (" . $college_result['college_id'] . ")";
        }
        if ($userType == 'mentor') {
            $filter_query .= " and pd.assignMentorId in (" . $json['userId'] . ")";
        }
        if ($json['college'] != "" and sizeof($json['college']) > 0) {
            $filter_query .= " and pd.college in ('" . implode("', '", array_map("addSlashToString", $json['college'])) . "')";
            $college_query = mysqli_query($databaseConnection, "SELECT GROUP_CONCAT(collegeName SEPARATOR ', ') as collegeName FROM `colleges` WHERE id in ('" . implode("', '", array_map("addSlashToString", $json['college'])) . "') ");
            $college = mysqli_fetch_array($college_query, MYSQLI_ASSOC);
        }

        $query = "select 
               SUM(CASE WHEN fr.communicationSkill >= 7 THEN 1 ELSE 0 END) as communicationSkillGood,
               SUM(CASE WHEN fr.communicationSkill > 4  AND fr.communicationSkill < 7 THEN 1 ELSE 0 END) as communicationSkillAcceptable,
               SUM(CASE WHEN fr.communicationSkill <= 4 THEN 1 ELSE 0 END) as communicationSkillNeedsImprovement,
               SUM(CASE WHEN fr.problemSolvingSkill >= 7 THEN 1 ELSE 0 END) as problemSolvingSkillGood,
               SUM(CASE WHEN fr.problemSolvingSkill > 4 AND fr.problemSolvingSkill < 7 THEN 1 ELSE 0 END) as problemSolvingSkillAcceptable,
               SUM(CASE WHEN fr.problemSolvingSkill <= 4 THEN 1 ELSE 0 END) as problemSolvingSkillNeedsImprovement,
               SUM(CASE WHEN fr.behaviouralSkill >= 7 THEN 1 ELSE 0 END) as behaviouralSkillGood,
               SUM(CASE WHEN fr.behaviouralSkill > 4 AND fr.behaviouralSkill < 7 THEN 1 ELSE 0 END) as behaviouralSkillAcceptable,
               SUM(CASE WHEN fr.behaviouralSkill <= 4 THEN 1 ELSE 0 END) as behaviouralSkillNeedsImprovement,
               SUM(CASE WHEN fr.confidence >= 7 THEN 1 ELSE 0 END) as confidenceGood,
               SUM(CASE WHEN fr.confidence > 4 AND fr.confidence < 7 THEN 1 ELSE 0 END) as confidenceAcceptable,
               SUM(CASE WHEN fr.confidence <= 4 THEN 1 ELSE 0 END) as confidenceNeedsImprovement,
               SUM(CASE WHEN fr.codingSkill >= 7 THEN 1 ELSE 0 END) as codingSkillGood,
               SUM(CASE WHEN fr.codingSkill > 4 AND fr.codingSkill < 7 THEN 1 ELSE 0 END) as codingSkillAcceptable,
               SUM(CASE WHEN fr.codingSkill <= 4 THEN 1 ELSE 0 END) as codingSkillNeedsImprovement,
               SUM(CASE WHEN fr.readingSkill >= 7 THEN 1 ELSE 0 END) as readingSkillGood,
               SUM(CASE WHEN fr.readingSkill > 4 AND fr.readingSkill < 7 THEN 1 ELSE 0 END) as readingSkillAcceptable,
               SUM(CASE WHEN fr.readingSkill <= 4 THEN 1 ELSE 0 END) as readingSkillNeedsImprovement,
               SUM(CASE WHEN fr.listeningSkill >= 7 THEN 1 ELSE 0 END) as listeningSkillGood,
               SUM(CASE WHEN fr.listeningSkill > 4 AND fr.listeningSkill < 7 THEN 1 ELSE 0 END) as listeningSkillAcceptable,
               SUM(CASE WHEN fr.listeningSkill <= 4 THEN 1 ELSE 0 END) as listeningSkillNeedsImprovement
               from feedback_report fr, feedback_request fbr, professionaldetails pd inner join users u on u.id = pd.candidateId " . $rawData . " where fbr.id = fr.feedbackRequestId and pd.candidateId = fbr.candidateId ";
        $result = mysqli_query($databaseConnection, $query . $filter_query);
        $data = mysqli_fetch_all($result, MYSQLI_ASSOC);

        $countQuery = "Select count(fr.id) as totalInterviews from feedback_report fr, feedback_request fbr, professionaldetails pd inner join users u on u.id = pd.candidateId " . $rawData . " where fbr.id = fr.feedbackRequestId and pd.candidateId = fbr.candidateId ";
        $countResult = mysqli_query($databaseConnection, $countQuery . $filter_query);
        $countData = mysqli_fetch_assoc($countResult);

        $candidateCountQuery = "Select count(distinct fbr.candidateId) as totalCandidate from feedback_report fr, feedback_request fbr, professionaldetails pd inner join users u on u.id = pd.candidateId " . $rawData . " where fbr.id = fr.feedbackRequestId and pd.candidateId = fbr.candidateId ";
        $candidateCountResult = mysqli_query($databaseConnection, $candidateCountQuery . $filter_query);
        $candidateCountData = mysqli_fetch_assoc($candidateCountResult);

        $areaToImorveComSQuery = "select group_concat(fr.areaToImproveComS SEPARATOR ', ') as areaToImorveComS from feedback_report fr, feedback_request fbr, professionaldetails pd inner join users u on u.id = pd.candidateId " . $rawData . " where fr.areaToImproveComS is not null and fr.areaToImproveComS != 'None' and fbr.id = fr.feedbackRequestId and pd.candidateId = fbr.candidateId ";
        $areaToImorveComSResult = mysqli_query($databaseConnection, $areaToImorveComSQuery . $filter_query);
        $areaToImorveComS = mysqli_fetch_assoc($areaToImorveComSResult);

        $areaToImprovePSSQuery = "select group_concat(fr.areaToImprovePSS SEPARATOR ', ') as areaToImprovePSS from feedback_report fr, feedback_request fbr, professionaldetails pd inner join users u on u.id = pd.candidateId " . $rawData . " where fr.areaToImprovePSS is not null and fr.areaToImprovePSS != 'None' and fbr.id = fr.feedbackRequestId and pd.candidateId = fbr.candidateId ";
        $areaToImprovePSSResult = mysqli_query($databaseConnection, $areaToImprovePSSQuery . $filter_query);
        $areaToImprovePSS = mysqli_fetch_assoc($areaToImprovePSSResult);

        $areaToImproveBSQuery = "select group_concat(fr.areaToImproveBS SEPARATOR ', ') as areaToImproveBS from feedback_report fr, feedback_request fbr, professionaldetails pd inner join users u on u.id = pd.candidateId " . $rawData . " where fr.areaToImproveBS is not null and fr.areaToImproveBS != 'None' and fbr.id = fr.feedbackRequestId and pd.candidateId = fbr.candidateId ";
        $areaToImproveBSResult = mysqli_query($databaseConnection, $areaToImproveBSQuery . $filter_query);
        $areaToImproveBS = mysqli_fetch_assoc($areaToImproveBSResult);

        $areaToImproveCQuery = "select group_concat(fr.areaToImproveC SEPARATOR ', ') as areaToImproveC from feedback_report fr, feedback_request fbr, professionaldetails pd inner join users u on u.id = pd.candidateId " . $rawData . " where fr.areaToImproveC is not null and fr.areaToImproveC != 'None' and fbr.id = fr.feedbackRequestId and pd.candidateId = fbr.candidateId ";
        $areaToImproveCResult = mysqli_query($databaseConnection, $areaToImproveCQuery . $filter_query);
        $areaToImproveC = mysqli_fetch_assoc($areaToImproveCResult);

        $areaToImproveCodSQuery = "select group_concat(fr.areaToImproveCodS SEPARATOR ', ') as areaToImproveCodS from feedback_report fr, feedback_request fbr, professionaldetails pd inner join users u on u.id = pd.candidateId " . $rawData . " where fr.areaToImproveCodS is not null and fr.areaToImproveCodS != 'None' and fbr.id = fr.feedbackRequestId and pd.candidateId = fbr.candidateId ";
        $areaToImproveCodSResult = mysqli_query($databaseConnection, $areaToImproveCodSQuery . $filter_query);
        $areaToImproveCodS = mysqli_fetch_assoc($areaToImproveCodSResult);

        $areaToImproveRSQuery = "select group_concat(fr.areaToImproveRS SEPARATOR ', ') as areaToImproveRS from feedback_report fr, feedback_request fbr, professionaldetails pd inner join users u on u.id = pd.candidateId " . $rawData . "  where fr.areaToImproveRS is not null and fr.areaToImproveRS != 'None' and fbr.id = fr.feedbackRequestId and pd.candidateId = fbr.candidateId ";
        $areaToImproveRSResult = mysqli_query($databaseConnection, $areaToImproveRSQuery . $filter_query);
        $areaToImproveRS = mysqli_fetch_assoc($areaToImproveRSResult);

        $areaToImproveLSQuery = "select group_concat(fr.areaToImproveLS SEPARATOR ', ') as areaToImproveLS from feedback_report fr, feedback_request fbr, professionaldetails pd inner join users u on u.id = pd.candidateId " . $rawData . " where fr.areaToImproveLS is not null and fr.areaToImproveLS != 'None' and fbr.id = fr.feedbackRequestId and pd.candidateId = fbr.candidateId ";
        $areaToImproveLSResult = mysqli_query($databaseConnection, $areaToImproveLSQuery . $filter_query);
        $areaToImproveLS = mysqli_fetch_assoc($areaToImproveLSResult);

        $synchQuery = mysqli_query($databaseConnection, "select synched_at from synch_log where table_name = 'feedback_report' order by id desc limit 0,1");
        $synchResult = mysqli_fetch_assoc($synchQuery);
        $to_encode = array(
            'data' => $data,
            'count' => $countData['totalInterviews'],
            'candidateCount' => $candidateCountData['totalCandidate'],
            'synched_at' => timeAgo($synchResult['synched_at']),
            'college' => array_key_exists('college_id', $college) ? $college['college_id'] : '',
            'collegeName' => array_key_exists('collegeName', $college) ? $college['collegeName'] : '',
            'areaToImorveComS' => getAreaToImproveFromString($areaToImorveComS['areaToImorveComS']),
            'areaToImprovePSS' => getAreaToImproveFromString($areaToImprovePSS['areaToImprovePSS']),
            'areaToImproveBS' => getAreaToImproveFromString($areaToImproveBS['areaToImproveBS']),
            'areaToImproveC' => getAreaToImproveFromString($areaToImproveC['areaToImproveC']),
            'areaToImproveCodS' => getAreaToImproveFromString($areaToImproveCodS['areaToImproveCodS']),
            'areaToImproveRS' => getAreaToImproveFromString($areaToImproveRS['areaToImproveRS']),
            'areaToImproveLS' => getAreaToImproveFromString($areaToImproveLS['areaToImproveLS']),
            'status' => 1
        );
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while getting feedback report"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getCorporateFeedbackSummaryData'])) {
    /* this method is Added by Anuj in jun 2022 */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $filter_query = " ";
        $having_query = " ";
        $limit = $json['limit'];
        $start = ($json['page'] - 1) * ($limit);
        $limit_query = $limit == 0 ? "" : " limit " . $start . "," . $limit;
        $alldata = array();
        $values = array();
        $collegeId = '';
        $order_query = " order by date_format(from_unixtime(floor(fbr.interviewSessionId/1000)),'%Y-%m-%d') DESC,fr.aptitudeScore Desc,fr.communicationSkill DESC";
        $rawData = " ";
        $companyId = '';
        $selectData = '';
        $subjectId = '';


        if ($userType == 'corporate') {
            // $code = mysqli_query($databaseConnection,"SELECT asp.name as compname FROM preInterview cd inner join aspiration_company asp on asp.id=cd.company_Id WHERE cd.userId = ".$userId."");

            $code = mysqli_query($databaseConnection, "SELECT firstName as compname from users WHERE id = " . $userId . "");

            while ($fil = mysqli_fetch_assoc($code)) {

                $letcheck = $fil['compname'];
            }
            $total_data['compname'] = $letcheck;
        }



        if ($userType == 'admin' && $json['interviewname'] != "") {
            $rawData .= " LEFT JOIN company_candidate_interest cci ON cci.candidateId = u.id AND cci.feedbackRequestId = fbr.id";
            $selectData .= "CASE WHEN i.companyId NOT IN (SELECT cd.company_id FROM preInterview cd) THEN 'Event' ELSE 'Goprac' END  as source,cci.status as isInterested,cci.isApproved as isApproved,CASE WHEN i.preInterviewId IN (" . $json['interviewname'] . ") THEN 'yes' ELSE 'no' END as isApply";
        } else if ($userType == 'admin') {
            $rawData .= " LEFT JOIN company_candidate_interest cci ON cci.candidateId = u.id AND cci.feedbackRequestId = fbr.id";
            $selectData .= "CASE WHEN i.companyId NOT IN (SELECT cd.company_id FROM preInterview cd) THEN 'Event' ELSE 'Goprac' END  as source,cci.status as isInterested,cci.isApproved as isApproved";
        }
        if ($userType == 'corporate') {
            // $rawData .= " LEFT JOIN company_candidate_interest cci ON cci.companyId in (SELECT cd.company_id FROM preInterview cd WHERE cd.userId = ".$userId.") AND cci.candidateId = u.id AND cci.feedbackRequestId = fbr.id ";

            $rawData .= " LEFT JOIN company_candidate_interest cci ON cci.companyId in (SELECT cd.company_id FROM preInterview cd WHERE cd.id in (SELECT preinterviewId FROM preInterview_corporate WHERE userId=" . $userId . ")) AND cci.candidateId = u.id AND cci.feedbackRequestId = fbr.id ";

            $filter_query .= " and (isc.recruiterId in (select id from recruiterList where corporateId=" . $userId . ") or FIND_IN_SET('" . $userId . "',u.dataSource))";

            /*  $companyIdData = mysqli_query($databaseConnection,"SELECT cd.company_id FROM preInterview cd WHERE cd.userId = ".$userId."");



             $companyId = mysqli_fetch_all($companyIdData,MYSQLI_ASSOC)[0]['company_id']; */
            // $selectData .= "CASE WHEN i.companyId in (SELECT cd.company_id FROM preInterview cd WHERE cd.userId = ".$userId.") THEN 'Event' ELSE 'Goprac' END  as source,
            // cci.status as isInterested,cci.checkurl as isviewed,
            // CASE WHEN i.companyId in (SELECT cd.company_id FROM preInterview cd WHERE cd.userId = ".$userId.") THEN 'Event' ELSE 'Goprac' END  as source,cci.isApproved as isApproved";
            // if ($json['dataShow'] == 'G') {
            //     $filter_query .= "  AND i.id IN (SELECT isub.id FROM interview isub WHERE isub.companyId IS NULL OR isub.companyId NOT IN (SELECT cd.company_id FROM preInterview cd)) ";
            // }
            // elseif ($json['dataShow'] == 'C') {
            //     $filter_query .= " AND i.id IN (SELECT isub.id FROM interview isub WHERE isub.companyId IN (SELECT cd.company_id FROM preInterview cd WHERE cd.userId = ".$userId."))";
            // }
            // CASE WHEN i.companyId in (SELECT cd.company_id FROM preInterview cd WHERE cd.id in (SELECT preinterviewId FROM preInterview_corporate WHERE userId=".$userId.")) THEN 'Event' ELSE 'Goprac' END  as source,
            $selectData .= "cci.status as isInterested,cci.checkurl as isviewed,
            CASE WHEN i.companyId in (SELECT cd.company_id FROM preInterview cd WHERE cd.id in (SELECT preinterviewId FROM preInterview_corporate WHERE userId=" . $userId . ")) THEN 'Event' ELSE 'Goprac' END  as source,cci.isApproved as isApproved";

            if ($json['dataShow'] == 'G') {
                $filter_query .= "  AND i.id IN (SELECT isub.id FROM interview isub WHERE isub.companyId IS NULL OR isub.companyId NOT IN (SELECT cd.company_id FROM preInterview cd)) ";
            } elseif ($json['dataShow'] == 'C') {
                $filter_query .= " AND i.id IN (SELECT isub.id FROM interview isub WHERE isub.companyId IN (SELECT cd.company_id FROM preInterview cd WHERE cd.id in (SELECT preinterviewId FROM preInterview_corporate WHERE userId=" . $userId . ")))";
            }
        }



        /* $filter_query .= " and fbr.review_status in('2','-4') "; */

        if ($json['college'] != "" and sizeof($json['college']) > 0)
            $filter_query .= " and pd.college in ('" . implode("', '", array_map("addSlashToString", $json['college'])) . "')";
        if ($json['stream'] != "" and sizeof($json['stream']) > 0) {
            $filter_query .= " and pd.specialization in ('" . implode("', '", $json['stream']) . "')";
        }
        if ($json['yop'] != "")
            $filter_query .= " and pd.year in (" . $json['yop'] . ")";

        if ($json['CGPA'] != "")
            $filter_query .= " and pd.cgpa >= " . $json['CGPA'] . "";

        // sibin 7-sept-2022 malpractice count and role filter

        if ($json['Mcount'] != "") {
            $rawData .= " inner join expert_review_observation_details erod on erod.expertReviewId=er.id inner join observation_values ov on ov.id=erod.observationValueId ";
            $filter_query .= " AND i.id IN (SELECT isub.id FROM interview isub WHERE isub.companyId IS NULL OR isub.companyId NOT IN (SELECT cd.company_id FROM preInterview cd)) and er.overAllRating='videoIssue' and erod.observationValueId in (308,442,443) ";
            if ($json['Mcount'] == "5") {
                $having_query .= " and count(er.candidateId) >= " . $json['Mcount'] . "";
            } else {
                $having_query .= " and count(er.candidateId) = " . $json['Mcount'] . "";
            }
        }

        if ($json['role'] != "" and sizeof($json['role']) > 0)
            $filter_query .= " and i.roleId in ('" . implode("', '", array_map("addSlashToString", $json['role'])) . "')";


        $filter = '';

        if ($json['communicationSkill'] != "") {
            $n = implode("', '", array_map("addSlashToString", $json['communicationSkill']));
            if (str_contains($n, 'good')) {
                $filter = " fr.communicationSkill >= 7";
                if (str_contains($n, 'acceptable')) {
                    $filter = " fr.communicationSkill > 4";
                    if (str_contains($n, 'needs improvement')) {
                        $filter = " fr.communicationSkill >= 0";
                    }
                } else if (str_contains($n, 'needs improvement')) {
                    $filter = " fr.communicationSkill >= 7 and fr.communicationSkill <= 4 ";
                }
            } else if (str_contains($n, 'acceptable')) {
                $filter = " fr.communicationSkill > 4 and fr.communicationSkill < 7";
                if (str_contains($n, 'needs improvement')) {
                    $filter = " fr.communicationSkill < 7";
                }
            } else if (str_contains($n, 'needs improvement')) {
                $filter = " fr.communicationSkill <= 4 ";
            }
            $filter_query .= " and " . $filter;
        }


        if ($json['confidence'] != "") {
            $n = implode("', '", array_map("addSlashToString", $json['confidence']));
            if (str_contains($n, 'good')) {
                $filter = " fr.confidence >= 7";
                if (str_contains($n, 'acceptable')) {
                    $filter = " fr.confidence > 4";
                    if (str_contains($n, 'needs improvement')) {
                        $filter = " fr.confidence >= 0";
                    }
                } else if (str_contains($n, 'needs improvement')) {
                    $filter = " fr.confidence >= 7 and fr.confidence <= 4 ";
                }
            } else if (str_contains($n, 'acceptable')) {
                $filter = " fr.confidence > 4 and fr.confidence < 7";
                if (str_contains($n, 'needs improvement')) {
                    $filter = " fr.confidence < 7";
                }
            } else if (str_contains($n, 'needs improvement')) {
                $filter = " fr.confidence <= 4 ";
            }
            $filter_query .= " and " . $filter;
        }


        if ($json['employabilitystatus'] != "" and sizeof($json['employabilitystatus']) > 0)
            $having_query .= " and employabilitystatus in ('" . implode("', '", array_map("addSlashToString", $json['employabilitystatus'])) . "')";

        if ($json['progSubjectsAptLevel'] != '' || $json['cognitiveSubjects'] != '' || $json['behavioralSubjects'] != '') {
            $rawData .= " inner join expert_review er on er.feedback_request_id=fbr.id left join questions q on q.id=er.questionId";

            $filter_query .= " and er.overallRating!='videoIssue'";

        }

        if ($json['cognitiveSubjects'] != '') {
            $subjectId .= "(select ROUND(avg(er.overallRating),1) from expert_review er where er.feedback_request_id=fbr.id and er.questionId in(select id from questions where subjectId in(" . implode(",", $json['cognitiveSubjects']) . ") and er.overallRating!='videoIssue')) as coreoverall,";

            if ($json['cognitiveSubjectsAptLevel'] != '') {
                if ($json['cognitiveSubjectsAptLevel'] === 'good') {
                    $having_query .= " and coreoverall >= 7 ";
                } elseif ($json['cognitiveSubjectsAptLevel'] === 'acceptable') {
                    $having_query .= " and coreoverall < 7 and coreoverall > 4 ";
                } elseif ($json['cognitiveSubjectsAptLevel'] === 'needImprovement') {
                    $having_query .= " and coreoverall <= 4 ";
                }
            }
        }
        if ($json['behavioralSubjects'] != '') {
            $subjectId .= "(select ROUND(avg(er.overallRating),1) from expert_review er where er.feedback_request_id=fbr.id and er.questionId in(select id from questions where subjectId in(" . implode(",", $json['behavioralSubjects']) . ") and er.overallRating!='videoIssue')) as bhevoverall,";

            if ($json['behavioralSubjectsAptLevel'] != '') {
                if ($json['behavioralSubjectsAptLevel'] === 'good') {
                    $having_query .= " and bhevoverall >= 7";
                } elseif ($json['behavioralSubjectsAptLevel'] === 'acceptable') {
                    $having_query .= " and bhevoverall < 7 and bhevoverall > 4";
                } else {
                    $having_query .= " and bhevoverall <= 4";
                }
            }
        }
        if ($json['progSubjects'] != '') {
            $subjectId .= "(select ROUND(avg(er.overallRating),1) from expert_review er where er.feedback_request_id=fbr.id and er.questionId in(select id from questions where subjectId in(" . implode(",", $json['progSubjects']) . ") and er.overallRating!='videoIssue')) as progoverall,";

            if ($json['progSubjectsAptLevel'] != '') {
                if ($json['progSubjectsAptLevel'] === 'good') {
                    $having_query .= " and progoverall >= 7";
                } elseif ($json['progSubjectsAptLevel'] === 'acceptable') {
                    $having_query .= " and progoverall < 7 and progoverall > 4";
                } else {
                    $having_query .= " and progoverall <= 4";
                }
            }
        }

        if ($json['isInterested'] != '') {
            if ($json['isInterested'] === 'yes') {
                $filter_query .= " and cci.status='y'";
            } else if ($json['isInterested'] === 'no') {
                $filter_query .= " and cci.status='n'";
            } else if ($json['isInterested'] === 'maybe') {
                $filter_query .= " and cci.status='m'";

            } else if ($json['isInterested'] === 'selected') {
                $filter_query .= " and cci.status='S'";
            }
        }

        if ($json['isviewed'] != '') {
            if ($json['isviewed'] === 'yes') {
                $filter_query .= " and cci.checkurl='y'";
            } else if ($json['isviewed'] === 'no') {
                $filter_query .= " and cci.checkurl='n'";
            }
        }


        if ($json['joinStatus'] != '') {
            if ($json['joinStatus'] === 'YM') {
                $filter_query .= " and pd.joinstatus in ('Y','M')";
            } else {
                $filter_query .= " and pd.joinstatus in ('" . implode("','", $json['joinStatus']) . "')";
            }
        }

        if ($json['locationList'] != "" and sizeof($json['locationList']) > 0) {
            $filter_query .= " and pd.preferredWorkLocation in (" . implode(", ", array_map("addSlashToString", $json['locationList'])) . ")";
        }

        if (($json['workexpfrom'] != '') && ($json['workexpto'] != '')) {
            $filter_query .= " and pd.workExperience between " . $json['workexpfrom'] . " and " . $json['workexpto'] . " ";
        }

        // 27 sep 2023 - commented by sourabh
        //  also show matching candidates who didnt apply
        // if ($json['interviewname'] != "")
        // $filter_query.=" and i.preInterviewId in (".$json['interviewname'].") ";

        if ($json['candidate_search'] != "") {
            if (preg_match('/^[0-9]{10}+$/', $json['candidate_search'])) {
                $filter_query .= " and u.mobileNumber=" . $json['candidate_search'] . "";
            } else if (filter_var($json['candidate_search'], FILTER_VALIDATE_EMAIL)) {
                $filter_query .= " and u.emailId='" . $json['candidate_search'] . "'";
            } else {
                $filter_query .= " and u.firstName like '%" . $json['candidate_search'] . "%'";
            }
        }

        if ($json['noticePeriod'] != '') {

            $filter_query .= " and pd.noticePeriod in ('" . implode("','", $json['noticePeriod']) . "')";

        }

        //redirection

        // if($json['preId']!='' || $json['recruiterId']!='' || $json['candidateStatus']!=''){
        //     $rawData .= " left outer join interviewSchedule isc on isc.preInterviewId= i.preInterviewId and isc.emailId=u.emailId";
        // }

        if ($json['candidateStatus'] != '') {
            $filter_query .= " and isc.candidateStatus in ('" . implode("','", $json['candidateStatus']) . "')";
        }

        if ($json['preId'] != '') {

            $filter_query .= " and i.preInterviewId =" . $json['preId'] . "";
        } else {
            $filter_query .= " and fbr.interviewId not in(select * from (select i.id from  scps_transaction scp inner join preInterview pi on pi.id=scp.preInterviewId inner join interview i on i.preInterviewId=scp.preInterviewId and i.roleId=scp.position where scp.status='deactive' group by i.id) as t) ";
        }

        if ($json['recruiterId'] != '' && $json['recruiterId'] != 'null') {

            $filter_query .= " and isc.recruiterId=" . $json['recruiterId'] . "";
        }


        if ($json['workreportredirect'] == 'Assessed' || ($json['assessment_from'] != "" && $json['assessment_to'] != "")) {

            $filter_query .= " and fbr.review_status in(2)";
        } else {

            $filter_query .= " and fbr.review_status in(2,-4)";

        }

        if ($json['workreportredirect'] != '' && $json['workreportredirect'] == 'unAttended') {

            $filter_query .= " and (fbr.id is not null and fbr.review_status=2) and (isc.candidateStatus in('UnAttended','Not Attended') or isc.candidateStatus is null) and isc.recruiterId is not null";

        }
        if ($json['workreportredirect'] != '' && $json['workreportredirect'] == 'dropOut') {
            //shrikant changed : 6/3/2024 Client Screen Reject
            $filter_query .= " and (fbr.id is not null and fbr.review_status=2) and (isc.candidateStatus in ('Client Screen Reject','Not interested','Recruiter Reject','No Show','RNR'))";
        }
        if ($json['workreportredirect'] != '' && $json['workreportredirect'] == 'shared') {

            $filter_query .= " and (fbr.id is not null and fbr.review_status=2) and (isc.candidateStatus in ('Profile Shared','shared'))";

        }
        if ($json['workreportredirect'] != '' && $json['workreportredirect'] == 'Offered') {

            $filter_query .= " and (fbr.id is not null and fbr.review_status=2) and (isc.candidateStatus in ('Offered'))";

        }
        if ($json['workreportredirect'] != '' && $json['workreportredirect'] == 'Joined') {

            $filter_query .= " and (fbr.id is not null and fbr.review_status=2) and (isc.candidateStatus in ('Joined'))";

        }
        if ($json['workreportredirect'] != '' && $json['workreportredirect'] == 'clientShortlisted') {

            $filter_query .= " and (fbr.id is not null and fbr.review_status=2) and (isc.candidateStatus in ('Client Shortlisted'))";

        }


        if ($json['assessment_from'] != "" && $json['assessment_to'] != "") {
            $filter_query .= " and fbr.review_status=2";
        }

        if ($json['assessment_from'] != "" && $json['assessment_to'] == "")
            $filter_query .= " and fbr.updatedAt >= '" . $json['assessment_from'] . "'";
        if ($json['assessment_from'] == "" && $json['assessment_to'] != "")
            $filter_query .= " and fbr.updatedAt <= '" . $json['assessment_to'] . "'";
        if ($json['assessment_from'] != "" && $json['assessment_to'] != "")
            $filter_query .= " and fbr.updatedAt >= '" . $json['assessment_from'] . "' and fbr.updatedAt <= '" . $json['assessment_to'] . "'";


        if ($json['candidateStatusFromDate'] != "" && $json['candidateStatusToDate'] == "")
            $filter_query .= " and pd.candidateStatusDate >= '" . $json['candidateStatusFromDate'] . "'";

        if ($json['candidateStatusFromDate'] == "" && $json['candidateStatusToDate'] != "")
            $filter_query .= " and pd.candidateStatusDate <= '" . $json['candidateStatusToDate'] . "'";

        if ($json['candidateStatusFromDate'] != "" && $json['candidateStatusToDate'] != "")
            $filter_query .= " and pd.candidateStatusDate >= '" . $json['candidateStatusFromDate'] . "' and pd.candidateStatusDate <= '" . $json['candidateStatusToDate'] . "'";

        if ($json['apply'] != '') {
            $having_query .= " and isApply in ('" . implode("','", $json['apply']) . "')";
        }

        // for profile match %
        $preferenceResult = mysqli_query($databaseConnection, "SELECT * from profilePreferences where preInterviewId =" . $json['interviewname']);
        if (mysqli_num_rows($preferenceResult) > 0) {
            $total_data['preferences'] = mysqli_fetch_all($preferenceResult, MYSQLI_ASSOC);
        } else {
            $total_data['preferences'] = [];
        }

        /* 
        $query = "select  pd.noticePeriod,pd.currentLocation,pd.salary,pd.workExperience,candidateEmp_status.empstatus as employabilitystatus,fr.aptitudeScore,u.id, concat(u.firstName,u.lastName) as name, u.emailId, u.mobileNumber, pd.college as cl_id, cl.collegeName as college, st.stream as specialization, pd.year,pd.cgpa,u.createdOn as signUpDate, concat('/review?i=',fbr.interviewId,'&c=',fbr.candidateId,'&s=',fbr.interviewSessionId) as url,pd.specialization as str_id,fbr.interviewSessionId as sessionId, i.name as interview_name, i.id as intId, fbr.id as fbr_id, fbr.review_status as fbr_status,(SELECT l.cityName from locations l where l.id=pd.currentLocation) as currentLocation, 
        (SELECT CONCAT(ROUND(AVG(er.overallRating),1),'/10') FROM expert_review er WHERE er.review_type = 'question' AND er.feedback_request_id = fbr.id) as subjectKnowledgeScore,           
        fbr.viewAssessment,fr.finalOpinion, fr.communicationSkill, fr.problemSolvingSkill, fr.behaviouralSkill, fr.confidence, fr.codingSkill, fr.readingSkill, fr.listeningSkill, fr.rComprehensionSkill, fr.presentationSkill, fr.grammerSkill, fr.expertAdvice,pd.fav_subjects as fav_subjectId,pd.fav_programming_skill as fav_programming_skillId,pd.languages as languageKnownId,pd.internship,pd.asp_companies as asp_companiesId,
        ".$selectData." from  expert_review er INNER JOIN users u ON u.id = er.candidateId inner join professionaldetails pd on pd.candidateId=u.id LEFT JOIN stream st on pd.specialization = st.id left outer join colleges cl on cl.id = pd.college INNER JOIN interview i ON er.interviewId = i.id INNER JOIN feedback_request fbr ON fbr.id = er.feedback_request_id inner join feedback_report fr on fr.feedbackRequestId = fbr.id LEFT OUTER JOIN questions q ON er.questionId = q.id LEFT JOIN favourite_subject fs ON fs.id = q.subjectId " . $rawData . " left outer join candidateEmp_status on fbr.candidateId = candidateEmp_status.candidateId where u.active = 'Y' and u.deleted_at is null "; */

        // query last modified by arun on 27/10/2022 to show both completed,malpractice and stepper rejected interviews

        $query = "select " . $subjectId . " isc.emailId as scheduleEmail,pr.id as preInterviewId,u.id,pd.assignMentorId,isc.candidateStatus,isc.candidateStatusDate,pd.resumeSharedCompany,pd.candidateFeedback,pd.resumeSharedDate,i.assessmenttype as assessmenttype,i.companyId,fbr.reasonOfRejection as reasonOfRejection,(CASE WHEN (fbr.review_status =-4 and fbr.reasonOfRejection ='studentIsIndulgedInMalpractice') THEN 'Malpractice' WHEN (fbr.review_status =-4 and fbr.reasonOfRejection ='Behavioural subject needs improvment') THEN 'Not Applicable' when fr.aptitudeScore=-998 then 'Partially Assessed' when fr.aptitudeScore=-996 then 'Stepper Rejected' Else fr.aptitudeScore END) as aptitudeScore,
        (CASE when fr.aptitudeScore=-998 then 'May Be Fit' when fr.aptitudeScore=-997 then 'May Be Fit' when fr.aptitudeScore=-996 then 'Not Fit'  when (fbr.review_status !=-4 and fr.aptitudeScore>=7) then 'Best Fit' when (fbr.review_status !=-4 and (fr.aptitudeScore<7 and fr.aptitudeScore>4)) then 'Possible Fit' when (fbr.review_status !=-4 and fr.aptitudeScore<=4) then 'Not Fit' WHEN fbr.review_status=-4 and fbr.reasonOfRejection in('studentIsIndulgedInMalpractice') THEN 'Not Fit' Else candidateEmp_status.empstatus END) as employabilitystatus,pd.noticePeriod,pd.workLocationPreference,pd.shift,pd.skills,pd.currentLocation,pd.jobType,CONCAT(pd.salary,'/',pd.expectedSalary) as expectedSalary,pd.workExperience, concat(u.firstName,u.lastName) as name, u.emailId, u.mobileNumber, pd.college as cl_id, cl.collegeName as college, st.stream as specialization, pd.year,pd.cgpa,u.createdOn as signUpDate, concat('/review?i=',fbr.interviewId,'&c=',fbr.candidateId,'&s=',fbr.interviewSessionId) as url,pd.specialization as str_id,fbr.interviewSessionId as sessionId, case when pr.interviewName is null then ac.name else pr.interviewName end as interview_name, i.id as intId, fbr.id as fbr_id, fbr.review_status as fbr_status,(SELECT l.cityName from locations l where l.id=pd.currentLocation) as currLocation, (SELECT CONCAT(ROUND(AVG(er.overallRating),1),'/10') FROM expert_review er WHERE er.review_type = 'question' AND er.feedback_request_id = fbr.id) as subjectKnowledgeScore, fbr.viewAssessment,fr.finalOpinion, fr.communicationSkill, fr.problemSolvingSkill, fr.behaviouralSkill, fr.confidence, fr.codingSkill, fr.readingSkill, fr.listeningSkill, fr.rComprehensionSkill, fr.presentationSkill, fr.grammerSkill, fr.expertAdvice,pd.fav_subjects as fav_subjectId,pd.fav_programming_skill as fav_programming_skillId,pd.languages as languageKnownId,pd.internship,pd.asp_companies as asp_companiesId,pr.hiringCompanies,round(sm.technical,2) as technical,round(sm.coding,2) as coding,round(sm.soft,2) as soft," . $selectData . " from 
        feedback_request fbr left outer join interview i on fbr.interviewId = i.id left outer join feedback_report fr on fr.feedbackRequestId = fbr.id left outer join favourite_subject fv on fv.id = i.subject_id left outer join category cat on i.categoryType = cat.id left outer join users u on u.id = fbr.candidateId left outer join interviewSchedule isc on isc.preInterviewId= i.preInterviewId and isc.emailId=u.emailId left outer join professionaldetails pd on pd.candidateId=u.id left outer join stream st on pd.specialization = st.id left outer join colleges cl on cl.id=pd.college left outer join candidateEmp_status on candidateEmp_status.candidateId=fbr.candidateId left outer join preInterview pr on pr.id=i.preInterviewId left outer join aspiration_company ac on ac.id = i.companyId left outer join (select feedbackRequestId,max(case when (subjectType='technical') then skillPercent else NULL end) as 'technical',max(case when (subjectType='coding') then skillPercent else NULL end) as 'coding',max(case when (subjectType='soft') then skillPercent else NULL end) as 'soft' from skillMatch group by feedbackRequestId order by feedbackRequestId) sm on sm.feedbackRequestId=fbr.id" . $rawData . " where fbr.interviewSessionId is not null and (fbr.reasonOfRejection in('Behavioural subject needs improvment','studentIsIndulgedInMalpractice') or fbr.reasonOfRejection is null) ";


        $data = $query . $filter_query . " group by fbr.interviewSessionId  having 1 " . $having_query . $order_query;

        $countData = $query . $filter_query . " group by fbr.interviewSessionId  having 1 " . $having_query . $order_query;

        if ($data != '') {
            $count_query = mysqli_query($databaseConnection, $countData);
            $query_sql = "SELECT tp.*,skillMatch(tp.id,tp.preInterviewId) as skillMatch FROM ( " . $data . $limit_query . " ) as tp";
            // echo $query_sql;
            // exit();
            $query = mysqli_query($databaseConnection, $query_sql);

            $synchQuery = mysqli_query($databaseConnection, "select synched_at from synch_log where table_name = 'feedback_report' order by id desc limit 0,1");
            $synchResult = mysqli_fetch_assoc($synchQuery);

            if (mysqli_num_rows($query) > 0) {
                $reviewData = array();
                while ($queryDataRow = mysqli_fetch_assoc($query)) {
                    // if ($queryDataRow['intId']!='' && $queryDataRow['intId']!=null){
                    //     $subjectResult = mysqli_query($databaseConnection,"select fs.id,scps.weightage from interview_questions_transection iqt inner join questions q on q.id=iqt.questionId inner join favourite_subject fs on fs.id=q.subjectId left join scps_transaction scps on scps.subject=q.subjectId where iqt.interviewId=".$queryDataRow['intId']." and iqt.sectionName!='ThankYou' group by fs.id;");
                    // if (mysqli_num_rows($subjectResult)>0) {
                    //     $queryDataRow['subjects'] = mysqli_fetch_all($subjectResult,MYSQLI_ASSOC);
                    // } else {
                    //     $queryDataRow['subjects'] = [];
                    // }
                    // }else{
                    //     $queryDataRow['subjects'] = [];
                    // }

                    // if ($queryDataRow['fbr_id']!='' && $queryDataRow['fbr_id']!=null){
                    //     $subjectScoreResult = mysqli_query($databaseConnection,"select subject,subjectScore from subjectWiseScores where feedbackRequestId=".$queryDataRow['fbr_id']."");
                    // if (mysqli_num_rows($subjectScoreResult)>0) {
                    //     $queryDataRow['subjectscore'] = mysqli_fetch_all($subjectScoreResult,MYSQLI_ASSOC);
                    // } else {
                    //     $queryDataRow['subjectscore'] = [];
                    // }
                    // }else{
                    //     $queryDataRow['subjectscore'] = [];
                    // }
                    // 

                    $favSubjectResult = mysqli_query($databaseConnection, "SELECT GROUP_CONCAT(fs.favourite_subject) as favourite_subject FROM favourite_subject fs WHERE fs.id IN (" . $queryDataRow['fav_subjectId'] . ");");
                    if ($favSubjectResult && mysqli_num_rows($favSubjectResult)) {
                        $queryDataRow['favourite_subject'] = mysqli_fetch_all($favSubjectResult, MYSQLI_ASSOC)[0]['favourite_subject'];
                    } else {
                        $queryDataRow['favourite_subject'] = '';
                    }
                    $favProgResult = mysqli_query($databaseConnection, "SELECT GROUP_CONCAT(fs.favourite_subject) as favourite_prog FROM favourite_subject fs WHERE fs.id IN (" . $queryDataRow['fav_programming_skillId'] . ");");
                    if ($favProgResult && mysqli_num_rows($favProgResult)) {
                        $queryDataRow['favourite_prog'] = mysqli_fetch_all($favProgResult, MYSQLI_ASSOC)[0]['favourite_prog'];
                    } else {
                        $queryDataRow['favourite_prog'] = '';
                    }
                    $langKnownResult = mysqli_query($databaseConnection, "SELECT GROUP_CONCAT(l.name) as languageKnown FROM `language` l WHERE l.id IN (" . $queryDataRow['languageKnownId'] . ");");
                    if ($langKnownResult && mysqli_num_rows($langKnownResult)) {
                        $queryDataRow['languageKnown'] = mysqli_fetch_all($langKnownResult, MYSQLI_ASSOC)[0]['languageKnown'];
                    } else {
                        $queryDataRow['languageKnown'] = '';
                    }

                    $aspCompanyResult = mysqli_query($databaseConnection, "SELECT GROUP_CONCAT(ac.name) as asp_companies FROM aspiration_company ac WHERE ac.id IN (" . $queryDataRow['asp_companiesId'] . ");");
                    if ($aspCompanyResult && mysqli_num_rows($aspCompanyResult) > 0) {
                        $queryDataRow['asp_companies'] = mysqli_fetch_all($aspCompanyResult, MYSQLI_ASSOC)[0]['asp_companies'];
                    } else {
                        $queryDataRow['asp_companies'] = '';
                    }

                    if ($userType == 'admin') {
                        $intCompanyResult = mysqli_query($databaseConnection, "SELECT cci.*,ac.name as companyName FROM company_candidate_interest cci LEFT JOIN aspiration_company ac ON cci.companyId = ac.id WHERE cci.candidateId = " . $queryDataRow['id'] . " AND cci.feedbackRequestId = " . $queryDataRow['fbr_id'] . " ");
                        if ($intCompanyResult && mysqli_num_rows($intCompanyResult) > 0) {
                            $queryDataRow['interestedCompanies'] = mysqli_fetch_all($intCompanyResult, MYSQLI_ASSOC);
                        } else {
                            $queryDataRow['interestedCompanies'] = [];
                        }
                    }
                    if ($userType == 'corporate') {
                        $queryDataRow['interestedCompanies'] = [];
                    }

                    $mcount = mysqli_query($databaseConnection, "select count(er.feedback_request_id) as malpractcount from expert_review er inner join expert_review_observation_details erod on erod.expertReviewId=er.id inner join observation_values ov on ov.id=erod.observationValueId where erod.observationValueId in (308,442,443) and er.feedback_request_id = " . $queryDataRow['fbr_id'] . " group by er.candidateId");
                    if (mysqli_num_rows($mcount) >= 1) {
                        $queryDataRow['malpracticeCount'] = mysqli_fetch_assoc($mcount)['malpractcount'];
                    } else {
                        $queryDataRow['malpracticeCount'] = null;
                    }

                    $mandatoryQuestionsSkipped = mysqli_query($databaseConnection, "SELECT COUNT(CASE WHEN iqt.attemptStatus='Skip' THEN 1 ELSE NULL END) AS mandatory_skipped  FROM interview_questions_transection iqt INNER JOIN questions q ON q.id = iqt.questionId WHERE q.subjectId<> 178 AND iqt.interviewId=" . $queryDataRow['intId'] . "");
                    if (mysqli_num_rows($mandatoryQuestionsSkipped) > 0) {
                        $result = mysqli_fetch_assoc($mandatoryQuestionsSkipped);
                        $queryDataRow['mandatoryQuestionsSkipped'] = $result['mandatory_skipped'];

                    } else {
                        $queryDataRow['mandatoryQuestionsSkipped'] = '0';
                    }

                    //to get speechAce skill score

                    $skill_score = mysqli_query($databaseConnection, "select t.*,case when t.speakingScore is not null and t.speakingScore=1 then '<A1' when t.speakingScore is not null and t.speakingScore=2 then 'A2' when t.speakingScore is not null and t.speakingScore=3 then 'A2' when t.speakingScore is not null and t.speakingScore=4 then 'A2+' when t.speakingScore is not null and t.speakingScore=5 then 'B1' when t.speakingScore is not null and t.speakingScore=6 then 'B1+' when t.speakingScore is not null and t.speakingScore=7 then 'B2' when t.speakingScore is not null and t.speakingScore=8 then 'B2+' when t.speakingScore is not null and t.speakingScore=9 then 'C1' when t.speakingScore is not null and t.speakingScore=10 then 'C2' when t.speakingScore is null then null end as CERF_score from (SELECT ROUND(AVG(CASE WHEN ks.id = 16 THEN ov.observation_values END), 1)as 'Fluency',ROUND(AVG(CASE WHEN ks.id = 17 THEN ov.observation_values END), 1) as 'Pronunciation',ROUND(AVG(CASE WHEN ks.id = 18 THEN ov.observation_values END), 1) as 'Vocabulary',ROUND(AVG(CASE WHEN ks.id = 19 THEN ov.observation_values END), 1) as 'Sentence Mastery',(select ROUND(AVG(er.overallRating)) as speakingScore from expert_review er inner join questions q on q.id=er.questionId where er.feedback_request_id=" . $queryDataRow['fbr_id'] . " and q.subjectId=178 and er.overAllRating!='videoIssue') as speakingScore FROM expert_review_observation_details as erod INNER JOIN observation_area as oa ON oa.id = erod.observationAreaId INNER JOIN expert_review as er ON er.id = erod.expertReviewId INNER JOIN feedback_request fr ON fr.id = er.feedback_request_id INNER JOIN key_skill as ks ON ks.id = oa.key_skill LEFT OUTER JOIN observation_values as ov ON ov.id = erod.observationValueId WHERE oa.observation_name != 'Issue Type' AND er.feedback_request_id = " . $queryDataRow['fbr_id'] . " AND er.subjectTag IS NULL AND ks.status = 'Yes' AND ks.id != 4 GROUP BY er.feedback_request_id ORDER BY er.feedback_request_id) as t");

                    if (mysqli_num_rows($skill_score) > 0) {
                        $queryDataRow['skillScore'] = mysqli_fetch_all($skill_score, MYSQLI_ASSOC);
                    } else {
                        $queryDataRow['skillScore'] = null;
                    }


                    array_push($reviewData, $queryDataRow);
                }
                $total_data['data'] = $reviewData;
                $total_data['count'] = mysqli_num_rows($count_query);
                $total_data['synched_at'] = timeAgo($synchResult['synched_at']);
                $total_data['college'] = $collegeId;
                $to_encode = $total_data;
            } else {
                $to_encode = array(
                    'result' => "error",
                    'status' => 0,
                    'errorCode' => "in Error while retrieving Student information."
                );
            }
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "in Error You are not having access this page."
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving Student information"
        );
    }
    echo json_encode($to_encode);

} elseif (isset($_GET['getFeedbackReportData'])) {
    /* this method is updated by narayan Jan 2022 */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $filter_query = "";
        $college = array();
        $rawData = " ";

        if ($json['stream'] != "" && sizeof($json['stream']) > 0)
            $filter_query .= " and pd.specialization in ('" . implode("', '", $json['stream']) . "')";
        if ($json['yop'] != "")
            $filter_query .= " and pd.year in (" . $json['yop'] . ")";
        if ($json['from_date'] != "" && $json['to_date'] == "")
            $filter_query .= " and fbr.interviewSessionId >= '" . strtotime($json['from_date']) . "'";
        if ($json['from_date'] == "" && $json['to_date'] != "")
            $filter_query .= " and fbr.interviewSessionId <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";
        if ($json['from_date'] != "" && $json['to_date'] != "")
            $filter_query .= " and fbr.interviewSessionId >= '" . strtotime($json['from_date']) . "' and fbr.interviewSessionId <= '" . strtotime('+1 day', strtotime($json['to_date'])) . "'";
        if ($json['isTieUpStatus'] != "") {
            $rawData .= " inner join raw_data rd on rd.email_id = u.emailId ";
            if ($json['isTieUpStatus'] == 'Y') {
                $filter_query .= " and rd.isPaid = 'Y'";
            } else {
                $filter_query .= " and rd.isPaid = 'N'";
            }
        }
        if ($userType == 'college') {
            $college_query = mysqli_query($databaseConnection, "select u1.* from users u1 where u1.id =" . $json['userId'] . " ");
            $college_result = mysqli_fetch_array($college_query, MYSQLI_ASSOC);
            $filter_query .= " and pd.college in (" . $college_result['college_id'] . ")";
        }
        if ($userType == 'mentor') {
            $filter_query .= " and pd.assignMentorId in (" . $json['userId'] . ")";
        }
        if ($json['college'] != "" and sizeof($json['college']) > 0) {
            $filter_query .= " and pd.college in ('" . implode("', '", array_map("addSlashToString", $json['college'])) . "')";
            $college_query = mysqli_query($databaseConnection, "SELECT GROUP_CONCAT(collegeName SEPARATOR ', ') as collegeName FROM `colleges` WHERE id in ('" . implode("', '", array_map("addSlashToString", $json['college'])) . "') ");
            $college = mysqli_fetch_array($college_query, MYSQLI_ASSOC);
        }

        $query = "select 
               SUM(CASE WHEN fr.communicationSkill >= 7 THEN 1 ELSE 0 END) as communicationSkillGood,
               SUM(CASE WHEN fr.communicationSkill > 4  AND fr.communicationSkill < 7 THEN 1 ELSE 0 END) as communicationSkillAcceptable,
               SUM(CASE WHEN fr.communicationSkill <= 4 THEN 1 ELSE 0 END) as communicationSkillNeedsImprovement,
               SUM(CASE WHEN fr.problemSolvingSkill >= 7 THEN 1 ELSE 0 END) as problemSolvingSkillGood,
               SUM(CASE WHEN fr.problemSolvingSkill > 4 AND fr.problemSolvingSkill < 7 THEN 1 ELSE 0 END) as problemSolvingSkillAcceptable,
               SUM(CASE WHEN fr.problemSolvingSkill <= 4 THEN 1 ELSE 0 END) as problemSolvingSkillNeedsImprovement,
               SUM(CASE WHEN fr.behaviouralSkill >= 7 THEN 1 ELSE 0 END) as behaviouralSkillGood,
               SUM(CASE WHEN fr.behaviouralSkill > 4 AND fr.behaviouralSkill < 7 THEN 1 ELSE 0 END) as behaviouralSkillAcceptable,
               SUM(CASE WHEN fr.behaviouralSkill <= 4 THEN 1 ELSE 0 END) as behaviouralSkillNeedsImprovement,
               SUM(CASE WHEN fr.confidence >= 7 THEN 1 ELSE 0 END) as confidenceGood,
               SUM(CASE WHEN fr.confidence > 4 AND fr.confidence < 7 THEN 1 ELSE 0 END) as confidenceAcceptable,
               SUM(CASE WHEN fr.confidence <= 4 THEN 1 ELSE 0 END) as confidenceNeedsImprovement,
               SUM(CASE WHEN fr.codingSkill >= 7 THEN 1 ELSE 0 END) as codingSkillGood,
               SUM(CASE WHEN fr.codingSkill > 4 AND fr.codingSkill < 7 THEN 1 ELSE 0 END) as codingSkillAcceptable,
               SUM(CASE WHEN fr.codingSkill <= 4 THEN 1 ELSE 0 END) as codingSkillNeedsImprovement,
               SUM(CASE WHEN fr.readingSkill >= 7 THEN 1 ELSE 0 END) as readingSkillGood,
               SUM(CASE WHEN fr.readingSkill > 4 AND fr.readingSkill < 7 THEN 1 ELSE 0 END) as readingSkillAcceptable,
               SUM(CASE WHEN fr.readingSkill <= 4 THEN 1 ELSE 0 END) as readingSkillNeedsImprovement,
               SUM(CASE WHEN fr.listeningSkill >= 7 THEN 1 ELSE 0 END) as listeningSkillGood,
               SUM(CASE WHEN fr.listeningSkill > 4 AND fr.listeningSkill < 7 THEN 1 ELSE 0 END) as listeningSkillAcceptable,
               SUM(CASE WHEN fr.listeningSkill <= 4 THEN 1 ELSE 0 END) as listeningSkillNeedsImprovement
               from feedback_report fr, feedback_request fbr, professionaldetails pd inner join users u on u.id = pd.candidateId " . $rawData . " where fbr.id = fr.feedbackRequestId and pd.candidateId = fbr.candidateId ";
        $result = mysqli_query($databaseConnection, $query . $filter_query);
        $data = mysqli_fetch_all($result, MYSQLI_ASSOC);

        $countQuery = "Select count(fr.id) as totalInterviews from feedback_report fr, feedback_request fbr, professionaldetails pd inner join users u on u.id = pd.candidateId " . $rawData . " where fbr.id = fr.feedbackRequestId and pd.candidateId = fbr.candidateId ";
        $countResult = mysqli_query($databaseConnection, $countQuery . $filter_query);
        $countData = mysqli_fetch_assoc($countResult);

        $candidateCountQuery = "Select count(distinct fbr.candidateId) as totalCandidate from feedback_report fr, feedback_request fbr, professionaldetails pd inner join users u on u.id = pd.candidateId " . $rawData . " where fbr.id = fr.feedbackRequestId and pd.candidateId = fbr.candidateId ";
        $candidateCountResult = mysqli_query($databaseConnection, $candidateCountQuery . $filter_query);
        $candidateCountData = mysqli_fetch_assoc($candidateCountResult);

        $areaToImorveComSQuery = "select group_concat(fr.areaToImproveComS SEPARATOR ', ') as areaToImorveComS from feedback_report fr, feedback_request fbr, professionaldetails pd inner join users u on u.id = pd.candidateId " . $rawData . " where fr.areaToImproveComS is not null and fr.areaToImproveComS != 'None' and fbr.id = fr.feedbackRequestId and pd.candidateId = fbr.candidateId ";
        $areaToImorveComSResult = mysqli_query($databaseConnection, $areaToImorveComSQuery . $filter_query);
        $areaToImorveComS = mysqli_fetch_assoc($areaToImorveComSResult);

        $areaToImprovePSSQuery = "select group_concat(fr.areaToImprovePSS SEPARATOR ', ') as areaToImprovePSS from feedback_report fr, feedback_request fbr, professionaldetails pd inner join users u on u.id = pd.candidateId " . $rawData . " where fr.areaToImprovePSS is not null and fr.areaToImprovePSS != 'None' and fbr.id = fr.feedbackRequestId and pd.candidateId = fbr.candidateId ";
        $areaToImprovePSSResult = mysqli_query($databaseConnection, $areaToImprovePSSQuery . $filter_query);
        $areaToImprovePSS = mysqli_fetch_assoc($areaToImprovePSSResult);

        $areaToImproveBSQuery = "select group_concat(fr.areaToImproveBS SEPARATOR ', ') as areaToImproveBS from feedback_report fr, feedback_request fbr, professionaldetails pd inner join users u on u.id = pd.candidateId " . $rawData . " where fr.areaToImproveBS is not null and fr.areaToImproveBS != 'None' and fbr.id = fr.feedbackRequestId and pd.candidateId = fbr.candidateId ";
        $areaToImproveBSResult = mysqli_query($databaseConnection, $areaToImproveBSQuery . $filter_query);
        $areaToImproveBS = mysqli_fetch_assoc($areaToImproveBSResult);

        $areaToImproveCQuery = "select group_concat(fr.areaToImproveC SEPARATOR ', ') as areaToImproveC from feedback_report fr, feedback_request fbr, professionaldetails pd inner join users u on u.id = pd.candidateId " . $rawData . " where fr.areaToImproveC is not null and fr.areaToImproveC != 'None' and fbr.id = fr.feedbackRequestId and pd.candidateId = fbr.candidateId ";
        $areaToImproveCResult = mysqli_query($databaseConnection, $areaToImproveCQuery . $filter_query);
        $areaToImproveC = mysqli_fetch_assoc($areaToImproveCResult);

        $areaToImproveCodSQuery = "select group_concat(fr.areaToImproveCodS SEPARATOR ', ') as areaToImproveCodS from feedback_report fr, feedback_request fbr, professionaldetails pd inner join users u on u.id = pd.candidateId " . $rawData . " where fr.areaToImproveCodS is not null and fr.areaToImproveCodS != 'None' and fbr.id = fr.feedbackRequestId and pd.candidateId = fbr.candidateId ";
        $areaToImproveCodSResult = mysqli_query($databaseConnection, $areaToImproveCodSQuery . $filter_query);
        $areaToImproveCodS = mysqli_fetch_assoc($areaToImproveCodSResult);

        $areaToImproveRSQuery = "select group_concat(fr.areaToImproveRS SEPARATOR ', ') as areaToImproveRS from feedback_report fr, feedback_request fbr, professionaldetails pd inner join users u on u.id = pd.candidateId " . $rawData . "  where fr.areaToImproveRS is not null and fr.areaToImproveRS != 'None' and fbr.id = fr.feedbackRequestId and pd.candidateId = fbr.candidateId ";
        $areaToImproveRSResult = mysqli_query($databaseConnection, $areaToImproveRSQuery . $filter_query);
        $areaToImproveRS = mysqli_fetch_assoc($areaToImproveRSResult);

        $areaToImproveLSQuery = "select group_concat(fr.areaToImproveLS SEPARATOR ', ') as areaToImproveLS from feedback_report fr, feedback_request fbr, professionaldetails pd inner join users u on u.id = pd.candidateId " . $rawData . " where fr.areaToImproveLS is not null and fr.areaToImproveLS != 'None' and fbr.id = fr.feedbackRequestId and pd.candidateId = fbr.candidateId ";
        $areaToImproveLSResult = mysqli_query($databaseConnection, $areaToImproveLSQuery . $filter_query);
        $areaToImproveLS = mysqli_fetch_assoc($areaToImproveLSResult);

        $synchQuery = mysqli_query($databaseConnection, "select synched_at from synch_log where table_name = 'feedback_report' order by id desc limit 0,1");
        $synchResult = mysqli_fetch_assoc($synchQuery);
        $to_encode = array(
            'data' => $data,
            'count' => $countData['totalInterviews'],
            'candidateCount' => $candidateCountData['totalCandidate'],
            'synched_at' => timeAgo($synchResult['synched_at']),
            'college' => array_key_exists('college_id', $college) ? $college['college_id'] : '',
            'collegeName' => array_key_exists('collegeName', $college) ? $college['collegeName'] : '',
            'areaToImorveComS' => getAreaToImproveFromString($areaToImorveComS['areaToImorveComS']),
            'areaToImprovePSS' => getAreaToImproveFromString($areaToImprovePSS['areaToImprovePSS']),
            'areaToImproveBS' => getAreaToImproveFromString($areaToImproveBS['areaToImproveBS']),
            'areaToImproveC' => getAreaToImproveFromString($areaToImproveC['areaToImproveC']),
            'areaToImproveCodS' => getAreaToImproveFromString($areaToImproveCodS['areaToImproveCodS']),
            'areaToImproveRS' => getAreaToImproveFromString($areaToImproveRS['areaToImproveRS']),
            'areaToImproveLS' => getAreaToImproveFromString($areaToImproveLS['areaToImproveLS']),
            'status' => 1
        );
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while getting feedback report"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['updateFeedbackReportData'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    /*select i.id,c.name as categoryName, m.id as menu_id , 
,c.name as concept_name from `interview` i inner join category c on i.categoryType = c.id left outer join favourite_subject fs on i.subject_id = fs.id left outer join menu_subject_transection mst on fs.id = mst.subject_id left outer join menu m on mst.menu_id = m.id left outer join concepts cp on cp.id = i.concept_id where i.deleted_at is null and i.isActive='Y' and i.categoryType in (1,2,6,7,8)  and m.name = 'Mock Interviews' order by block_status  desc;*/

    /* this method is updated  by Narayan Jan 2022 */

    if (isset($json)) {
        $synchQuery = "INSERT INTO `synch_log` (`table_name`, `synched_at`) VALUES ('feedback_report', '" . date('Y-m-d H:i:s') . "');";
        mysqli_query($databaseConnection, $synchQuery);

        $condition = "fbr.id not in (select feedbackRequestId from feedback_report) and ";
        $feedbackReportData = getFeedbackReport($databaseConnection, $condition);

        $condition2 = "fbr.id  in (select feedbackRequestId from feedback_report) and ";
        $feedbackReportData2 = getFeedbackReport($databaseConnection, $condition2);

        if (array_key_exists(0, $feedbackReportData)) {
            for ($i = 0; $i < count($feedbackReportData); $i++) {
                $query = "INSERT INTO `feedback_report`(`feedbackRequestId`, `finalOpinion`, `communicationSkill`, `areaToImproveComS`, `durationOfPracticeComS`, `problemSolvingSkill`, `areaToImprovePSS`, `durationOfPracticePSS`, `behaviouralSkill`, `areaToImproveBS`, `durationOfPracticeBS`, `confidence`, `areaToImproveC`, `durationOfPracticeC`, `codingSkill`, `areaToImproveCodS`, `durationOfPracticeCodS`, `readingSkill`, `areaToImproveRS`, `durationOfPracticeRS`, `listeningSkill`, `areaToImproveLS`, `durationOfPracticeLS`, `rComprehensionSkill`, `areaToImproveRCS`, `durationOfPracticeRCS`, `presentationSkill`, `areaToImprovePS`, `durationOfPracticePS`, `grammerSkill`, `areaToImproveGVS`, `durationOfPracticeGVS`, `expertAdvice`,`whatIsGoodComS`,`whatIsGoodPSS`,`whatIsGoodBS`,`whatIsGoodC`,`whatIsGoodCodS`,`whatIsGoodRS`,`whatIsGoodLS`,`whatIsGoodRCS`,`whatIsGoodPS`,`whatIsGoodGVS`,`aptitudeScore`) VALUES ('" . $feedbackReportData[$i]['feedbackRequestId'] . "', NULLIF('" . $feedbackReportData[$i]['finalOpinion'] . "', ''), NULLIF('" . $feedbackReportData[$i]['communicationSkill'] . "', ''), NULLIF('" . $feedbackReportData[$i]['areaToImproveComS'] . "', ''), NULLIF('" . $feedbackReportData[$i]['durationOfPracticeComS'] . "', ''), NULLIF('" . $feedbackReportData[$i]['problemSolvingSkill'] . "', ''), NULLIF('" . $feedbackReportData[$i]['areaToImprovePSS'] . "', ''), NULLIF('" . $feedbackReportData[$i]['durationOfPracticePSS'] . "', ''), NULLIF('" . $feedbackReportData[$i]['behaviouralSkill'] . "', ''), NULLIF('" . $feedbackReportData[$i]['areaToImproveBS'] . "', ''), NULLIF('" . $feedbackReportData[$i]['durationOfPracticeBS'] . "', ''), NULLIF('" . $feedbackReportData[$i]['confidence'] . "', ''), NULLIF('" . $feedbackReportData[$i]['areaToImproveC'] . "', ''), NULLIF('" . $feedbackReportData[$i]['durationOfPracticeC'] . "', ''), NULLIF('" . $feedbackReportData[$i]['codingSkill'] . "', ''), NULLIF('" . $feedbackReportData[$i]['areaToImproveCodS'] . "', ''), NULLIF('" . $feedbackReportData[$i]['durationOfPracticeCodS'] . "', ''), NULLIF('" . $feedbackReportData[$i]['readingSkill'] . "', ''), NULLIF('" . $feedbackReportData[$i]['areaToImproveRS'] . "', ''), NULLIF('" . $feedbackReportData[$i]['durationOfPracticeRS'] . "', ''), NULLIF('" . $feedbackReportData[$i]['listeningSkill'] . "', ''), NULLIF('" . $feedbackReportData[$i]['areaToImproveLS'] . "', ''), NULLIF('" . $feedbackReportData[$i]['durationOfPracticeLS'] . "', ''), NULLIF('" . $feedbackReportData[$i]['rComprehensionSkill'] . "', ''), NULLIF('" . $feedbackReportData[$i]['areaToImproveRCS'] . "', ''), NULLIF('" . $feedbackReportData[$i]['durationOfPracticeRCS'] . "', ''), NULLIF('" . $feedbackReportData[$i]['presentationSkill'] . "', ''), NULLIF('" . $feedbackReportData[$i]['areaToImprovePS'] . "', ''), NULLIF('" . $feedbackReportData[$i]['durationOfPracticePS'] . "', ''), NULLIF('" . $feedbackReportData[$i]['grammerSkill'] . "', ''), NULLIF('" . $feedbackReportData[$i]['areaToImproveGVS'] . "', ''), NULLIF('" . $feedbackReportData[$i]['durationOfPracticeGVS'] . "', ''), NULLIF('" . addslashes($feedbackReportData[$i]['expertAdvice']) . "', ''),NULLIF('" . $feedbackReportData[$i]['whatIsGoodComS'] . "', ''),NULLIF('" . $feedbackReportData[$i]['whatIsGoodPSS'] . "', ''),NULLIF('" . $feedbackReportData[$i]['whatIsGoodBS'] . "', ''),NULLIF('" . $feedbackReportData[$i]['whatIsGoodC'] . "', ''),NULLIF('" . $feedbackReportData[$i]['whatIsGoodCodS'] . "', ''),NULLIF('" . $feedbackReportData[$i]['whatIsGoodRS'] . "', ''),NULLIF('" . $feedbackReportData[$i]['whatIsGoodLS'] . "', ''),NULLIF('" . $feedbackReportData[$i]['whatIsGoodRCS'] . "', ''),NULLIF('" . $feedbackReportData[$i]['whatIsGoodPS'] . "', ''),NULLIF('" . $feedbackReportData[$i]['whatIsGoodGVS'] . "', ''),NULLIF('" . $feedbackReportData[$i]['aptitudeScore'] . "', ''))";
                mysqli_query($databaseConnection, $query);
            }
        }
        for ($i = 0; $i < count($feedbackReportData2); $i++) {
            $query2 = "UPDATE `feedback_report` SET `finalOpinion` = NULLIF('" . $feedbackReportData2[$i]['finalOpinion'] . "', ''), `communicationSkill` = NULLIF('" . $feedbackReportData2[$i]['communicationSkill'] . "', ''), `areaToImproveComS` = NULLIF('" . $feedbackReportData2[$i]['areaToImproveComS'] . "', ''), `durationOfPracticeComS` = NULLIF('" . $feedbackReportData2[$i]['durationOfPracticeComS'] . "', ''), `problemSolvingSkill` = NULLIF('" . $feedbackReportData2[$i]['problemSolvingSkill'] . "', ''), `areaToImprovePSS` = NULLIF('" . $feedbackReportData2[$i]['areaToImprovePSS'] . "', ''), `durationOfPracticePSS` = NULLIF('" . $feedbackReportData2[$i]['durationOfPracticePSS'] . "', ''), `behaviouralSkill` = NULLIF('" . $feedbackReportData2[$i]['behaviouralSkill'] . "', ''), `areaToImproveBS` = NULLIF('" . $feedbackReportData2[$i]['areaToImproveBS'] . "', ''), `durationOfPracticeBS` = NULLIF('" . $feedbackReportData2[$i]['durationOfPracticeBS'] . "', ''), `confidence` = NULLIF('" . $feedbackReportData2[$i]['confidence'] . "', ''), `areaToImproveC` = NULLIF('" . $feedbackReportData2[$i]['areaToImproveC'] . "', ''), `durationOfPracticeC` = NULLIF('" . $feedbackReportData2[$i]['durationOfPracticeC'] . "', ''), `codingSkill` = NULLIF('" . $feedbackReportData2[$i]['codingSkill'] . "', ''), `areaToImproveCodS` = NULLIF('" . $feedbackReportData2[$i]['areaToImproveCodS'] . "', ''), `durationOfPracticeCodS` = NULLIF('" . $feedbackReportData2[$i]['durationOfPracticeCodS'] . "', ''), `readingSkill` = NULLIF('" . $feedbackReportData2[$i]['readingSkill'] . "', ''), `areaToImproveRS` = NULLIF('" . $feedbackReportData2[$i]['areaToImproveRS'] . "', ''), `durationOfPracticeRS` = NULLIF('" . $feedbackReportData2[$i]['durationOfPracticeRS'] . "', ''), `listeningSkill` = NULLIF('" . $feedbackReportData2[$i]['listeningSkill'] . "', ''), `areaToImproveLS` = NULLIF('" . $feedbackReportData2[$i]['areaToImproveLS'] . "', ''), `durationOfPracticeLS` = NULLIF('" . $feedbackReportData2[$i]['durationOfPracticeLS'] . "', ''), `rComprehensionSkill` = NULLIF('" . $feedbackReportData2[$i]['rComprehensionSkill'] . "', ''), `areaToImproveRCS` = NULLIF('" . $feedbackReportData2[$i]['areaToImproveRCS'] . "', ''), `durationOfPracticeRCS` = NULLIF('" . $feedbackReportData2[$i]['durationOfPracticeRCS'] . "', ''), `presentationSkill` = NULLIF('" . $feedbackReportData2[$i]['presentationSkill'] . "', ''), `areaToImprovePS` = NULLIF('" . $feedbackReportData2[$i]['areaToImprovePS'] . "', ''), `durationOfPracticePS` = NULLIF('" . $feedbackReportData2[$i]['durationOfPracticePS'] . "', ''), `grammerSkill` = NULLIF('" . $feedbackReportData2[$i]['grammerSkill'] . "', ''), `areaToImproveGVS` = NULLIF('" . $feedbackReportData2[$i]['areaToImproveGVS'] . "', ''), `durationOfPracticeGVS` = NULLIF('" . $feedbackReportData2[$i]['durationOfPracticeGVS'] . "', ''), `expertAdvice` = NULLIF('" . addslashes($feedbackReportData2[$i]['expertAdvice']) . "', ''),`whatIsGoodComS` = NULLIF('" . $feedbackReportData2[$i]['whatIsGoodComS'] . "', ''),`whatIsGoodPSS` = NULLIF('" . $feedbackReportData2[$i]['whatIsGoodPSS'] . "', ''),`whatIsGoodBS` = NULLIF('" . $feedbackReportData2[$i]['whatIsGoodBS'] . "', ''),`whatIsGoodC` = NULLIF('" . $feedbackReportData2[$i]['whatIsGoodC'] . "', ''),`whatIsGoodCodS` = NULLIF('" . $feedbackReportData2[$i]['whatIsGoodCodS'] . "', ''),`whatIsGoodRS` = NULLIF('" . $feedbackReportData2[$i]['whatIsGoodRS'] . "', ''),`whatIsGoodLS` = NULLIF('" . $feedbackReportData2[$i]['whatIsGoodLS'] . "', ''),`whatIsGoodRCS` = NULLIF('" . $feedbackReportData2[$i]['whatIsGoodRCS'] . "', ''),`whatIsGoodPS` = NULLIF('" . $feedbackReportData2[$i]['whatIsGoodPS'] . "', ''),`whatIsGoodGVS` = NULLIF('" . $feedbackReportData2[$i]['whatIsGoodGVS'] . "', ''),`aptitudeScore` = NULLIF('" . $feedbackReportData2[$i]['aptitudeScore'] . "', '') WHERE `feedbackRequestId`='" . $feedbackReportData2[$i]['feedbackRequestId'] . "'";
            mysqli_query($databaseConnection, $query2);
        }

        $query3 = "DELETE FROM `feedback_report` WHERE `feedbackRequestId` NOT IN (SELECT id from feedback_request where review_status = '2')";
        mysqli_query($databaseConnection, $query3);
        $to_encode = array(
            'data1' => $feedbackReportData,
            'data2' => $feedbackReportData2,
            'status' => 1,
            'result' => "success"
        );
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while updating feedback report"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getEventRegistrationData'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $filter_query = "";

        $order_query = " order by er.createdAt  desc ";
        $query = "SELECT 
                er.createdAt as date_of_registration,er.id,
                concat(u.firstName,' ',u.lastName) as name,
                u.emailId,
                u.mobileNumber,pd.college,pd.specialization,pd.year,
                cat.name as category,i.name as interview_name ,i.id as intId
                FROM `event_registration` er,users  u ,category  cat,interview i ,event e,professionaldetails pd 
                WHERE er.userId=u.id and cat.id=er.categoryType and e.interviewId=i.id and e.id=er.eventId and pd.candidateId=er.userId and u.active='Y' and u.deleted_at is null";
        $data = '';
        if ($userType == 'college') {
            $college_query = mysqli_query($databaseConnection, "select * from `users` u1 where u1.id =" . $json['userId'] . " order by id limit 1");
            $college = mysqli_fetch_array($college_query, MYSQLI_ASSOC);
            $filter_query .= " and pd.college=" . $college['college_id'];
        } elseif ($userType == 'student') {
            $filter_query .= " and u.id=" . $json['userId'];
        }
        //$data = $query.$filter_query." group by pd.candidateId ".$order_query;
        $data = $query . $filter_query . $order_query;
        if ($data != '') {
            /* End Anil Code*/
            //$count_query=mysqli_query($databaseConnection,$data);
            $query = mysqli_query($databaseConnection, $data);
            if (mysqli_num_rows($query) > 0) {
                $total_data['data'] = mysqli_fetch_all($query, MYSQLI_ASSOC);
                $total_data['count'] = mysqli_num_rows($query);
                $to_encode = $total_data;
            } else {
                $to_encode = array(
                    'result' => "error",
                    'status' => 0,
                    'errorCode' => "in Error while retrieving Student information."
                );
            }
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "in Error You are not having access this page."
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving Student information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['geteventRegistrationFilters'])) {

    $int_query = mysqli_query($databaseConnection, "select id,name from interview ORDER BY name");
    $values['interviews'] = mysqli_fetch_all($int_query, MYSQLI_ASSOC);
    $stream_query = mysqli_query($databaseConnection, "select * from stream where isActive = 'Y' order by id=11,stream");
    $college_query = mysqli_query($databaseConnection, "select id,collegeName as college from colleges  order by id=188,collegeName");
    $values['specialization'] = mysqli_fetch_all($stream_query, MYSQLI_ASSOC);
    $values['college'] = mysqli_fetch_all($college_query, MYSQLI_ASSOC);
    echo json_encode($values);
} elseif (isset($_GET['getrawdataDashboardData'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    $limit = 200;
    $start = 0;
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $filter_query = " where isActive = 'Y' ";
        $limit = $json['limit'];
        $start = ($json['page'] - 1) * $limit;
        $order_query = " order by id desc";
        $limit_query = $limit == 0 ? "" : " limit " . $start . "," . $limit;
        if ($json['emailId'] != "") {
            $filter_query .= " and email_id like '%" . $json['emailId'] . "%'";
        }
        if ($json['stream'] != "")
            $filter_query .= " and stream in ('" . implode("', '", $json['stream']) . "')";
        if ($json['signup_status'] != "")
            $filter_query .= " and signup_status =" . $json['signup_status'];
        if ($json['yop'] != "")
            $filter_query .= " and yop in (" . $json['yop'] . ")";
        if ($json['college'] != "")
            $filter_query .= " and college_name in ('" . implode("', '", array_map("addSlashToString", $json['college'])) . "')";
        if ($json['tieUpCollegeName'] != "")
            $filter_query .= " and tieUpCollegeName in ('" . implode("','", array_map("addSlashToString", $json['tieUpCollegeName'])) . "')";
        if ($json['filterUserType'] != "")
            $filter_query .= " and userType like '" . $json['filterUserType'] . "'";
        if ($json['mentorship_status'] != "")
            $filter_query .= " and mentorship_status like '" . $json['mentorship_status'] . "'";
        /*if($json['subjects']!="")
            $filter_query.=" and fav_subjects like '".$json['subjects']."'";
        if($json['skills']!="")
            $filter_query.=" and fav_programming_skill like '".$json['skills']."'";*/
        if ($json['uploaded_from_date'] != "" && $json['uploaded_to_date'] == "")
            $filter_query .= " and uploadedAt >= '" . $json['uploaded_from_date'] . "'";
        if ($json['uploaded_from_date'] == "" && $json['uploaded_to_date'] != "")
            $filter_query .= " and uploadedAt <= '" . $json['uploaded_to_date'] . "'";
        if ($json['uploaded_from_date'] != "" && $json['uploaded_to_date'] != "")
            $filter_query .= " and uploadedAt >= '" . $json['uploaded_from_date'] . "' and uploadedAt <= '" . $json['uploaded_to_date'] . "'";
        if ($json['isTieUpStatus'] != "") {
            if ($json['isTieUpStatus'] == 'Y') {
                $filter_query .= " and isPaid = 'Y'";
            } else if ($json['isTieUpStatus'] == 'F') {
                $filter_query .= " and isPaid = 'F'";
            } else {
                $filter_query .= " and isPaid = 'N'";
            }
        }
        $query = "select * from raw_data";

        $data = '';
        if ($userType == 'college') {
            $college_query = mysqli_query($databaseConnection, "select * from `users` u1 where u1.id =" . $json['userId'] . " order by id limit 1");
            $college = mysqli_fetch_array($college_query, MYSQLI_ASSOC);
            $filter_query .= " and pd.college=" . $college['college_id'];
        } elseif ($userType == 'student') {
            $filter_query .= " and u.id=" . $json['userId'];
        }

        $data = $query . $filter_query . $order_query;

        //echo $data.'  ';

        if ($data != '') {

            $count_query = mysqli_query($databaseConnection, "select count(id) as count_result from raw_data" . $filter_query);

            $query = mysqli_query($databaseConnection, $data . $limit_query);
            if (mysqli_num_rows($query) > 0) {
                $main_data = mysqli_fetch_all($query, MYSQLI_ASSOC);
                $count_result = mysqli_fetch_assoc($count_query);
                $row = mysqli_query($databaseConnection, "select synched_at from synch_log where table_name = 'raw_data' order by id desc limit 0,1");
                $result = mysqli_fetch_assoc($row);
                $to_encode = array(
                    'data' => $main_data,
                    'count' => $count_result['count_result'],
                    'synched_at' => timeAgo($result['synched_at']),
                );
            } else {
                $to_encode = array(
                    'result' => "error",
                    'status' => 0,
                    'errorCode' => "in Error while retrieving Student information.",
                    'qry' => $data . " limit " . $start . "," . $limit
                );
            }
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "in Error You are not having access this page."
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving Student information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getrawdataDashboardFilters'])) {
    $stream_query = mysqli_query($databaseConnection, "select distinct(stream) as stream from raw_data where stream is not null and stream != '' order by stream");
    //$college_query=mysqli_query($databaseConnection,"select id,collegeName as college from colleges order by id=188,collegeName");
    $college_query = mysqli_query($databaseConnection, "select distinct(college_name) as college from raw_data where college_name is not null and college_name != '' order by college_name");
    $tieUpCollege_query = mysqli_query($databaseConnection, "select distinct(tieUpCollegeName) as college from raw_data where tieUpCollegeName is not null and tieUpCollegeName != '' order by college");
    $userType_query = mysqli_query($databaseConnection, "select distinct(userType) as userType from raw_data order by userType");
    $values['specialization'] = mysqli_fetch_all($stream_query, MYSQLI_ASSOC);
    $values['college'] = mysqli_fetch_all($college_query, MYSQLI_ASSOC);
    $values['tieUpCollegeName'] = mysqli_fetch_all($tieUpCollege_query, MYSQLI_ASSOC);
    $values['userType'] = mysqli_fetch_all($userType_query, MYSQLI_ASSOC);
    echo json_encode($values);
} elseif (isset($_GET['synchRawData'])) {

    //$query1="update raw_data r,users u set r.signup_status = 1, r.contact_number = u.mobileNumber where u.emailId = r.email_id and r.signup_status != 1;";
    $query1 = "update raw_data r, users u inner join professionaldetails pd on pd.candidateId = u.id inner join colleges c on c.id = pd.college inner join stream s on pd.specialization = s.id set r.signup_status = 1,r.contact_number = u.mobileNumber, r.college_name = c.collegeName, r.stream = s.stream,  r.yop = pd.year where r.email_id = u.emailId and u.verificationStatus='Y' ;";
    $query = "INSERT INTO `synch_log` (`table_name`, `synched_at`) VALUES ('raw_data', '" . date('Y-m-d H:i:s') . "');";

    if (mysqli_query($databaseConnection, $query1)) {
        //$query2="update raw_data r,users u,colleges c, professionaldetails pd set r.college_name = c.collegeName where u.emailId = r.email_id and c.id = pd.college and pd.candidateId = u.id;";
        $query2 = "insert into raw_data (`candidate_name`,`college_name`,`yop`,`email_id`,`contact_number`,`stream`,`signup_status`)
            select u.firstName, c.collegeName, pd.year,u.emailId, u.mobileNumber, s.stream,'1' from users u inner join professionaldetails pd on pd.candidateId = u.id inner join stream s on  s.id = pd.specialization inner join colleges c on c.id = pd.college where u.emailId not in (select email_id from raw_data) and u.verificationStatus='Y'";
        $query2Result = mysqli_query($databaseConnection, $query2);
        mysqli_query($databaseConnection, $query);
        $values['result'] = "success";
    } else {
        $values['result'] = "fail";
    }
    echo json_encode($values);
} elseif (isset($_GET['updatePeerResponseData'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $currentUserType = $json['currentUserType'];
        $query = "UPDATE `questions` SET `peerResponseStatus`='A' WHERE `peerResponseStatus`='NA' AND `id` IN (Select temp.questionId from (select m.questionId from mergedVideos m inner join feedback_request fr on fr.interviewSessionId = m.interviewSessionId inner join expert_review er on er.feedback_request_id = fr.id and m.questionId = er.questionId and m.candidateId = er.candidateId and m.interviewId = er.interviewId  where m.interviewSessionId is not null and m.rejected='N' and fr.review_status='2' and er.overallRating in('5','6','7','8','9','10') and er.overallRating not in('videoIssue') group by m.questionId) as temp)";
        $result = mysqli_query($databaseConnection, $query);
        if ($result) {
            $synchQuery = "INSERT INTO `synch_log` (`table_name`, `synched_at`) VALUES ('bestPeerResponse', '" . date('Y-m-d H:i:s') . "');";
            mysqli_query($databaseConnection, $synchQuery);
            $to_encode = array(
                'status' => 1,
                'result' => "success"
            );
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "out Error while retrieving User information" . $query
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving User information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['uploadScreenRecordingToVimeo'])) {
    if ($_FILES['video-blob']) {
        $currentStreamId = $_POST['currentStreamId'];

        $client = new Vimeo("be1cd73378131270e832b71009c3aa10cfe8f6e3", "ACJ7SgqpXse9nD0pfgP6+IXOD5XxvVxuTk6Hr9T2a5D8ROhVqkgJ+EWsB6pgXf7U3JoXaR2eN0ysj8jjVBPgbGjSHCnPvMIye97nv1GmeDn+wzH7mrk/4a6Bsfv/nVVy", "59f892688f66084c8288f030ff53038c");

        $file_name = $_FILES['video-blob']['tmp_name'];
        $uri = $client->upload($file_name, array(
            "name" => $_POST['currentStreamId'],
            "description" => "Expert Screen Sharing Video"
        ));

        $vimeoURL = explode("/", $uri);
        $vimeoId = end($vimeoURL);

        $sql = "UPDATE `mergedVideos` SET `youtubeId`='" . $vimeoId . "' WHERE `outputVideoURL`='" . $currentStreamId . "'";
        mysqli_query($databaseConnection, $sql);

        $to_encode = array(
            'result' => "Success",
            'message' => "video uploaded",
            'status' => 1,
            'response' => $uri
        );
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while uploading information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['uploadVideoToVimeo'])) {
    if ($_FILES['video-blob']) {
        $currentStreamId = $_POST['currentStreamId'];
        $questionId = $_POST['questionId'];
        $panelId = $_POST['panelId'];
        $description = $_POST['videoType'] == 'expertAdvice' ? 'Expert Advice Video' : ('quesVideo' ? 'Expert Question Video' : 'Peer Response Video');
        $vidLength = $_POST['vidLength'];
        $whiteboardText = addslashes(trim($_POST['whiteboardText']));

        $client = new Vimeo("be1cd73378131270e832b71009c3aa10cfe8f6e3", "ACJ7SgqpXse9nD0pfgP6+IXOD5XxvVxuTk6Hr9T2a5D8ROhVqkgJ+EWsB6pgXf7U3JoXaR2eN0ysj8jjVBPgbGjSHCnPvMIye97nv1GmeDn+wzH7mrk/4a6Bsfv/nVVy", "59f892688f66084c8288f030ff53038c");

        $file_name = $_FILES['video-blob']['tmp_name'];
        $uri = $client->upload($file_name, array(
            "name" => $currentStreamId,
            "description" => $description
        ));

        $vimeoURL = explode("/", $uri);
        $vimeoId = end($vimeoURL);
        if ($_POST['videoType'] == 'expertAdvice') {
            $panelQuery = "select questionId,expertId from questions_transection Where `questionId`='" . $questionId . "' and `delegationType` = 'guidanceVideo' ";
            $panelResult = mysqli_query($databaseConnection, $panelQuery);
            $values = mysqli_fetch_assoc($panelResult);
        } elseif ($_POST['videoType'] == 'quesVideo') {
            $panelQuery = "select questionId,expertId from questions_transection Where `questionId`='" . $questionId . "' and `delegationType` = 'questionVideo' ";
            $panelResult = mysqli_query($databaseConnection, $panelQuery);
            $values = mysqli_fetch_assoc($panelResult);
        } else {
            $panelQuery = "select questionId,expertId from questions_transection Where `questionId`='" . $questionId . "' and `delegationType` = 'peerResponseVideo' ";
            $panelResult = mysqli_query($databaseConnection, $panelQuery);
            $values = mysqli_fetch_assoc($panelResult);
        }
        if (is_null($values['expertId']) || $panelId == $values['expertId']) {
            if ($_POST['videoType'] == 'expertAdvice') {
                $sql = "UPDATE `questions_transection` SET `vimeoId`='" . $vimeoId . "' , `expertId` = '" . $panelId . "' , `vidLength`='" . $vidLength . "', `uploadStatus`='1'  WHERE `questionId`='" . $questionId . "' and `delegationType` = 'guidanceVideo' ";
            } elseif ($_POST['videoType'] == 'quesVideo') {
                $sql = "UPDATE `questions_transection` SET `vimeoId`='" . $vimeoId . "' ,`expertId` = '" . $panelId . "' ,`vidLength`='" . $vidLength . "',  `uploadStatus`= '1' WHERE `questionId`='" . $questionId . "' and `delegationType` = 'questionVideo' ";
            } else {
                $sql = "UPDATE `questions_transection` SET `vimeoId`='" . $vimeoId . "' , `expertId` = '" . $panelId . "' , `vidLength`='" . $vidLength . "',`uploadStatus`= '1', `whiteboardText` = NULLIF('" . $whiteboardText . "', '')  WHERE `questionId`='" . $questionId . "' and `delegationType` = 'peerResponseVideo' ";
            }
            mysqli_query($databaseConnection, $sql);

            $to_encode = array(
                'result' => "Success",
                'message' => "video uploaded",
                'status' => 1,
                'response' => $uri,
                'query' => $sql
            );
        } else {
            $to_encode = array(
                'result' => "Error",
                'message' => "Another expert is uploading",
                'status' => 0,
                'errorCode' => "Another expert is uploading"
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while uploading information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['approveVimeoVideo'])) {
    if ($_POST['questionId']) {
        $questionId = $_POST['questionId'];
        $expertId = $_POST['expertId'];
        $videoType = $_POST['videoType'];
        $imagesNumber = $_POST['imagesNumber'];
        $videoNumber = $_POST['videoNumber'];
        $sql = " ";
        $updateSql = " ";
        if ($expertId != 0) {
            if ($videoType == 'quesVideo') {
                $vimeoSql = "Select vimeoId,delegationType from  questions_transection where questionId='" . $questionId . "' and expertId='" . $expertId . "' and  delegationType= 'questionVideo' ";
            } elseif ($videoType == 'expertAdvice') {
                $vimeoSql = "Select vimeoId,delegationType  from  questions_transection where questionId='" . $questionId . "' and expertId='" . $expertId . "' and  delegationType= 'guidanceVideo' ";
            } else {
                $vimeoSql = "Select vimeoId,delegationType  from  questions_transection where questionId='" . $questionId . "' and expertId='" . $expertId . "' and  delegationType= 'peerResponseVideo' ";
            }

            $result = mysqli_query($databaseConnection, $vimeoSql);
            if (mysqli_num_rows($result) >= 1) {
                $row = array();
                $row = mysqli_fetch_all($result, MYSQLI_ASSOC);
                if ($row[0]["delegationType"] == 'guidanceVideo' && $row[0]["vimeoId"] != '') {
                    $sql = "UPDATE `questions` SET `expertAdvice`='" . $row[0]["vimeoId"] . "' WHERE `id`='" . $questionId . "'";
                    $response = $row[0]["vimeoId"];
                    $updateSql = "UPDATE `questions_transection` SET `uploadStatus`=2,noOfImages='" . $imagesNumber . "',noOfVideos='" . $videoNumber . "' WHERE `questionId`='" . $questionId . "' and expertId='" . $expertId . "' and delegationType='guidanceVideo'";
                } elseif ($row[0]["delegationType"] == 'questionVideo' && $row[0]["vimeoId"] != '') {
                    $sql = "UPDATE `questions` SET `youtubeId`='" . $row[0]["vimeoId"] . "' WHERE `id`='" . $questionId . "'";
                    $response = $row[0]["vimeoId"];
                    $updateSql = "UPDATE `questions_transection` SET `uploadStatus`=2  WHERE `questionId`='" . $questionId . "' and expertId='" . $expertId . "' and  delegationType='questionVideo'";
                } elseif ($row[0]["delegationType"] == 'peerResponseVideo' && $row[0]["vimeoId"] != '') {
                    $sql = "UPDATE `questions` SET `peerResponseVideo`='" . $row[0]["vimeoId"] . "' WHERE `id`='" . $questionId . "'";
                    $response = $row[0]["vimeoId"];
                    $updateSql = "UPDATE `questions_transection` SET `uploadStatus`=2  WHERE `questionId`='" . $questionId . "' and expertId='" . $expertId . "' and  delegationType='peerResponseVideo'";
                }
                mysqli_query($databaseConnection, $sql);
                mysqli_query($databaseConnection, $updateSql);
                /* change by Naraayn  change priority high or ultra high to No when work is completed*/
                $highPrioritycheck = mysqli_query($databaseConnection, "select q.id from questions q where q.expertAdvice is not null and q.youtubeId != '314664775' and (q.peerResponseVideo is not null or q.mbr_id != '0') and (q.eligibleStreamId != '' AND q.eligibleStreamId IS NOT NULL AND q.subjectId != '' AND q.subjectId IS NOT NULL AND q.conceptId != '' AND q.conceptId IS NOT NULL AND q.key_skill_id != '' AND q.key_skill_id IS NOT NULL AND q.topic_id != '' AND q.topic_id IS NOT NULL AND q.isWbRequired != '' AND q.isWbRequired IS NOT NULL AND q.questionLevel != '' AND q.questionLevel IS NOT NULL) and q.id='" . $questionId . "' ");
                if (mysqli_num_rows($highPrioritycheck) == 1) {
                    $updateHighPriority = "UPDATE questions set priorityStatus='0' where id = '" . $questionId . "'";
                    mysqli_query($databaseConnection, $updateHighPriority);
                }
                $to_encode = array(
                    'result' => "success",
                    'message' => "video Approved",
                    'status' => 1
                );
            } else {
                $to_encode = array(
                    'result' => "Failed",
                    'message' => "video UnApproved"
                );
            }
        } else {
            if ($videoType == 'quesVideo') {
                $vimeoSql = "Select vimeoId,delegationType from  questions_transection where questionId='" . $questionId . "'  and  delegationType= 'questionVideo' ";
            } elseif ($videoType == 'expertAdvice') {
                $vimeoSql = "Select vimeoId,delegationType  from  questions_transection where questionId='" . $questionId . "' and  delegationType= 'guidanceVideo' ";
            } else {
                $vimeoSql = "Select vimeoId,delegationType  from  questions_transection where questionId='" . $questionId . "' and  delegationType= 'peerResponseVideo' ";
            }
            $result = mysqli_query($databaseConnection, $vimeoSql);
            if (mysqli_num_rows($result) >= 1) {
                $row = array();
                $row = mysqli_fetch_all($result, MYSQLI_ASSOC);

                if ($row[0]["delegationType"] == 'guidanceVideo' && $row[0]["vimeoId"] != '') {
                    $sql = "UPDATE `questions` SET `expertAdvice`='" . $row[0]["vimeoId"] . "' WHERE `id`='" . $questionId . "'";
                    $response = $row[0]["vimeoId"];
                    $updateSql = "UPDATE `questions_transection` SET `uploadStatus`=2,noOfImages='" . $imagesNumber . "',noOfVideos='" . $videoNumber . "' WHERE `questionId`='" . $questionId . "' and delegationType='guidanceVideo'";
                } elseif ($row[0]["delegationType"] == 'questionVideo' && $row[0]["vimeoId"] != '') {
                    $sql = "UPDATE `questions` SET `youtubeId`='" . $row[0]["vimeoId"] . "' WHERE `id`='" . $questionId . "'";
                    $response = $row[0]["vimeoId"];
                    $updateSql = "UPDATE `questions_transection` SET `uploadStatus`=2  WHERE `questionId`='" . $questionId . "' and delegationType='questionVideo'";
                } elseif ($row[0]["delegationType"] == 'peerResponseVideo' && $row[0]["vimeoId"] != '') {
                    $sql = "UPDATE `questions` SET `peerResponseVideo`='" . $row[0]["vimeoId"] . "' WHERE `id`='" . $questionId . "'";
                    $response = $row[0]["vimeoId"];
                    $updateSql = "UPDATE `questions_transection` SET `uploadStatus`=2  WHERE `questionId`='" . $questionId . "' and  delegationType='peerResponseVideo'";
                }
                mysqli_query($databaseConnection, $sql);
                mysqli_query($databaseConnection, $updateSql);
                /* change by Naraayn  2/7/2021 change priority high or Ultra high to No when work is completed*/
                $highPrioritycheck = mysqli_query($databaseConnection, "select q.id from questions q where q.expertAdvice is not null and q.youtubeId != '314664775' and (q.peerResponseVideo is not null or q.mbr_id != '0') and (q.eligibleStreamId != '' AND q.eligibleStreamId IS NOT NULL AND q.subjectId != '' AND q.subjectId IS NOT NULL AND q.conceptId != '' AND q.conceptId IS NOT NULL AND q.key_skill_id != '' AND q.key_skill_id IS NOT NULL AND q.topic_id != '' AND q.topic_id IS NOT NULL AND q.isWbRequired != '' AND q.isWbRequired IS NOT NULL AND q.questionLevel != '' AND q.questionLevel IS NOT NULL) and q.id='" . $questionId . "'");
                if (mysqli_num_rows($highPrioritycheck) == 1) {
                    $updateHighPriority = "UPDATE questions set priorityStatus='0' where id = '" . $questionId . "'";
                    mysqli_query($databaseConnection, $updateHighPriority);
                }

                $to_encode = array(
                    'result' => "success",
                    'message' => "video Approved",
                    'status' => 1
                );
            } else {
                $to_encode = array(
                    'result' => "Failed",
                    'message' => "video UnApproved"
                );
            }
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while Approving"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['questionTaggingInfo'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $questionId = $json['questionId'];
        $delegationType = $json['delegationType'];
        $sql = "select qtt.*,q.id as questionId,q.youtubeId,q.quesDiagram,qs.delegationType,qs.expertId,qs.uploadStatus from questions_tagging_transection qtt inner join questions_transection qs on qtt.questionId = qs.questionId  inner join questions q on qs.questionId = q.id  where qs.delegationType='tagging' and qtt.questionId = '" . $questionId . "'";
        $query = mysqli_query($databaseConnection, $sql);
        if (mysqli_num_rows($query) >= 1) {
            $values = mysqli_fetch_array($query, MYSQLI_ASSOC);
            $to_encode = $values;
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "out Error while retrieving tagging information"
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving tagging information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['updateTaggingQuestion'])) {
    if ($_POST['question_id']) {
        $questionId = $_POST['question_id'];
        $topic_id = $_POST['topic_id'];
        $expertId = $_POST['expertId'];
        $concept_id = $_POST['concept_id'];
        $subject_id = $_POST['subject_id'];
        $question_level = $_POST['questionLevel'];
        // $domainId = explode(',', $_POST['domainId']);
        if ($_POST['otherTopic'] != "") {
            $topicQuery = mysqli_query($databaseConnection, "insert into topic(name) values ('" . addslashes($_POST['otherTopic']) . "');");
            $topic_id = mysqli_insert_id($databaseConnection);
        }

        if ($_POST['otherConcept'] != "") {
            $topicQuery = mysqli_query($databaseConnection, "insert into concepts(name) values ('" . addslashes($_POST['otherConcept']) . "');");
            $concept_id = mysqli_insert_id($databaseConnection);
        }

        if ($_POST['otherSubject'] != "") {
            $topicQuery = mysqli_query($databaseConnection, "insert into favourite_subject(favourite_subject, isActiveForMentorship) values ('" . addslashes($_POST['otherSubject']) . "', 'N');");
            $subject_id = mysqli_insert_id($databaseConnection);
        }

        /* if ($_POST['otherIndustry'] != "") {
            array_pop($domainId);
            $_POST['otherIndustry'] = explode(",",$_POST['otherIndustry']);
            for($i=0; $i<count($_POST['otherIndustry']); $i++) {
                if(trim($_POST['otherIndustry'][$i]) != '') {
                    $domainQuery = mysqli_query($databaseConnection, "insert into favourite_domain(name) values ('".addslashes($_POST['otherIndustry'][$i])."');");
                    $domain_id = mysqli_insert_id($databaseConnection);
                    array_push($domainId, $domain_id);
                }
            }
        }*/
        $panelQuery = "select questionId,expertId from questions_transection where `questionId`='" . $questionId . "' and `delegationType` = 'tagging' ";
        $panelResult = mysqli_query($databaseConnection, $panelQuery);
        $values = mysqli_fetch_assoc($panelResult);
        if (is_null($values['expertId']) || $expertId == $values['expertId']) {
            $quesTran = "update questions_transection  set `uploadStatus`= 1 , expertId='" . $expertId . "' WHERE `questionId`='" . $questionId . "' and `delegationType` = 'tagging' ";
            mysqli_query($databaseConnection, $quesTran);
            $sql = "update questions_tagging_transection set `topicId`='" . $topic_id . "', `keySkillId`='" . $_POST['keySkillId'] . "', `questionLevel`='" . $_POST['questionLevel'] . "', eligibleStreamId='" . $_POST['eligibleStreamId'] . "', subjectId='" . $subject_id . "', conceptId='" . $concept_id . "',
            `shortExpectedAns`='" . addslashes($_POST['shortExpectedAns']) . "',
            `instruction`='" . addslashes($_POST['instruction']) . "',
            `answerDuration`='" . $_POST['answerDuration'] . "',
            `thinkingTime`='" . $_POST['thinkingTime'] . "',
            `isWbRequired`='" . $_POST['isWbRequired'] . "',
            `tutorialLink`='" . addslashes($_POST['tutorialLink']) . "',
            `remarks`='" . addslashes($_POST['remarks']) . "',
            `questionText` = '" . addslashes($_POST['questionText']) . "'
            where questionId='" . $questionId . "' ";
            mysqli_query($databaseConnection, $sql);
            if ($sql) {
                $to_encode = array(
                    'status' => 1,
                    'result' => "success",
                    'uploadStatus' => 1,
                    'query1' => $sql,
                    'query2' => $quesTran
                );
            } else {
                $to_encode = array(
                    'status' => 0,
                    'result' => "error",
                    'errorCode' => "out Error while updating question information" . $sql
                );
            }
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "other expert is updated question information"
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while updating question information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['approvedTagging'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $questionId = $json['questionId'];
        $delegationType = $json['delegationType'];
        $expertId = $json['expertId'];
        $sql = "update questions_transection set uploadStatus=2  where questionId='" . $questionId . "' and delegationType='tagging'  ";
        $query = mysqli_query($databaseConnection, $sql);
        $transQuery = mysqli_query($databaseConnection, "SELECT * from `questions_tagging_transection` where questionId = '" . $questionId . "' ");
        $questionValue = mysqli_fetch_assoc($transQuery);
        $questionUpdate = "Update questions set topic_id= '" . $questionValue['topicId'] . "', key_skill_id= '" . $questionValue['keySkillId'] . "',
                  questionLevel= '" . $questionValue['questionLevel'] . "', eligibleStreamId= '" . $questionValue['eligibleStreamId'] . "',
                   subjectId= '" . $questionValue['subjectId'] . "', conceptId= '" . $questionValue['conceptId'] . "', domainId= '" . $questionValue['domainId'] . "',
                   `shortExpectedAns`='" . addslashes($questionValue['shortExpectedAns']) . "',
                   `instruction`='" . addslashes($questionValue['instruction']) . "',
                   `answerDuration`='" . $questionValue['answerDuration'] . "',
                   `thinkingTime`='" . $questionValue['thinkingTime'] . "',
                   `isWbRequired`='" . $questionValue['isWbRequired'] . "',
                   `tutorialLink`='" . addslashes($questionValue['tutorialLink']) . "',
                   `remarks`='" . addslashes($questionValue['remarks']) . "',
                   `questionText` = '" . addslashes($questionValue['questionText']) . "',`clusterLevel` =  '" . $questionValue['questionLevel'] . "'
                   where id = '" . $questionId . "' ";
        $updateQuery = mysqli_query($databaseConnection, $questionUpdate);
        /* change by Naraayn 2/7/2021 change priority high or Ultra high to No when work is completed*/
        $highPrioritycheck = mysqli_query($databaseConnection, "select q.id from questions q where q.expertAdvice is not null and q.youtubeId != '314664775' and (q.peerResponseVideo is not null or q.mbr_id != '0') and (q.eligibleStreamId != '' AND q.eligibleStreamId IS NOT NULL AND q.subjectId != '' AND q.subjectId IS NOT NULL AND q.conceptId != '' AND q.conceptId IS NOT NULL AND q.key_skill_id != '' AND q.key_skill_id IS NOT NULL AND q.topic_id != '' AND q.topic_id IS NOT NULL AND q.isWbRequired != '' AND q.isWbRequired IS NOT NULL AND q.questionLevel != '' AND q.questionLevel IS NOT NULL) and q.id='" . $questionId . "'");
        if (mysqli_num_rows($highPrioritycheck) == 1) {
            $updateHighPriority = "UPDATE questions set priorityStatus='0' where id = '" . $questionId . "'";
            mysqli_query($databaseConnection, $updateHighPriority);
        }
        if ($updateQuery) {
            $to_encode = array(
                'status' => 1,
                'result' => "Success",
                'message' => "Approved"
            );
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "out Error while retrieving tagging information",
                'query' => $questionUpdate
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while Approving tagging Question"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['userCreate'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        //$userId = $json['userId'];
        $sql2 = "select * from users where emailId='" . $json['emailId'] . "';";
        $sql2Query = mysqli_query($databaseConnection, $sql2);
        if (!$sql2Query) {
            $sql = " INSERT INTO `users`(`userName`, `password`, `firstName`, `lastName`, `usertype`, `mobileNumber`, `emailId`, `active`, `smsOtp`, `verificationLink`, `verificationStatus`, `college_id`, `createdOn`) VALUES ('" . $json['emailId'] . "','" . $json['password'] . "','" . $json['firstName'] . "','','" . $json['usertype'] . "','" . $json['mobileNumber'] . "','" . $json['emailId'] . "','Y','','','Y'," . $json['college_id'] . " ,  ROUND(UNIX_TIMESTAMP()*1000));";
            if (mysqli_query($databaseConnection, $sql)) {
                $userId = mysqli_insert_id($databaseConnection);
                $pd_sql = "INSERT INTO `professionaldetails` (`candidateId`, `qualification`, `specialization`, `college`, `year`) VALUES ('" . $userId . "','" . $json['qualification'] . "', '" . $json['specialization'] . "','" . $json['college'] . "','" . $json['year'] . "');";
                $pd_sqlQuery = mysqli_query($databaseConnection, $pd_sql);

                if ($pd_sqlQuery) {
                    $sCodeSql = "select * from scodes where s_value='" . $json['sCode'] . "' and s_is_availed='N' and userId is null;";
                    $sCodeQuery = mysqli_query($databaseConnection, $sCodeSql);
                    if (mysqli_num_rows($sCodeQuery) > 0) {
                        $sCodeData = "update scodes set s_is_availed='Y' , userId='" . $userId . "' where s_value='" . $json['sCode'] . "';";
                        mysqli_query($databaseConnection, $sCodeData);
                        $to_encode = array(
                            'status' => 1,
                            'result' => "success",
                            'msg' => "user created successfully with professional and subscription code"
                        );
                    } else {
                        $to_encode = array(
                            'status' => 2,
                            'result' => "error",
                            'msg' => "Subscription code invalid" . $sCodeQuery
                        );
                    }
                } else {
                    $to_encode = array(
                        'status' => 3,
                        'result' => "error",
                        'msg' => "error while creating professional info " . $pd_sqlQuery
                    );
                }
                if ($json['usertype'] == 'expert') {
                    $panelquery = "INSERT INTO `panel` (`name`, `qualification`, `oraganisation`, `experience`, `specilization`, `emailId`, `phonenumber`, `panelTitle`, `panelDescription`) VALUES ('" . $json['firstName'] . "', '" . $json['qualification'] . "', '" . $json['college'] . "', '', '" . $json['specialization'] . "', '" . $json['emailId'] . "', '" . $json['mobileNumber'] . "', '', '');";
                    mysqli_query($databaseConnection, $panelquery);
                    $panelId = mysqli_insert_id($databaseConnection);
                    mysqli_query($databaseConnection, "update users set panelId=" . $panelId . " where id=" . $userId);
                }
                /*changes By anil 30-09-2018*/
            } else {
                $to_encode = array(
                    'status' => 0,
                    'result' => "error",
                    'errorCode' => "out Error while creating User information" . $sql
                );
            }
        } else {
            $to_encode = array(
                'status' => 4,
                'result' => "error",
                'errorCode' => "User alreay exist"
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving User information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['userUpdate'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $oldScode = $json['oldScode'];
        $firstName = $json['firstName'];
        $firstName = addslashes($firstName);
        $password = password_hash($json['password'], PASSWORD_BCRYPT, ["cost" => 12]);
        $sql = "UPDATE `users` SET `userName`='" . $json['emailId'] . "',`password`='" . $password . "',`firstName`='" . $firstName . "',`usertype`='" . $json['usertype'] . "',`mobileNumber`='" . $json['mobileNumber'] . "',`emailId`='" . $json['emailId'] . "',`smsOtp`='" . $json['smsOtp'] . "',`college_id`='" . $json['college_id'] . "',`verificationStatus`='" . $json['verificationStatus'] . "',`active`='" . $json['active'] . "' WHERE id=" . $userId;
        $professionalsql = "";

        if (mysqli_query($databaseConnection, $sql)) {
            $pd_query = "UPDATE professionaldetails set qualification='" . $json['qualification'] . "',specialization='" . $json['specialization'] . "',college='" . $json['college'] . "',year='" . $json['year'] . "' where candidateId='" . $userId . "'";
            $query = mysqli_query($databaseConnection, $pd_query);
            $sCodeSql = "select * from scodes where s_value='" . $json['sCode'] . "' and s_is_availed='N' and userId is null;";
            $sCodeQuery = mysqli_query($databaseConnection, $sCodeSql);
            if (mysqli_num_rows($sCodeQuery) > 0) {
                $oldScodeData = "update scodes set s_is_availed='N' where userId='" . $userId . "' and s_value='" . $oldScode . "';";
                mysqli_query($databaseConnection, $oldScodeData);
                $sCodeData = "update scodes set s_is_availed='Y' , userId='" . $userId . "' where s_value='" . $json['sCode'] . "';";
                mysqli_query($databaseConnection, $sCodeData);
                $to_encode = array(
                    'status' => 1,
                    'result' => "success",
                    'msg' => "User updated successfully"
                );
            } else {
                $to_encode = array(
                    'status' => 2,
                    'result' => "error",
                    'msg' => "Invalid Subscription Code"
                );
            }
            if ($json['usertype'] == 'expert') {
                $userQuery = mysqli_query($databaseConnection, "select * from users WHERE id=" . $userId);
                $user = mysqli_fetch_assoc($userQuery);
                if ($user['panelId'] == 0) {
                    $panelquery = "INSERT INTO `panel` (`name`, `qualification`, `oraganisation`, `experience`, `specilization`, `emailId`, `phonenumber`, `panelTitle`, `panelDescription`) VALUES ('" . $json['firstName'] . "', '" . $json['qualification'] . "', '" . $json['college'] . "', '', '" . $json['specialization'] . "', '" . $json['emailId'] . "', '" . $json['mobileNumber'] . "', '', '');";
                    mysqli_query($databaseConnection, $panelquery);
                    $panelId = mysqli_insert_id($databaseConnection);
                    mysqli_query($databaseConnection, "update users set panelId=" . $panelId . " where id=" . $userId);
                }
            }
            /*Changes By anil 30-09-2018*/
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "out Error while updating User information" . $sql
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving User information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getPanelData'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $data = '';
        if ($userType == 'admin') {
            $data = "select * from `panel` where deleted_at is null and expertStatus=1";
            //$data = "select * from `panel` order by name";
        }
        if ($data != '') {
            $query = mysqli_query($databaseConnection, $data);
            if (mysqli_num_rows($query) >= 1) {
                $values = array();
                while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
                    $row['url'] = "/finbox?pid=" . $row['id'];
                    $row['picture'] = 'panel_' . $row['id'] . '.png';
                    $values[] = $row;
                }
                $to_encode = $values;
            } else {
                $to_encode = array(
                    'result' => "error",
                    'status' => 0,
                    'errorCode' => "in Error while retrieving User information."
                );
            }
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "in Error You are not having access this page."
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving User information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getPanelDashboardData'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $limit = $json['limit'];
        $filter_query = " where 1 ";
        $order_Query = "order by u.createdOn desc";
        $start = ($json['page'] - 1) * $limit;
        $limit_query = $limit == 0 ? "" : " limit " . $start . "," . $limit;
        if ($json['panelStatus'] != "") {
            if ($json['panelStatus'] == '2') {
                $filter_query .= " and p.underTesting = 'N' ";
            } else {
                $filter_query .= " and p.expertStatus = '" . $json['panelStatus'] . "' ";
            }
        }
        if ($json['name'] != "") {
            $filter_query .= " and p.name like '%" . $json['name'] . "%' ";
        }
        if ($json['stream'] != "") {
            $filter_query .= " and pd.specialization = '" . $json['stream'] . "' ";
        }
        if ($json['approvedWork'] != "") {
            if ($json['approvedWork'] == 'U') {
                $filter_query .= " and p.underTesting = 'Y' ";
            }
            if ($json['approvedWork'] == 'A') {
                $filter_query .= " and p.isAssessmentApproved = 'Y' ";
            }
            if ($json['approvedWork'] == 'P') {
                $filter_query .= " and p.isPeerApproved = 'Y' ";
            }
            if ($json['approvedWork'] == 'C') {
                $filter_query .= " and p.isVideoApproved = 'Y' ";
            }
            if ($json['approvedWork'] == 'T') {
                $filter_query .= " and p.isTaggingApproved = 'Y' ";
            }
        }
        if ($json['referrerStatus'] != "") {
            if ($json['referrerStatus'] == '1') {
                $filter_query .= " and p.referrerName != 'None' and p.referrerName !=''  ";
            } else {
                $filter_query .= " and (p.referrerName = 'None' or p.referrerName ='') ";
            }

        }
        if ($json['publishStatus'] != "") {
            $filter_query .= " and p.publishStatus = '" . $json['publishStatus'] . "' ";
        }
        if ($json['programming'] != "") {
            $filter_query .= " and p.coding  like '%" . $json['programming'] . "%' ";
        }
        if ($json['areaOfExpertise'] != "") {
            $filter_query .= " and FIND_IN_SET('" . $json['areaOfExpertise'] . "',p.areaOfExpertiseId )";
        }
        if ($json['institute'] != "") {
            $filter_query .= " and p.oraganisation = '" . $json['institute'] . "' ";
        }
        if ($json['years'] != "") {
            $filter_query .= " and p.experience >= '" . $json['years'] . "' ";
        }
        if ($json['years'] == "less than 1 year") {
            $filter_query .= " and p.experience like '%" . $json['years'] . "%' ";
        }
        if ($json['teaching'] != "") {
            $filter_query .= " and p.teachingExperience='" . $json['teaching'] . "' ";
        }
        if ($json['iAm'] != "") {
            $filter_query .= " and p.expertType = '" . $json['iAm'] . "' ";
        }
        if ($json['verificationStatus'] != "") {
            $filter_query .= " and p.expertStatus = " . $json['verificationStatus'] . " ";
        }
        //for redirection
        if ($json['redirect'] != "" && $json['redirect'] == 'weeklyActiveExperts') {
            $filter_query .= " AND p.deleted_at IS null AND p.lastActiveOnAssessment IS NOT NULL AND TIMESTAMPDIFF(DAY,p.lastActiveOnAssessment,now()) <= 15 ";
        }

        if ($json['redirect'] != "" && $json['redirect'] == 'totalWorkingExperts') {
            $filter_query .= " AND p.deleted_at IS null AND p.lastActiveOnAssessment IS NOT NULL ";
        }

        $data = '';
        if ($userType == 'admin') {
            //$data = "select * from `panel` where deleted_at is null"; 
            // $data = "select u.createdOn as signUpDate,u.id as candidateId,s.stream,p.* from panel p left outer join users u on p.id = u.panelId left outer join professionaldetails pd on pd.candidateId=u.id inner join stream s on pd.specialization = s.id " . $filter_query . $order_Query;
            // keerthi 05 July 2023
            $data = "select u.createdOn as signUpDate,u.id as candidateId,s.stream,(CASE WHEN p.experience IS NOT NULL THEN p.experience ELSE TIMESTAMPDIFF(YEAR, p.lastContactDate, NOW()) END) AS yearsOfExperience,p.* from panel p left outer join users u on p.id = u.panelId left outer join professionaldetails pd on pd.candidateId=u.id inner join stream s on pd.specialization = s.id " . $filter_query . $order_Query;
        }
        if ($data != '') {
            $query = mysqli_query($databaseConnection, $data . $limit_query);
            $count_query = mysqli_query($databaseConnection, "select count(p.id) as count_result from panel p left outer join users u on p.id = u.panelId left outer join professionaldetails pd on pd.candidateId=u.id inner join stream s on pd.specialization = s.id " . $filter_query . " " . $order_Query . ";");

            if (mysqli_num_rows($query) >= 1) {
                $count_result = mysqli_fetch_assoc($count_query);
                $values = array();
                while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
                    $row['url'] = "/finbox?pid=" . $row['id'];
                    $row['picture'] = 'panel_' . $row['id'] . '.png';
                    $areaOfQuery = mysqli_query($databaseConnection, "SELECT group_concat(fs.favourite_subject SEPARATOR ', ') AS areaOfExpertise_name FROM panel pd, favourite_subject fs WHERE FIND_IN_SET(fs.id, pd.areaOfExpertiseId) and pd.id = '" . $row['id'] . "'");
                    $areaOfResult = mysqli_fetch_array($areaOfQuery, MYSQLI_ASSOC);
                    $row['areaOfExpertise_name'] = $areaOfResult['areaOfExpertise_name'];
                    array_push($values, $row);
                }
                $to_encode = array(
                    'result' => "success",
                    'status' => 1,
                    'data' => $values,
                    'count' => $count_result['count_result'],
                    'query' => $data . $limit_query

                );
            } else {
                $to_encode = array(
                    'result' => "error",
                    'status' => 0,
                    'query' => $data . $limit_query,
                    'errorCode' => "in Error while retrieving User information."
                );
            }
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "in Error You are not having access this page."
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving User information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getContentWorkLogData'])) {
    /* this added by Naraayn 9-Nov for expertoring expert content work */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userType = $json['userType'];
        $data = '';
        if ($userType == 'admin') {
            $data = "select  ecl.expertId,p.name, ecl.questionId,ecl.delegationType,ecl.attempt,ecl.status,ecl.createdAt,ecl.updatedAt from expert_content_log ecl inner join panel p on p.id = ecl.expertId order by ecl.updatedAt,p.name";
        }
        if ($data != '') {
            $query = mysqli_query($databaseConnection, $data);
            if (mysqli_num_rows($query) >= 1) {
                $values = array();
                while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
                    array_push($values, $row);
                }
                $to_encode = array(
                    'result' => "success",
                    'status' => 1,
                    'data' => $values,

                );
            } else {
                $to_encode = array(
                    'result' => "error",
                    'status' => 0,
                    'query' => $data,
                    'errorCode' => "in Error while retrieving User information."
                );
            }
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "in Error You are not having access this page."
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving User information"
        );
    }
    echo json_encode($to_encode);

} elseif (isset($_GET['updateWorkTypeForExpert'])) {
    /* Type of WOrk update By Admin */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $panelId = $json['panelId'];

        $sql = "UPDATE `panel` SET `isVideoApproved`='" . $json['contentVideo'] . "',`isAssessmentApproved`='" . $json['assessment'] . "',`ispeerApproved`='" . $json['peerVideo'] . "', `isTaggingApproved`='" . $json['taggingVideo'] . "', `underTesting`='" . $json['underTesting'] . "',`onHold`='" . $json['onHold'] . "',`onHoldComment`='" . $json['onHoldComment'] . "',`addQuestionorReview`='" . $json['addQuestionorReview'] . "' where deleted_at is null  and id = " . $panelId;

        $panel_transql = "UPDATE `panels_transection` SET `isExpertVideoApproved`='" . $json['contentVideo'] . "',`isExpertAssessmentApproved`='" . $json['assessment'] . "',`isExpertpeerApproved`='" . $json['peerVideo'] . "', `isExpertTaggingApproved`='" . $json['taggingVideo'] . "',`onHold`='" . $json['onHold'] . "',`onHoldComment`='" . $json['onHoldComment'] . "',`addQuestionorReview`='" . $json['addQuestionorReview'] . "' where panelId = " . $panelId;
        $panels_transUpdate = mysqli_query($databaseConnection, $panel_transql);

        if (mysqli_query($databaseConnection, $sql)) {
            $to_encode = array(
                'status' => 1,
                'result' => "success",
                'query' => $sql
            );
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "Error while updating Type Panel"
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "Error while updating Panel"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['ApprovedPanel'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $panelId = $json['panelId'];

        $sql = "UPDATE `panel` SET `expertStatus`='1' where deleted_at is null  and id = " . $panelId;

        if (mysqli_query($databaseConnection, $sql)) {
            $to_encode = array(
                'status' => 1,
                'result' => "success"
            );
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "Error while approving Panel"
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "Error while approving Panel"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['RejectPanel'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $panelId = $json['panelId'];
        $sql = "UPDATE `panel` SET expertStatus='-1'  WHERE `panel`.`id` = " . $panelId;
        //$userSql = "UPDATE `users` set panelId='0',usertype='student' where panelId='".$panelId."' ";
        if (mysqli_query($databaseConnection, $sql)) {
            $to_encode = array(
                'status' => 1,
                'result' => "success"
            );
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "Error while Rejecting Panel"
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => " Error while Rejecting Panel"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['PublishedPanel'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $panelId = $json['panelId'];
        $publishStatus = $json['publishStatus'];
        $sql = "UPDATE `panel` SET publishStatus='" . $publishStatus . "' WHERE `panel`.`id` = " . $panelId;
        if (mysqli_query($databaseConnection, $sql)) {
            $to_encode = array(
                'status' => 1,
                'result' => "success"
            );
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "Error while Publishing Panel"
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => " Error while Publishing Panel"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getDelegatePanelList'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $panel_id = $json['panel_id'];

        if ($json['fbr_delegate']) {
            $data = "select * from `panel` where deleted_at is null and expertStatus=1 and id not in ('" . $json['fbr_delegate'] . "') order by name";
        } else {
            $data = "select * from `panel` where deleted_at is null and expertStatus=1 and id not in ('" . $panel_id . "') order by name";
        }

        $query = mysqli_query($databaseConnection, $data);
        if (mysqli_num_rows($query) >= 1) {
            $values = array();
            $values = mysqli_fetch_all($query, MYSQLI_ASSOC);
            $to_encode = $values;
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "in Error while retrieving User information."
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while retrieving User information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['updateDelegateFeedback'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $panel_id = $json['panel_id'];
        $checkStatus = $json['checkStatus'];
        $feedbackRequestId = $json['feedbackRequestId'];

        $data2 = "select fr.* FROM feedback_request fr where fr.id = '" . $feedbackRequestId . "'";
        $query2 = mysqli_query($databaseConnection, $data2);
        $values = mysqli_fetch_assoc($query2);

        if ($values['review_status'] != 2) {
            $data = "update feedback_request set delegationId = '" . $panel_id . "' where id = '" . $feedbackRequestId . "'";
            $query = mysqli_query($databaseConnection, $data);
        } else if ($values['review_status'] == 2) {
            $query = 1;
        }

        $feedbackQry = "update feedback_status_question set expertId = '" . $panel_id . "' where feedbackRequestId = '" . $feedbackRequestId . "' and expertId is null and review_status!=2";
        $result = mysqli_query($databaseConnection, $feedbackQry);

        if ($checkStatus == 'true') {
            $data3 = "update expert_review set feedbackGivenBy = '" . $panel_id . "' where feedback_request_id = '" . $feedbackRequestId . "'";
            $query3 = mysqli_query($databaseConnection, $data3);

            $feedbackQry2 = "update feedback_status_question set expertId = '" . $panel_id . "' where feedbackRequestId = '" . $feedbackRequestId . "'";
            $result2 = mysqli_query($databaseConnection, $feedbackQry2);
        }

        if ($values['review_status'] == 0 || $values['review_status'] == 1) {
            $date = new DateTime(date("Y-m-d"));
            $date->modify('+7 day');
            $fbDeliveryDATE = $date->format('Y-m-d');

            $userQuery = "SELECT CONCAT(firstName, ' ', IFNULL(lastName, '')) AS candidateName, emailId AS candidateEmail, mobileNumber AS candidateMobileNumber FROM users WHERE id = " . $values['candidateId'];
            $userQueryResult = mysqli_query($databaseConnection, $userQuery);
            $candidateDetails = $userQueryResult->fetch_assoc();

            $interviewQuery = "SELECT i.id AS interviewId, i.name AS interviewname, i.description AS interviewDescription, " . " p.id AS panelId, p.name AS panelName, p.emailid AS panelEmail, p.phonenumber AS panelPhoneNumber " . " FROM interview AS i, panel AS p " . " WHERE p.id = i.panelId AND i.id = " . $values['interviewId'];
            $interviewQueryResult = mysqli_query($databaseConnection, $interviewQuery);
            $interviewDetails = $interviewQueryResult->fetch_assoc();

            $contactDetails = array();
            $panelData = "select * from panel where id = '" . $panel_id . "'";
            $panelQuery = mysqli_query($databaseConnection, $panelData);
            $panelValues = mysqli_fetch_assoc($panelQuery);
            $contact['contactEmail'] = $panelValues['emailId'];
            $contact['contactName'] = $panelValues['name'];
            array_push($contactDetails, $contact);

            expertReviewWithFeedbackEmail($contactDetails, $candidateDetails, $interviewDetails, $fbDeliveryDATE);
        }

        if ($query && $query2 && $result) {
            $to_encode = array(
                'result' => "success",
                'status' => 1,
                'message' => "Delegation Successfull."
            );
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "in Error while retrieving User information."
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while retrieving User information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['deletePanel'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $panelId = $json['panelId'];
        /*Changes By anil 03-10-2018*/
        // $sql="update panel set when deleted_at is null then deleted_at='".date('Y-m-d H:i:s')."' where id=".$panelId;
        $sql = "UPDATE `panel` SET `deleted_at` = CASE when deleted_at is null THEN CURRENT_DATE else null end WHERE `panel`.`id` = " . $panelId;
        /*Changes By anil 03-10-2018*/
        //$sql="update panel set deleted_at='".date('Y-m-d H:i:s')."' where id=".$panelId;
        if (mysqli_query($databaseConnection, $sql)) {
            $to_encode = array(
                'status' => 1,
                'result' => "success"
            );
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "out Error while retrieving User information"
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving User information"
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['checkDataFiledByExpert'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $expertId = mysqli_query($databaseConnection, "select panelId from users where id='" . $userId . "'");
        $expertIdResult = mysqli_fetch_assoc($expertId);
        $id = $expertIdResult['panelId'];
        $areaOfExperties = mysqli_query($databaseConnection, "SELECT areaOfExpertiseId,id,name,emailId,experience from panel where id='" . $id . "' and deleted_at is null ");

        if (mysqli_num_rows($areaOfExperties) > 0) {
            $areaOfExpertiesResult = mysqli_fetch_all($areaOfExperties, MYSQLI_ASSOC);
            $to_encode = array(
                'area' => $areaOfExpertiesResult,
                'message' => 'success',
                'status' => 1,
            );
        } else {
            $to_encode = array(
                'message' => 'error',
                'status' => 0,
            );
        }

    }
    echo json_encode($to_encode);

} elseif (isset($_GET['updatePanel'])) {

    /*$data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {*/
    $panelId = $_POST['panelId'];
    $collegeQ = "select id from colleges where collegeName='" . addslashes($_POST['college']) . "'";
    $collegeQuery = mysqli_query($databaseConnection, $collegeQ);
    if (mysqli_num_rows($collegeQuery) > 0) {
        $collegeResult = mysqli_fetch_assoc($collegeQuery);
        $updateUserCollege = mysqli_query($databaseConnection, "UPDATE `professionaldetails` SET `college`='" . $collegeResult['id'] . "' WHERE candidateId ='" . $_POST['candidateId'] . "' ");
    }
    $updateExpertDetailInUsers = mysqli_query($databaseConnection, "UPDATE `users` SET `emailId`='" . $_POST['emailId'] . "', `mobileNumber` ='" . $_POST['phoneNumber'] . "', `userName`='" . $_POST['emailId'] . "'  WHERE id ='" . $_POST['candidateId'] . "' ");
    $areaOfExpertises = $_POST['areaOfExpertise'];
    $otherAreaOfExpertises = $_POST['otherAreaOfExpertise'];
    $otherAreaOfExpertisesValue = $_POST['otherAreaOfExpertiseValue'];
    $code = $_POST['coding'];
    $cloud = $_POST['cloudSubject'];
    $dataAnalyst = $_POST['dataAnalystSubject'];

    //$areaOfExpertises =  str_replace(',', ', ', $areaOfExpertise);
    $coding = str_replace(',', ', ', $code);
    $clouding = str_replace(',', ', ', $cloud);
    $dataAnalysting = str_replace(',', ', ', $dataAnalyst);
    $sql = "update panel set `name`='" . $_POST['name'] . "',`qualification`='" . $_POST['qualification'] . "',`oraganisation`='" . addslashes($_POST['college']) . "',`experience`='" . $_POST['experience'] . "',`companiesWorked`='" . addslashes($_POST['companiesWorkedFor']) . "',`emailId`='" . $_POST['emailId'] . "',`phonenumber`='" . $_POST['phoneNumber'] . "',`panelTitle`='" . $_POST['name'] . "',`linkedinProfile`='" . addslashes($_POST['linkedinProfile']) . "',`coding`='" . $coding . "', expertType='" . $_POST['expertType'] . "',areaOfExpertiseId='" . $areaOfExpertises . "', `otherAreaOfExpertiseId` = '" . $otherAreaOfExpertises . "', `otherAreaOfExpertiseValue` = '" . $otherAreaOfExpertisesValue . "',referrerName='" . $_POST['referrerName'] . "' ,whatsappNumber='" . $_POST['whatsappNo'] . "',`cloud`='" . $clouding . "',`dataAnalyst`='" . $dataAnalysting . "' where id=" . $panelId;
    /*Expert only update his/her type of work in panels_transection added by Narayn 19-05-2021*/
    $data_transection = "UPDATE `panels_transection` SET `isExpertConfirmLater`='" . $_POST['confirmLater'] . "',`isExpertAssessmentApproved`='" . $_POST['isAssessmentApproved'] . "',`isExpertVideoApproved`='" . $_POST['isVideoApproved'] . "',`isExpertPeerApproved`='" . $_POST['isPeerApproved'] . "',`addQuestionorReview`='" . $_POST['addQuestionorReview'] . "' WHERE panelId='" . $panelId . "'";
    $query_transection = mysqli_query($databaseConnection, $data_transection);
    if (mysqli_query($databaseConnection, $sql)) {
        if ($_POST['imgVal'] != "") {
            $filename = 'panel_' . $panelId; //panel_id
            $extension = pathinfo($_FILES["picture"]["name"], PATHINFO_EXTENSION); //png
            $basename = $filename . '.' . $extension;
            $file_tmp = $_FILES['picture']['tmp_name'];
            if (file_exists("../pracschool_app/public/images/" . $basename)) {
                unlink("../pracschool_app/public/images/" . $basename);
                move_uploaded_file($file_tmp, "../pracschool_app/public/images/" . $basename);
            } else {
                move_uploaded_file($file_tmp, "../pracschool_app/public/images/" . $basename);
            }
            $to_encode = array(
                'status' => 1,
                'result' => "img upload success"
            );
        }
        $to_encode = array(
            'status' => 1,
            'result' => "success"
        );
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "in Error while retrieving User information"
        );
    }
    /*} else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving User information"
        );
    }*/
    echo json_encode($to_encode);
} elseif (isset($_GET['getInterviewData'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        //$data='select * from `interview` where deleted_at is null';
        $data = "select i.*, fs.favourite_subject as subject_name from `interview` i left outer join favourite_subject fs on i.subject_id = fs.id WHERE i.categoryType != 9 order by id desc";

        $query = mysqli_query($databaseConnection, $data);
        if (mysqli_num_rows($query) >= 1) {
            $values = array();
            $categories = mysqli_query($databaseConnection, "select id, name from category where id != 5");
            $values['categories'] = mysqli_fetch_all($categories, MYSQLI_ASSOC);

            $industry = mysqli_query($databaseConnection, "select * from favourite_domain order by id=39,name");
            $values['industry'] = mysqli_fetch_all($industry, MYSQLI_ASSOC);

            $relavantRole = mysqli_query($databaseConnection, "select id, name from relavant_role order by id=29,name");
            $values['relavantRole'] = mysqli_fetch_all($relavantRole, MYSQLI_ASSOC);

            $subject = mysqli_query($databaseConnection, "select * from favourite_subject order by id=29,favourite_subject");
            $values['subject'] = mysqli_fetch_all($subject, MYSQLI_ASSOC);

            $concept = mysqli_query($databaseConnection, "select id, name from concepts order by id=1,name");
            $values['concept'] = mysqli_fetch_all($concept, MYSQLI_ASSOC);

            $key_skill = mysqli_query($databaseConnection, "select * from key_skill where id not in (4,5) order by key_skill");
            $values['key_skill'] = mysqli_fetch_all($key_skill, MYSQLI_ASSOC);

            $product_list = mysqli_query($databaseConnection, "select id,name from product order by id");
            $values['product_list'] = mysqli_fetch_all($product_list, MYSQLI_ASSOC);


            $stream = mysqli_query($databaseConnection, "select * from stream order by id=11,stream");
            $values['stream'] = mysqli_fetch_all($stream, MYSQLI_ASSOC);

            $assessmentParameters = mysqli_query($databaseConnection, "select id, observation_name as name from observation_area where key_skill not in (0,5) and mandatory='1' order by observation_name");
            $values['assessmentParameters'] = mysqli_fetch_all($assessmentParameters, MYSQLI_ASSOC);

            while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
                $category_query = mysqli_query($databaseConnection, "select * from category where id=" . $row['categoryType']);
                $category_name = '';
                if (mysqli_num_rows($category_query) >= 1) {
                    $category = mysqli_fetch_array($category_query, MYSQLI_ASSOC);
                    $category_name = $category['name'];
                }
                $panel_query = mysqli_query($databaseConnection, "select * from panel where id=" . $row['panelId']);
                $panel_name = '';
                if (mysqli_num_rows($panel_query) >= 1) {
                    $panel = mysqli_fetch_array($panel_query, MYSQLI_ASSOC);
                    $panel_name = $panel['name'];
                }

                $tutorialQuery = mysqli_query($databaseConnection, "select * from interview_tutorial where interviewId = '" . $row['id'] . "'");
                $tutorialLink = '';
                if (mysqli_num_rows($tutorialQuery) >= 1) {
                    $tutorialLink = mysqli_fetch_all($tutorialQuery, MYSQLI_ASSOC);
                }

                $row['tutorialLink'] = $tutorialLink;
                $row['panel_name'] = $panel_name;
                $row['category_name'] = $category_name;
                $row['status'] = ($row['isActive'] == 'Y') ? 'Published' : 'Inactive';
                $values['data'][] = $row;
            }
            $to_encode = $values;
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "in Error while retrieving Interview information."
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving Interview information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['interviewInfo'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $interviewId = $json['interviewId'];
        $sql = "select * from interview where id=" . $interviewId;
        $query = mysqli_query($databaseConnection, $sql);
        if (mysqli_num_rows($query) >= 1) {
            $values = array();
            $row = mysqli_fetch_array($query, MYSQLI_ASSOC);

            $tutorialQuery = mysqli_query($databaseConnection, "select * from interview_tutorial where interviewId = '" . $row['id'] . "'");
            $tutorialLink = '';
            if (mysqli_num_rows($tutorialQuery) >= 1) {
                $tutorialLink = mysqli_fetch_all($tutorialQuery, MYSQLI_ASSOC);
            }
            $row['tutorialLink'] = $tutorialLink;
            $assResult = "SELECT group_concat(ks.id SEPARATOR ', ') as key_skill_id  FROM key_skill ks WHERE FIND_IN_SET(ks.key_skill,'" . $row['assessmentParameters'] . "')";
            $ksQuery = mysqli_query($databaseConnection, $assResult);
            if (mysqli_num_rows($ksQuery) >= 1) {
                $assRow = mysqli_fetch_array($ksQuery, MYSQLI_ASSOC);
                $row['key_skill_id'] = $assRow['key_skill_id'];
            } else {
                $row['key_skill_id'] = null;
            }

            $values[] = $row;
            $to_encode = $values;
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "out Error while retrieving Interview information"
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving Interview information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['deleteInterview'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $interviewId = $json['interviewId'];
        //$sql="update interview set deleted_at='".date('Y-m-d H:i:s')."' where id=".$interviewId;
        $sql = "update interview set deleted_at = CASE when deleted_at is null THEN CURRENT_DATE else null end where id=" . $interviewId;
        if (mysqli_query($databaseConnection, $sql)) {
            $to_encode = array(
                'status' => 1,
                'result' => "success"
            );
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "out Error while retrieving Interview information"
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving Interview information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['updateInterview'])) {

    /*$data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {*/
    //$interviewId = $json['interviewId'];
    $interviewId = $_POST['interview_id'];
    $subject_id = $_POST['subject_id'];
    //$concept_id = $_POST['concept_id'];
    //$role = $json['role'];
    // $industry = $_POST['industry'];
    $targetAudience = str_replace(',', ', ', $_POST['targetAudience']);
    $streamSql = "SELECT group_concat(s.id SEPARATOR ',') as streamName from stream s WHERE FIND_IN_SET(s.stream,'" . $_POST['targetAudience'] . "')";
    $streamResult = mysqli_query($databaseConnection, $streamSql);
    $streamRow = mysqli_fetch_array($streamResult, MYSQLI_ASSOC);
    $streamIds = $streamRow['streamName'];
    $assessmentParameters = str_replace(',', ', ', $_POST['assessmentParameters']);
    if (isset($_POST["tutorialLink"]) && is_array($_POST["tutorialLink"])) {
        $numberOfLinks = count($_POST["tutorialLink"]);
    } else {
        $numberOfLinks = 0;
    }

    if ($_POST['otherSubject'] != "") {
        $subjectQuery = mysqli_query($databaseConnection, "insert into favourite_subject(favourite_subject) values ('" . addslashes($_POST['otherSubject']) . "');");
        $subject_id = mysqli_insert_id($databaseConnection);
    }

    /*if ($_POST['otherConcept'] != "") {
            $conceptQuery = mysqli_query($databaseConnection, "insert into concepts(name, subject_id) values ('".addslashes($_POST['otherConcept'])."', '".$subject_id."');");
            $concept_id = mysqli_insert_id($databaseConnection);
        }*/
    /*if ($json['otherRole'] != "") {
            $relavantRoleQuery = mysqli_query($databaseConnection, "insert into relavant_role(name) values ('".$json['otherRole']."');");
            $relavantRoleId = mysqli_insert_id($databaseConnection);
            $role = $json['otherRole'];
        }*/
    /* if ($_POST['otherIndustry'] != "") {
            $industryQuery = mysqli_query($databaseConnection, "insert into industry(name) values ('".addslashes($_POST['otherIndustry'])."');");
            $industryId = mysqli_insert_id($databaseConnection);
            $industry = addslashes($_POST['otherIndustry']);
        }*/
    $sql = "update interview set `categoryType`=" . $_POST['categorieId'] . ",`stream`='" . $streamIds . "', `name`='" . addslashes($_POST['name']) . "', `description`='" . addslashes($_POST['description']) . "', `isActive`='N', `interviewLevel`='" . $_POST['interviewLevel'] . "', `targetAudience`='" . $targetAudience . "', `duration`='" . addslashes($_POST['duration']) . "', `subject_id`='" . $subject_id . "', `productId`='" . $_POST['productId'] . "', `assessmentParameters` = '" . $assessmentParameters . "' where id=" . $interviewId;

    if (mysqli_query($databaseConnection, $sql)) {
        $sqlQuery = mysqli_query($databaseConnection, "select * from menu_subject_transection where menu_id = '" . $_POST['productId'] . "' and subject_id = '" . $subject_id . "'");
        if (mysqli_num_rows($sqlQuery) == 0) {
            $insertSqlQuery = mysqli_query($databaseConnection, "INSERT INTO `menu_subject_transection` (`menu_id`, `subject_id`) VALUES ('" . $_POST['productId'] . "', '" . $subject_id . "');");
            $menuInsertId = mysqli_insert_id($databaseConnection);
        }
        $tutorialLinkQuery = mysqli_query($databaseConnection, 'DELETE FROM `interview_tutorial` where interviewId=' . $interviewId);

        for ($i = 0; $i < $numberOfLinks; $i++) {
            if (trim($_POST["tutorialLink"][$i] != '')) {
                $link = "INSERT INTO interview_tutorial(interviewId, tutorial_link, remarks, topic_name) VALUES ('" . $interviewId . "', '" . addslashes($_POST["tutorialLink"][$i]) . "', '" . addslashes($_POST["linkDesc"][$i]) . "', '" . addslashes($_POST["topicName"][$i]) . "')";
                mysqli_query($databaseConnection, $link);
            }
        }

        $to_encode = array(
            'status' => 1,
            'result' => "success",
            'interviewId' => $interviewId,
            'interviewStatus' => 'N'
        );
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while updating Interview information"
        );
    }
    /*} else {
        $to_encode = array(
                    'status' => 0,
                    'result' => "error",
                    'errorCode' => "out Error while updating Interview information"
        );
    }*/
    echo json_encode($to_encode);
} elseif (isset($_GET['uploadMarketingDataIntoRawData'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $sql1 = mysqli_query($databaseConnection, "DELETE FROM `temprawdata` WHERE `email_id` = '' AND `contact_number` = '' AND `college_name` = ''");

        $sql2 = mysqli_query($databaseConnection, "update raw_data rd inner join temprawdata trd on rd.email_id = trd.email_id set rd.isPaid = trd.isPaid, rd.tieUpCollegeName = trd.college_name, rd.uploadedAt = NOW() where rd.signup_status = 1 and trd.isPaid in ('F','Y') ");

        $sql3 = mysqli_query($databaseConnection, "update raw_data rd inner join temprawdata trd on rd.email_id = trd.email_id set rd.isPaid = trd.isPaid,rd.uploadedAt = NOW() where rd.signup_status = 1 and trd.isPaid = 'N' ");

        $sql4 = mysqli_query($databaseConnection, "update raw_data rd inner join temprawdata trd on rd.email_id = trd.email_id set rd.isPaid = trd.isPaid, rd.contact_number = trd.contact_number, rd.candidate_name = trd.candidate_name, rd.college_name = trd.college_name, rd.stream = trd.stream, rd.yop = trd.yop , rd.tieUpCollegeName = trd.college_name, rd.uploadedAt = NOW() where rd.signup_status = 0  and trd.isPaid in ('F','Y') ");


        $sql5 = mysqli_query($databaseConnection, "update raw_data rd inner join temprawdata trd on rd.email_id = trd.email_id set rd.isPaid = trd.isPaid, rd.contact_number = trd.contact_number, rd.candidate_name = trd.candidate_name, rd.college_name = trd.college_name, rd.stream = trd.stream, rd.yop = trd.yop , rd.uploadedAt = NOW() where rd.signup_status = 0  and trd.isPaid = 'N' ");


        $sql6 = mysqli_query($databaseConnection, "INSERT INTO `raw_data`(`candidate_name`, `college_name`, `stream`, `yop`, `email_id`, `contact_number`, `signup_status`, `isPaid`, `uploadedAt`) SELECT candidate_name, college_name, stream, yop, email_id, contact_number, 0, isPaid, NOW() FROM `temprawdata` WHERE `email_id` NOT IN (SELECT `email_id` FROM `raw_data` GROUP BY `email_id`)");
        $sql7 = mysqli_query($databaseConnection, "delete from temprawdata");
        $sql8 = mysqli_query($databaseConnection, "update raw_data set tieUpCollegeName = college_name where isPaid in ('Y','F') and tieUpCollegeName is null");

        if ($sql1 && $sql2 && $sql3 && $sql4 && $sql5 && $sql6 && $sql7 && $sql8) {
            $to_encode = array(
                'status' => 1,
                'result' => "success"

            );
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "in Error while updating Interview information"
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while updating Interview information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['uploadMarketingData'])) {
    $insertedId = '';
    $rowWithError = '';
    if ($_FILES['excelfile']) {
        $file = $_FILES['excelfile']['tmp_name'];
        //$skip_row_number = array("1");
        $handle = fopen($file, "r");
        $count = 1;
        $sql1 = mysqli_query($databaseConnection, "delete from temprawdata");
        $row = fgetcsv($handle, 1000, ",");
        while (($row = fgetcsv($handle, 1000, ",")) !== false) {
            $count = $count + 1;
            $candidate_name = $row[0];
            $college_name = addslashes($row[1]);
            $stream = $row[2];
            $yop = $row[3];
            $email_id = trim($row[4], " ");
            $contact_number = ltrim($row[5]);
            $contact_number_length = strlen($contact_number);
            $isPaid = ltrim($row[6]);
            if ($candidate_name == '' || $college_name == '' || $email_id == '' || $contact_number == '' || $contact_number_length != 10) {
                $rowWithError = $rowWithError . " Data is not correct in row no " . $count;
                break;
            }
            $query = "INSERT INTO temprawdata (candidate_name,college_name,stream,yop,email_id,contact_number,isPaid) VALUES ('$candidate_name','$college_name','$stream', $yop,'$email_id','$contact_number','$isPaid')";
            $result = mysqli_query($databaseConnection, $query);
            if (!$result) {
                $rowWithError = $rowWithError . " Data is not correct in row no " . $count;
                break;
            }
            $intserts = mysqli_insert_id($databaseConnection);
            $insertedId = $insertedId . $intserts . '", "';
        }
        fclose($handle);
        if ($rowWithError != '') {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'message1' => "Hi",
                'query' => "INSERT INTO temprawdata (candidate_name,college_name,stream,yop,email_id,contact_number,isPaid) VALUES ('$candidate_name','$college_name','$stream', $yop,'$email_id','$contact_number','$isPaid')",
                'message' => "Please check all data  of Row No " . $count . " after correcting data please upload it againg"
            );
        } elseif ($result) {
            $to_encode = array(
                'status' => 1,
                'result' => "success",
                'data' => $insertedId,
                'count' => $count
            );
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'query' => "INSERT INTO temprawdata (candidate_name,college_name,stream,yop,email_id,contact_number,isPaid) VALUES ('$candidate_name','$college_name','$stream', $yop,'$email_id','$contact_number','$isPaid')",
                'message' => "Please check all data  of Row No " . $count . " after correcting data please upload it againg"
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while inserting data information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['publishInterview'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $interviewId = $json['interviewId'];
        $sql = "update interview set `isActive`='Y' where id=" . $interviewId;
        if (mysqli_query($databaseConnection, $sql)) {
            $to_encode = array(
                'status' => 1,
                'result' => "success"
            );
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "in Error while updating Interview information"
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while updating Interview information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getRecommendedInterviews'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];

        $sql = "select i.id as interviewId, i.name as interviewname, description as interviewDescription, i.assessmentParameters, i.keyArea, p.name as panelname, panelDescription from interview i, panel p where i.panelId = p.id and i.isActive = 'Y' and i.deleted_at is null and i.categoryType in (1,2,7,8) order by i.name;";
        $query = mysqli_query($databaseConnection, $sql);
        if (mysqli_num_rows($query) >= 1) {
            $row = mysqli_fetch_all($query, MYSQLI_ASSOC);
            $to_encode = $row;
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "no data found"
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while retrieving Interview information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getCategoryType'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $interviewId = $json['interviewId'];
        $candidateId = $json['candidateId'];
        $categoryType = $json['categoryType'];

        $sql3 = "select id,collegeName as college from colleges order by id=188,collegeName;";
        $query3 = mysqli_query($databaseConnection, $sql3);

        $sql4 = "select * from stream where isActive = 'Y' order by id=11,stream";
        $query4 = mysqli_query($databaseConnection, $sql4);
        $result4 = mysqli_fetch_all($query4, MYSQLI_ASSOC);

        /*$sql5 = "select * from qualification order by qualification";
        $query5 = mysqli_query($databaseConnection, $sql5);
        $result5 = mysqli_fetch_all($query5, MYSQLI_ASSOC);*/

        if (mysqli_num_rows($query3) >= 1) {

            $result3 = mysqli_fetch_all($query3, MYSQLI_ASSOC);
            $sql2 = "select count(distinct interviewSessionId)+100 as totalAttendedInterview from mergedVideos where interviewId = '" . $interviewId . "';";
            $query2 = mysqli_query($databaseConnection, $sql2);
            $result2 = mysqli_fetch_assoc($query2);

            if ($categoryType == 2 || $categoryType == 3) {
                $sql = "select e.*,c.description as collegeDescription from event e left outer join colleges c on e.collegeId = c.id where e.interviewId = '" . $interviewId . "' ORDER BY e.id DESC;";
                $query = mysqli_query($databaseConnection, $sql);
                $result = mysqli_fetch_assoc($query);

                $checkRegistration = "select if((select count(*) from event_registration where userId = '" . $candidateId . "' and eventId = '" . $result['id'] . "' and categoryType =  '" . $categoryType . "')=1, 'Y', 'N') as registered;";
                $checkRegistrationQuery = mysqli_query($databaseConnection, $checkRegistration);
                if (mysqli_num_rows($checkRegistrationQuery) >= 1) {
                    $checkRegistrationValues = mysqli_fetch_all($checkRegistrationQuery, MYSQLI_ASSOC);
                }
            } else {
                $result['startTime'] = null;
                $result['endTime'] = null;
                $result['id'] = NULL;
                $result['name'] = NULL;
                $checkRegistrationValues[0]['registered'] = null;
                $result['collegeDescription'] = null;
                $result['collegeId'] = null;
                $result['eventDescription'] = null;
                $result['description'] = null;
            }

            $to_encode = array(
                'status' => 1,
                'message' => "success",
                'totalAttendedInterview' => $result2['totalAttendedInterview'],
                'startTime' => $result['startTime'],
                'endTime' => $result['endTime'],
                'registered' => $checkRegistrationValues[0]['registered'],
                'eventId' => $result['id'],
                'eventDescription' => $result['description'],
                'name' => $result['name'],
                'collegeList' => $result3,
                'stream' => $result4,
                'collegeDescription' => $result['collegeDescription'],
                'collegeId' => $result['collegeId']
            );
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "in Error while retrieving Interview information"
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while retrieving Interview information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getInterviewQuestionData'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $interviewId = $json['interviewId'];
        $totalQuestionStatus = 0;
        $data = '';

        $values = array();
        $interviews = mysqli_query($databaseConnection, "select id, name from interview order by name");
        $values['interviews'] = mysqli_fetch_all($interviews, MYSQLI_ASSOC);

        $topic = mysqli_query($databaseConnection, "select * from topic order by id=1,name");
        $values['topic'] = mysqli_fetch_all($topic, MYSQLI_ASSOC);

        $key_skill = mysqli_query($databaseConnection, "select * from key_skill where id not in (4,5)");
        $values['key_skill'] = mysqli_fetch_all($key_skill, MYSQLI_ASSOC);

        $data = "select q.*,iqt.interviewId, iqt.sequence,iqt.deleted_at as deletedQuestion,t.name as topic_name from `questions` q inner join interview_questions_transection iqt on iqt.questionId = q.id inner join interview i on i.id = iqt.interviewId left outer join topic t on q.topic_id = t.id where iqt.interviewId ='" . $interviewId . "' order by iqt.sequence";
        $query = mysqli_query($databaseConnection, $data);
        if (mysqli_num_rows($query) >= 1) {
            while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
                $row['questionHtml'] = nl2br($row['questionText']);
                $interview_query = mysqli_query($databaseConnection, "select * from interview where id=" . $interviewId);
                $interview_title = '';
                if (mysqli_num_rows($interview_query) > 0) {
                    $interview = mysqli_fetch_array($interview_query, MYSQLI_ASSOC);
                    $interview_title = $interview['name'];
                    $interviewStatus = $interview['isActive'];
                }

                $row['key_skill_name'] = '';
                $key_skill_id = explode(",", $row['key_skill_id']);
                $row['key_skill_id'] = '';
                $k = 0;
                for ($i = 0; $i < count($key_skill_id); $i++) {
                    for ($j = 0; $j < count($values['key_skill']); $j++) {
                        if ($key_skill_id[$i] == $values['key_skill'][$j]['id']) {
                            if ($k == 0) {
                                $row['key_skill_name'] = $values['key_skill'][$j]['key_skill'];
                                $row['key_skill_id'] = $key_skill_id[$i];
                                $k++;
                            } else {
                                $row['key_skill_name'] = $row['key_skill_name'] . ', ' . $values['key_skill'][$j]['key_skill'];
                                $row['key_skill_id'] = $row['key_skill_id'] . ',' . $key_skill_id[$i];
                                $k++;
                            }
                        }
                    }
                }
                /* deletedQuestion is question WHich is deleted from interview and deleted_at is question which is deleted from questionDashboard */
                if ($row['deleted_at'] == null && $row['deletedQuestion'] == null) {
                    $totalQuestionStatus++;
                }
                $row['interview_title'] = $interview_title;
                $row['isActive'] = ($row['isActive'] == 'Y') ? 'Yes' : 'No';
                $row['isFollowUp'] = ($row['isFollowUp'] == 'Y') ? 'Yes' : 'No';
                $values['data'][] = $row;
            }
            if ($totalQuestionStatus == 0) {
                $values['interviewStatus'] = '';
            } else {
                $values['interviewStatus'] = $interviewStatus;
            }
            $to_encode = $values;
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "in Error while retrieving question information.",
                'qry' => $data . " limit " . $start . "," . $limit
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'errorCode' => "out Error while retrieving Interview information"
        );
    }
    echo json_encode($to_encode);
}
//node-api
elseif (isset($_GET['getQuestionData'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    $limit = 200;
    $start = 0;
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $main_data = array();
        $filter_query = " where 1 ";
        $limit = $json['limit'];
        $having_query1 = " having 1 ";
        $start = ($json['page'] - 1) * $limit;
        $groupby_query = " group by q.id ";
        $order_query = " order by q.id desc";
        $limit_query = $limit == 0 ? "" : " limit " . $start . "," . $limit;


        if ($json['subject'] != "" and sizeof($json['subject']) > 0)
            $filter_query .= " and q.subjectId in ('" . implode("', '", $json['subject']) . "')";


        $alternateQuestionStatus = isset($json['alternateQuestionStatus']) ? $json['alternateQuestionStatus'] : '';
        if ($alternateQuestionStatus !== "") {
            if ($alternateQuestionStatus == "Not-Available") {
                $filter_query .= " and q.alternateQuestionStatus IS NULL";
            } elseif ($alternateQuestionStatus == "In-Progress") {
                $filter_query .= " and q.alternateQuestionStatus IN('0','1')";
            } elseif ($alternateQuestionStatus == "Available") {
                $filter_query .= " and q.alternateQuestionStatus IN('2')";
            } elseif ($alternateQuestionStatus == "Reviewed") {
                $filter_query .= " and q.alternateQuestionStatus IN('4')";
            } elseif ($alternateQuestionStatus == "Error") {
                $filter_query .= " and q.alternateQuestionStatus IN('3')";
            }
        }

        if ($json['keySkill'] != "" and sizeof($json['keySkill']) > 0)
            $filter_query .= " and " . getMultipleFindInSet($json['keySkill'], "q.key_skill_id");

        if ($json['topic'] != "" and sizeof($json['topic']) > 0)
            $filter_query .= " and q.topic_id in ('" . implode("', '", $json['topic']) . "')";

        if ($json['isWbRequired'] != "")
            $filter_query .= " and q.isWbRequired like '" . $json['isWbRequired'] . "'";

        if ($json['questionLevel'] != "" and $json['questionLevel'] != [""] and sizeof($json['questionLevel']) > 0)
            $filter_query .= " and q.questionLevel in ('" . implode("', '", $json['questionLevel']) . "')";


        if ($json['questionId'] != "")
            $filter_query .= " and q.id in (" . $json['questionId'] . ")";


        if ($json['questionType'] != "") {
            if ($json['questionType'] == "Start") {
                $filter_query .= " and q.questionType = 'Start'";
            } elseif ($json['questionType'] == "Universal") {
                $filter_query .= " and q.questionType = 'Universal'";
            } elseif ($json['questionType'] == "Climax") {
                $filter_query .= " and q.questionType = 'Climax'";
            } else {
                $filter_query .= " and (q.questionType = 'Thank You' or  q.shortExpectedAns= 'Thank You' or q.subjectId = 154) ";
            }
        }

        $questionStatus = isset($json['quesStatus']) ? $json['quesStatus'] : array();
        if ($questionStatus != "" and sizeof($questionStatus) > 0) {
            if ($questionStatus != [""]) {
                $filter_ques = "0 ";
                foreach ($questionStatus as $qStatus) {
                    if ($qStatus == "rawQus") {
                        $filter_ques .= " OR (q.deleted_at is null and (q.expertApproval ='N' or (q.eligibleStreamId = '' OR q.eligibleStreamId IS  NULL OR q.subjectId = '' OR q.subjectId IS  NULL OR q.conceptId = '' OR q.conceptId IS  NULL OR q.key_skill_id = '' OR q.key_skill_id IS  NULL OR q.topic_id = '' OR q.topic_id IS  NULL OR q.isWbRequired = '' OR q.isWbRequired IS  NULL OR q.questionLevel = '' OR q.questionLevel IS  NULL))) ";
                    } elseif ($qStatus == "inactive") {
                        $filter_ques .= " OR q.deleted_at is not null ";
                    } elseif ($qStatus == "readyToUse") {
                        $filter_ques .= " OR  (q.deleted_at is null and q.expertApproval = 'Y' and (q.eligibleStreamId != '' AND q.eligibleStreamId IS NOT NULL AND q.subjectId != '' AND q.subjectId IS NOT NULL AND q.conceptId != '' AND q.conceptId IS NOT NULL AND q.key_skill_id != '' AND q.key_skill_id IS NOT NULL AND q.topic_id != '' AND q.topic_id IS NOT NULL AND q.isWbRequired != '' AND q.isWbRequired IS NOT NULL AND q.questionLevel != '' AND q.questionLevel IS NOT NULL)) ";
                    } elseif ($qStatus == "readyUpdatedUse") {
                        $filter_ques .= " OR (q.deleted_at is null and q.expertAdvice is not null  and (q.peerResponseVideo is not null or q.mbr_id != '0')  and  q.youtubeId !=314664775) ";
                    }
                }
                $filter_query .= " and (" . $filter_ques . ")";
            }
        }
        if ($json['quesType'] != "") {
            if ($json['quesType'] == "thankYou") {
                $filter_query .= "  and q.shortExpectedAns= 'Thank You'";
            } elseif ($json['quesType'] == "parent") {
                $filter_query .= " and q.followUp   = 'Parent' ";
            } elseif ($json['quesType'] == "single") {
                $filter_query .= " and q.followUp   = 'Single' ";
            } elseif ($json['quesType'] == "child1") {
                $filter_query .= " and q.followUp = 'Child 1'";
            } elseif ($json['quesType'] == "child2") {
                $filter_query .= " and q.followUp = 'Child 2'";
            } elseif ($json['quesType'] == "child3") {
                $filter_query .= " and q.followUp = 'Child 3'";
            } elseif ($json['quesType'] == "child4") {
                $filter_query .= " and q.followUp = 'Child 4'";
            } elseif ($json['quesType'] == "child5") {
                $filter_query .= " and q.followUp = 'Child 5'";
            } elseif ($json['quesType'] == "child6") {
                $filter_query .= " and q.followUp = 'Child 6'";
            }
        }
        if ($json['frequencyUsage'] != "") {
            if ($json['frequencyUsage'] == '0') {
                $having_query1 .= " and frequency = 0";
            } elseif ($json['frequencyUsage'] == '1-10') {
                $having_query1 .= " and frequency between 1 AND 10 ";
            } elseif ($json['frequencyUsage'] == '10-50') {
                $having_query1 .= " and  frequency between 11 AND 50";
            } elseif ($json['frequencyUsage'] == '50+') {
                $having_query1 .= " and frequency >50 ";
            }
        }

        if ($json['vimeoId'] != "") {
            $filter_query .= " and q.youtubeId in (" . $json['vimeoId'] . ")";
        }

        $synchQuery = mysqli_query($databaseConnection, "select synched_at from synch_log where table_name = 'bestPeerResponse' order by id desc limit 0,1");
        $synchResult = mysqli_fetch_assoc($synchQuery);
        /* change by Narayan 6/8/2021 for personalized video feedback status added in query */
        $query = "select q.*,(select count(questionId) as feedbackVideo from expert_review where feedbackVideoURL is not null and rejected='N' and questionId=q.id) AS videoFeedback,(SELECT COUNT(DISTINCT iqt.interviewId) FROM `interview_questions_transection` iqt WHERE iqt.noOfSkip IS NULL AND iqt.noOfRespond IS NULL AND iqt.interviewId is not null AND iqt.questionId = q.id) AS usedStreamCount,CASE WHEN q.deleted_at is not null THEN 'Trashed'  WHEN (q.deleted_at is null and q.expertAdvice is not null  and (q.peerResponseVideo is not null or q.mbr_id != '0')  and  q.youtubeId !=314664775) THEN 'Ready toUse Plus' WHEN (q.deleted_at is null and q.expertApproval = 'Y' and (q.eligibleStreamId != '' AND q.eligibleStreamId IS NOT NULL AND q.subjectId != '' AND q.subjectId IS NOT NULL AND q.conceptId != '' AND q.conceptId IS NOT NULL AND q.key_skill_id != '' AND q.key_skill_id IS NOT NULL AND q.topic_id != '' AND q.topic_id IS NOT NULL AND q.isWbRequired != '' AND q.isWbRequired IS NOT NULL AND q.questionLevel != '' AND q.questionLevel IS NOT NULL)) THEN 'Ready to use' WHEN ((q.deleted_at is null and q.expertApproval ='N') or (q.eligibleStreamId = '' OR q.eligibleStreamId IS  NULL OR q.subjectId = '' OR q.subjectId IS  NULL OR q.conceptId = '' OR q.conceptId IS  NULL OR q.key_skill_id = '' OR q.key_skill_id IS  NULL OR q.topic_id = '' OR q.topic_id IS  NULL OR q.isWbRequired = '' OR q.isWbRequired IS  NULL OR q.questionLevel = '' OR q.questionLevel IS  NULL)) THEN 'Raw Qns' ELSE 'Nothing' END AS questionStatus,count(DISTINCT fsq.id) as frequency, CASE WHEN q.expertAdvice IS NULL and qst.questionId IS NULL THEN 'Not Available' WHEN q.expertAdvice IS NULL and qst.questionId IS NOT NULL and qst.delegationType='guidanceVideo' and qst.uploadStatus !='2' THEN 'Delegated' WHEN q.expertAdvice IS  NOT NULL THEN 'Available' ELSE 'Not Available' END  as guidanceVideoStatus,CASE WHEN q.youtubeId = '314664775' and qst.questionId IS NULL THEN 'Not Available' WHEN q.youtubeId != '314664775' THEN 'Available' WHEN q.youtubeId = '314664775' and qst.questionId IS NOT NULL and qst.delegationType='questionVideo' and qst.uploadStatus !='2' THEN 'Delegated'  ELSE 'Not Available' END  as questionVideoStatus,t.name as topic_name, fs.favourite_subject as subject_name, c.name as concept_name,CASE WHEN (SELECT COUNT(DISTINCT iqt.questionId) FROM `interview_questions_transection` iqt WHERE iqt.noOfSkip IS NULL AND iqt.noOfRespond IS NULL AND iqt.questionId = q.id) > 0 THEN 'Yes' ELSE 'No' END as isQuestionUsed from questions q left outer join topic t on q.topic_id = t.id left outer join favourite_subject fs on fs.id = q.subjectId left outer join concepts c on c.id = q.conceptId left outer join questions_transection qst on qst.questionId = q.id left outer join feedback_status_question fsq on q.id = fsq.questionId left outer join feedback_request fr on  fsq.feedbackRequestId= fr.id";
        $data = '';
        $data = $query . $filter_query . $groupby_query . $having_query1 . $order_query;
        $CountQuery = "Select q.id,(select count(questionId) as feedbackVideo from expert_review where feedbackVideoURL is not null and rejected='N' and questionId=q.id) AS videoFeedback,count(DISTINCT fsq.id) as frequency,CASE WHEN (SELECT COUNT(DISTINCT iqt.questionId) FROM `interview_questions_transection` iqt WHERE iqt.noOfSkip IS NULL AND iqt.noOfRespond IS NULL AND iqt.questionId = q.id) > 0 THEN 'Yes' ELSE 'No' END as isQuestionUsed from questions q left outer join topic t on q.topic_id = t.id left outer join favourite_subject fs on fs.id = q.subjectId left outer join concepts c on c.id = q.conceptId left outer join questions_transection qst on qst.questionId = q.id  left outer join feedback_status_question fsq on q.id = fsq.questionId left outer join feedback_request fr on  fsq.feedbackRequestId= fr.id";
        $countData = $CountQuery . $filter_query . $groupby_query . $having_query1 . $order_query;


        $query = mysqli_query($databaseConnection, $data . $limit_query);
        if (mysqli_num_rows($query) > 0) {
            $count = mysqli_query($databaseConnection, $countData);
            $count_result = mysqli_num_rows($count);
            //$main_data = mysqli_fetch_all($query,MYSQLI_ASSOC);

            while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
                $row['questionHtml'] = nl2br($row['questionText']);
                if ($row['usedStreamCount'] > 0) {
                    $usedStaus = mysqli_query($databaseConnection, "Select i.name as InterviewName , p.name as ProductName,(select GROUP_CONCAT(DISTINCT s.stream SEPARATOR ', ') as streams from interview itw , stream s where itw.id = i.id and find_in_set(s.id,itw.stream) ) as streamName from interview_questions_transection iqt inner join questions q on q.id = iqt.questionId inner join interview i on i.id = iqt.interviewId inner join product p on p.id = i.productId where q.id = '" . $row['id'] . "';");
                    $row['usedStausList'] = mysqli_fetch_all($usedStaus, MYSQLI_ASSOC);
                } else {
                    $row['usedStausList'] = [];
                }

                $keySkillQuery = mysqli_query($databaseConnection, "SELECT q.key_skill_id, group_concat(ks.key_skill SEPARATOR ', ') AS key_skill_name FROM questions q, key_skill ks WHERE FIND_IN_SET(ks.id, q.key_skill_id) and q.id = '" . $row['id'] . "';");
                $keySkillResult = mysqli_fetch_array($keySkillQuery, MYSQLI_ASSOC);
                $row['key_skill_name'] = $keySkillResult['key_skill_name'];

                $eligibleStreamQuery = mysqli_query($databaseConnection, "SELECT q.eligibleStreamId, group_concat(s.stream SEPARATOR ', ') AS eligibleStreamName FROM questions q, stream s WHERE FIND_IN_SET(s.id, q.eligibleStreamId) and q.id = '" . $row['id'] . "';");
                $eligibleStreamResult = mysqli_fetch_array($eligibleStreamQuery, MYSQLI_ASSOC);
                $row['eligibleStreamName'] = $eligibleStreamResult['eligibleStreamName'];

                $questionVideoQuery = mysqli_query($databaseConnection, "SELECT questionId FROM `questions_transection` WHERE uploadStatus in (0,1) and delegationType='questionVideo' and questionId='" . $row['id'] . "';");
                if (mysqli_num_rows($questionVideoQuery) > 0) {
                    $row['questionVideoStatus'] = 'Delegated';
                }
                $guidanceVideoQuery = mysqli_query($databaseConnection, "SELECT questionId FROM `questions_transection` WHERE uploadStatus in (0,1) and delegationType='guidanceVideo' and questionId='" . $row['id'] . "';");
                if (mysqli_num_rows($questionVideoQuery) > 0) {
                    $row['guidanceVideoStatus'] = 'Delegated';
                }

                /* this for total peer response video available count  which is not rejected by admin */
                if ($row['peerResponseStatus'] == 'A') {
                    $getAvailableCount = mysqli_query($databaseConnection, "select count(temp.id) as peerAvailableCount from  (select er.id from mergedVideos m inner join feedback_request fr on fr.interviewSessionId = m.interviewSessionId inner join expert_review er on er.feedback_request_id = fr.id where m.interviewSessionId is not null and m.rejected='N' and  er.questionId = '" . $row['id'] . "' and fr.review_status='2' and er.overallRating > 4 and er.overallRating !='videoIssue' group by fr.interviewSessionId) as temp");
                    $PeerAvailableCountResult = mysqli_fetch_array($getAvailableCount, MYSQLI_ASSOC);
                    $row['peerAvailableCount'] = $PeerAvailableCountResult['peerAvailableCount'];
                }
                /* this for total peer response video selected count */
                if ($row['peerResponseStatus'] != 'A' && $row['peerResponseStatus'] != 'NA' && $row['mbr_id'] == 0) {
                    $row['selectedPeerCount'] = count(explode(',', $row['peerResponseStatus']));
                }


                array_push($main_data, $row);
            }
            $to_encode = array(
                'result' => "success",
                'status' => 1,
                'data' => $main_data,
                'count' => $count_result,
                'synched_at' => timeAgo($synchResult['synched_at'])
            );
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'synched_at' => timeAgo($synchResult['synched_at']),
                'errorCode' => "in Error while retrieving question information.",
                'qry' => $data . " limit " . $start . "," . $limit
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while retrieving question information"
        );
    }
    echo json_encode($to_encode);
}
elseif (isset($_GET['exportQuestionData'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    $limit = 200;
    $start = 0;
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $main_data = array();
        $filter_query = " where 1 ";
        $limit = $json['limit'];
        $start = ($json['page'] - 1) * $limit;
        $groupby_query = " group by q.id";
        $order_query = " order by q.id";
        $having_query1 = " having 1 ";
        $limit_query = $limit == 0 ? "" : " limit " . $start . "," . $limit;
        $execute = true;

        if ($json['eligibleStream'] != "" and sizeof($json['eligibleStream']) > 0)
            $filter_query .= " and " . getMultipleFindInSet($json['eligibleStream'], "q.eligibleStreamId");
        if ($json['subject'] != "" and sizeof($json['subject']) > 0)
            $filter_query .= " and q.subjectId in ('" . implode("', '", $json['subject']) . "')";
        /*if($json['domain']!="" AND sizeof($json['domain']) > 0)
            $filter_query.=" and ".getMultipleFindInSet($json['domain'], "q.domainId");*/
        if ($json['concept'] != "" and sizeof($json['concept']) > 0)
            $filter_query .= " and q.conceptId in ('" . implode("', '", $json['concept']) . "')";
        if ($json['keySkill'] != "" and sizeof($json['keySkill']) > 0)
            $filter_query .= " and " . getMultipleFindInSet($json['keySkill'], "q.key_skill_id");
        if ($json['topic'] != "" and sizeof($json['topic']) > 0)
            $filter_query .= " and q.topic_id in ('" . implode("', '", $json['topic']) . "')";
        if ($json['isWbRequired'] != "")
            $filter_query .= " and q.isWbRequired like '" . $json['isWbRequired'] . "'";
        if ($json['questionLevel'] != "" and $json['questionLevel'] != [""] and sizeof($json['questionLevel']) > 0)
            $filter_query .= " and q.questionLevel in ('" . implode("', '", $json['questionLevel']) . "')";
        if ($json['peerResponseStatus'] != "") {
            if ($json['peerResponseStatus'] == "NA" || $json['peerResponseStatus'] == "A") {
                $filter_query .= " and q.peerResponseStatus in ('" . $json['peerResponseStatus'] . "')";
            } elseif ($json['peerResponseStatus'] == "selected") {
                $filter_query .= " and q.peerResponseStatus not in ('NA', 'A') and q.mbr_id = '0' and q.peerResponseVideo is null ";
            } elseif ($json['peerResponseStatus'] == "peerResponseVideo") {
                $filter_query .= " and q.peerResponseVideo is not null";
            } elseif ($json['peerResponseStatus'] == "delegated") {
                $filter_query .= " and qst.uploadStatus in (0,1) and qst.delegationType='peerResponseVideo'";
            } else {
                $filter_query .= " and q.mbr_id != '0'";
            }
        }
        if ($json['eAppStatus'] != "") {
            if ($json['eAppStatus'] == "Y") {
                $filter_query .= " and q.expertApproval = 'Y'";
            } else {
                $filter_query .= " and q.expertApproval = 'N'";
            }
        }
        if ($json['videoFeedback'] != "") {
            if ($json['videoFeedback'] == 1) {
                $having_query1 .= " and NoOfvideoFeedback > 0";
            } else {
                $having_query1 .= " and NoOfvideoFeedback = 0";
            }
        }
        /*if($json['highPriority']!=""){
            if($json['highPriority'] =="Y"){
                //$filter_query.=" and (q.highPriority = 'Y' or (DATEDIFF(sub.endDate,CURDATE())>=0 and fr.review_status in(0,1)) or (DATEDIFF(sub.endDate,CURDATE())>=0 and qst.uploadStatus in(0,1))) ";
                $filter_query.=" and (q.highPriority = 'Y' or (q.highPriority = 'N' and fr.priority in(1,2) AND fr.review_status in(0,1)) ) ";
            }else{
                //$filter_query.=" and ((q.highPriority = 'N' ) or (((fr.review_status is null and q.highPriority = 'N') OR (DATEDIFF(sub.endDate,CURDATE()) < 0 AND q.highPriority = 'N')) OR (DATEDIFF(sub.endDate,CURDATE()) >= 0 and fr.review_status =2 and qst.uploadStatus=2 ))) ";
                $filter_query.=" and (q.highPriority = 'N' or (q.highPriority = 'N' and fr.priority in(1,2) and fr.review_status not in(0,1)) or (q.highPriority = 'N' and fr.priority ='0') ) ";
            }
        }*/
        if ($json['highPriority'] != "") {
            if ($json['highPriority'] == "1") {
                $filter_query .= " and q.priorityStatus = '1'";
            } else if ($json['highPriority'] == "2") {
                $filter_query .= " and q.priorityStatus = '2'";
            } else {
                $filter_query .= " and q.priorityStatus = '0'";
            }
        }
        if ($json['frequencyUsage'] != "") {
            if ($json['frequencyUsage'] == '0') {
                $having_query1 .= " and  frequency = 0";
            } elseif ($json['frequencyUsage'] == '1-10') {
                $having_query1 .= " and frequency between 1 AND 10 ";
            } elseif ($json['frequencyUsage'] == '10-50') {
                $having_query1 .= " and frequency between 11 AND 50";
            } elseif ($json['frequencyUsage'] == '50+') {
                $having_query1 .= " and frequency >50 ";
            }
        }
        if ($json['questionId'] != "")
            $filter_query .= " and q.id in (" . $json['questionId'] . ")";
        if ($json['taggingStatus'] != "") {
            if ($json['taggingStatus'] == "complete") {
                $filter_query .= " and (q.eligibleStreamId != '' AND q.eligibleStreamId IS NOT NULL AND q.subjectId != '' AND q.subjectId IS NOT NULL AND q.conceptId != '' AND q.conceptId IS NOT NULL AND q.key_skill_id != '' AND q.key_skill_id IS NOT NULL AND q.topic_id != '' AND q.topic_id IS NOT NULL AND q.isWbRequired != '' AND q.isWbRequired IS NOT NULL AND q.questionLevel != '' AND q.questionLevel IS NOT NULL)";
            } elseif ($json['taggingStatus'] == "incomplete") {
                $filter_query .= " and qst.questionId is null and (q.eligibleStreamId = '' OR q.eligibleStreamId IS NULL OR q.subjectId = '' OR q.subjectId IS NULL OR q.conceptId = '' OR q.conceptId IS NULL OR q.key_skill_id = '' OR q.key_skill_id IS NULL OR q.topic_id = '' OR q.topic_id IS NULL OR q.isWbRequired = '' OR q.isWbRequired IS NULL OR q.questionLevel = '' OR q.questionLevel IS NULL)";
            } else {
                $filter_query .= " and qst.questionId is not null and qst.uploadStatus in (0,1) ";
            }
        }
        if ($json['questionType'] != "") {
            if ($json['questionType'] == "Start") {
                $filter_query .= " and q.questionType = 'Start'";
            } elseif ($json['questionType'] == "Universal") {
                $filter_query .= " and q.questionType = 'Universal'";
            } elseif ($json['questionType'] == "Climax") {
                $filter_query .= " and q.questionType = 'Climax'";
            } else {
                $filter_query .= " and (q.questionType = 'Thank You' or  q.shortExpectedAns= 'Thank You' or q.subjectId = 154) ";
            }
        }
        if ($json['quesStatus'] != "" and sizeof($json['quesStatus']) > 0) {
            $questionStatus = $json['quesStatus'];
            $filter_ques = "0 ";
            foreach ($questionStatus as $qStatus) {
                if ($qStatus == "rawQus") {
                    $filter_ques .= " OR (q.deleted_at is null and (q.expertApproval ='N' or (q.eligibleStreamId = '' OR q.eligibleStreamId IS  NULL OR q.subjectId = '' OR q.subjectId IS  NULL OR q.conceptId = '' OR q.conceptId IS  NULL OR q.key_skill_id = '' OR q.key_skill_id IS  NULL OR q.topic_id = '' OR q.topic_id IS  NULL OR q.isWbRequired = '' OR q.isWbRequired IS  NULL OR q.questionLevel = '' OR q.questionLevel IS  NULL))) ";
                } elseif ($qStatus == "inactive") {
                    $filter_ques .= " OR q.deleted_at is not null ";
                } elseif ($qStatus == "readyToUse") {
                    $filter_ques .= " OR  (q.deleted_at is null and q.expertApproval = 'Y' and (q.eligibleStreamId != '' AND q.eligibleStreamId IS NOT NULL AND q.subjectId != '' AND q.subjectId IS NOT NULL AND q.conceptId != '' AND q.conceptId IS NOT NULL AND q.key_skill_id != '' AND q.key_skill_id IS NOT NULL AND q.topic_id != '' AND q.topic_id IS NOT NULL AND q.isWbRequired != '' AND q.isWbRequired IS NOT NULL AND q.questionLevel != '' AND q.questionLevel IS NOT NULL)) ";
                } elseif ($qStatus == "readyUpdatedUse") {
                    $filter_ques .= " OR (q.deleted_at is null and q.expertAdvice is not null  and (q.peerResponseVideo is not null or q.mbr_id != '0')  and  q.youtubeId !=314664775) ";
                }
            }
            $filter_query .= " and (" . $filter_ques . ")";
        }
        if ($json['quesType'] != "") {
            if ($json['quesType'] == "thankYou") {
                $filter_query .= "  and q.shortExpectedAns= 'Thank You'";
            } elseif ($json['quesType'] == "parent") {
                $filter_query .= " and q.followUp   = 'Parent' ";
            } elseif ($json['quesType'] == "single") {
                $filter_query .= " and q.followUp   = 'Single' ";
            } elseif ($json['quesType'] == "child1") {
                $filter_query .= " and q.followUp = 'Child 1'";
            } elseif ($json['quesType'] == "child2") {
                $filter_query .= " and q.followUp = 'Child 2'";
            } elseif ($json['quesType'] == "child3") {
                $filter_query .= " and q.followUp = 'Child 3'";
            } elseif ($json['quesType'] == "child4") {
                $filter_query .= " and q.followUp = 'Child 4'";
            } elseif ($json['quesType'] == "child5") {
                $filter_query .= " and q.followUp = 'Child 5'";
            } elseif ($json['quesType'] == "child6") {
                $filter_query .= " and q.followUp = 'Child 6'";
            }
        }
        if ($json['expAdvStatus'] != "") {
            if ($json['expAdvStatus'] == "available") {
                $filter_query .= " and q.expertAdvice is not null";
            } elseif ($json['expAdvStatus'] == "delegated") {
                $filter_query .= " and qst.uploadStatus in (0,1) and qst.delegationType='guidanceVideo'";
            } else {
                $filter_query .= " and qst.questionId is null and q.expertAdvice is null";
            }
        }
        if ($json['quesVidStatus'] != "") {
            if ($json['quesVidStatus'] == "available") {
                $filter_query .= " and q.youtubeId != '314664775'";
            } elseif ($json['quesVidStatus'] == "delegated") {
                $filter_query .= " and qst.uploadStatus in (0,1) and qst.delegationType='questionVideo'";
            } else {
                $filter_query .= " and qst.questionId is null and q.youtubeId = '314664775'";
            }
        }
        if ($json['isQuesUsed'] != "") {
            if ($json['isQuesUsed'] == "yes") {
                $having_query1 .= " and isQuestionUsed = 'Yes' ";
            } else {
                $having_query1 .= " and isQuestionUsed = 'No' ";
            }
        }
        if ($json['vimeoId'] != "") {
            $filter_query .= " and q.youtubeId in (" . $json['vimeoId'] . ")";
        }

        $synchQuery = mysqli_query($databaseConnection, "select synched_at from synch_log where table_name = 'bestPeerResponse' order by id desc limit 0,1");
        $synchResult = mysqli_fetch_assoc($synchQuery);
        /* change by Narayan 6/8/2021 for personalized video feedback status */
        $query = "select q.*,(select count(questionId) as feedbackVideo from expert_review where feedbackVideoURL is not null and rejected='N' and questionId=q.id) AS videoFeedback,(SELECT  COUNT(DISTINCT iqt.interviewId) FROM `interview_questions_transection` iqt WHERE iqt.noOfSkip IS NULL AND iqt.noOfRespond IS NULL AND iqt.interviewId is not null AND iqt.questionId = q.id) AS usedStreamCount,CASE WHEN q.deleted_at is not null THEN 'Trashed'  WHEN (q.deleted_at is null and q.expertAdvice is not null  and (q.peerResponseVideo is not null or q.mbr_id != '0')  and  q.youtubeId !=314664775) THEN 'Ready toUse Plus' WHEN (q.deleted_at is null and q.expertApproval = 'Y' and (q.eligibleStreamId != '' AND q.eligibleStreamId IS NOT NULL AND q.subjectId != '' AND q.subjectId IS NOT NULL AND q.conceptId != '' AND q.conceptId IS NOT NULL AND q.key_skill_id != '' AND q.key_skill_id IS NOT NULL AND q.topic_id != '' AND q.topic_id IS NOT NULL AND q.isWbRequired != '' AND q.isWbRequired IS NOT NULL AND q.questionLevel != '' AND q.questionLevel IS NOT NULL)) THEN 'Ready to use' WHEN ((q.deleted_at is null and q.expertApproval ='N') or (q.eligibleStreamId = '' OR q.eligibleStreamId IS  NULL OR q.subjectId = '' OR q.subjectId IS  NULL OR q.conceptId = '' OR q.conceptId IS  NULL OR q.key_skill_id = '' OR q.key_skill_id IS  NULL OR q.topic_id = '' OR q.topic_id IS  NULL OR q.isWbRequired = '' OR q.isWbRequired IS  NULL OR q.questionLevel = '' OR q.questionLevel IS  NULL)) THEN 'Raw Qns' ELSE 'Nothing' END AS questionStatus,count(DISTINCT fsq.id) as frequency, CASE WHEN q.expertAdvice IS NULL and qst.questionId IS NULL THEN 'Not Available' WHEN q.expertAdvice IS NULL and qst.questionId IS NOT NULL and qst.delegationType='guidanceVideo' and qst.uploadStatus !='2' THEN 'Delegated' WHEN q.expertAdvice IS  NOT NULL THEN 'Available' ELSE 'Not Available' END  as guidanceVideoStatus,CASE WHEN q.youtubeId = '314664775' and qst.questionId IS NULL THEN 'Not Available' WHEN q.youtubeId != '314664775' THEN 'Available' WHEN q.youtubeId = '314664775' and qst.questionId IS NOT NULL and qst.delegationType='questionVideo' and qst.uploadStatus !='2' THEN 'Delegated'  ELSE 'Not Available' END  as questionVideoStatus,t.name as topic_name, fs.favourite_subject as subject_name, c.name as concept_name, CASE WHEN (SELECT COUNT(DISTINCT iqt.questionId) FROM `interview_questions_transection` iqt WHERE iqt.noOfSkip IS NULL AND iqt.noOfRespond IS NULL AND iqt.questionId = q.id) > 0 THEN 'Yes' ELSE 'No' END as isQuestionUsed from questions q left outer join topic t on q.topic_id = t.id left outer join favourite_subject fs on fs.id = q.subjectId left outer join concepts c on c.id = q.conceptId left outer join questions_transection qst on qst.questionId = q.id  left outer join feedback_status_question fsq on q.id = fsq.questionId left outer join feedback_request fr on  fsq.feedbackRequestId= fr.id";
        $data = '';
        $data = $query . $filter_query . $groupby_query . $having_query1 . $order_query;
        //$count_query=mysqli_query($databaseConnection,$data);
        $query = mysqli_query($databaseConnection, $data);
        if (mysqli_num_rows($query) > 0) {
            $count = mysqli_query($databaseConnection, $data);
            $count_result = mysqli_num_rows($count);
            //$main_data = mysqli_fetch_all($query,MYSQLI_ASSOC);
            while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
                $row['questionHtml'] = nl2br($row['questionText']);

                if ($row['questionCreator'] != '0' && $row['questionCreator'] != null) {
                    $creator = mysqli_query($databaseConnection, "Select p.name from  questions q  inner join panel p on q.questionCreator= p.id  where q.id = '" . $row['id'] . "';");
                    $creatorResult = mysqli_fetch_array($creator, MYSQLI_ASSOC);
                    $row['questionCreatorName'] = $creatorResult['name'];
                } elseif ($row['questionCreator'] == '0') {
                    $row['questionCreatorName'] = 'In House';
                } else {
                    $row['questionCreatorName'] = 'None';
                }
                if ($row['questionReviewer'] != '0' && $row['questionReviewer'] != null) {
                    $creator = mysqli_query($databaseConnection, "Select p.name from  questions q  inner join panel p on q.questionReviewer= p.id  where q.id = '" . $row['id'] . "';");
                    $creatorResult = mysqli_fetch_array($creator, MYSQLI_ASSOC);
                    $row['questionReviewerName'] = $creatorResult['name'];
                } elseif ($row['questionReviewer'] == '0') {
                    $row['questionReviewerName'] = 'In House';
                } else {
                    $row['questionReviewerName'] = 'None';
                }

                // if ($row['usedStreamCount'] > 0) {
                //     $usedStaus = mysqli_query($databaseConnection, "Select i.name as InterviewName , p.name as ProductName,(select GROUP_CONCAT(DISTINCT s.stream SEPARATOR ', ') as streams from interview itw , stream s where itw.id = i.id and find_in_set(s.id,itw.stream)) as streamName from interview_questions_transection iqt inner join questions q on q.id = iqt.questionId inner join interview i on i.id = iqt.interviewId inner join product p on p.id = i.productId where q.id = '" . $row['id'] . "';");
                //     $usedStatusResult = mysqli_fetch_all($usedStaus, MYSQLI_ASSOC);
                //     $row['usedStausList'] = $usedStatusResult;
                // } else {
                //     $row['usedStausList'] = [];
                // }

                $keySkillQuery = mysqli_query($databaseConnection, "SELECT q.key_skill_id, group_concat(ks.key_skill SEPARATOR ', ') AS key_skill_name FROM questions q, key_skill ks WHERE FIND_IN_SET(ks.id, q.key_skill_id) and q.id = '" . $row['id'] . "';");
                $keySkillResult = mysqli_fetch_array($keySkillQuery, MYSQLI_ASSOC);
                $row['key_skill_name'] = $keySkillResult['key_skill_name'];

                $eligibleStreamQuery = mysqli_query($databaseConnection, "SELECT q.eligibleStreamId, group_concat(s.stream SEPARATOR ', ') AS eligibleStreamName FROM questions q, stream s WHERE FIND_IN_SET(s.id, q.eligibleStreamId) and q.id = '" . $row['id'] . "';");
                $eligibleStreamResult = mysqli_fetch_array($eligibleStreamQuery, MYSQLI_ASSOC);
                $row['eligibleStreamName'] = $eligibleStreamResult['eligibleStreamName'];

                $questionVideoQuery = mysqli_query($databaseConnection, "SELECT questionId FROM `questions_transection` WHERE uploadStatus in (0,1) and delegationType='questionVideo' and questionId='" . $row['id'] . "';");
                if (mysqli_num_rows($questionVideoQuery) > 0) {
                    $row['questionVideoStatus'] = 'Delegated';
                }
                $guidanceVideoQuery = mysqli_query($databaseConnection, "SELECT questionId FROM `questions_transection` WHERE uploadStatus in (0,1) and delegationType='guidanceVideo' and questionId='" . $row['id'] . "';");
                if (mysqli_num_rows($questionVideoQuery) > 0) {
                    $row['guidanceVideoStatus'] = 'Delegated';
                }
                /*$domainQuery = mysqli_query($databaseConnection, "SELECT q.domainId, group_concat(fd.name SEPARATOR ', ') AS domain_name FROM questions q, favourite_domain fd WHERE FIND_IN_SET(fd.id, q.domainId) and q.id = '".$row['id']."';");
                $domainResult = mysqli_fetch_array($domainQuery, MYSQLI_ASSOC);
                $row['domain_name'] = $domainResult['domain_name'];*/


                $execute = true;
                if ($row['mbr_id'] != 0) {
                    $isPeerAvailable = mysqli_query($databaseConnection, "select u.firstName as candidateName, u.emailId, u.mobileNumber, i.name as interviewName, concat('https://goprac.com/review?i=', i.id, '&c=', m.candidateId, '&s=', m.interviewSessionId) as interviewLink, iqt.sequence as questionNumber, fr.id as feedback_request_id from mergedVideos m inner join users u on u.id = m.candidateId inner join interview i on i.id = m.interviewId inner join interview_questions_transection iqt on iqt.interviewId = m.interviewId and iqt.questionId = m.questionId inner join feedback_request fr on fr.interviewSessionId = m.interviewSessionId where m.mergeId = '" . $row['mbr_id'] . "';");
                    $isPeerResult = mysqli_fetch_array($isPeerAvailable, MYSQLI_ASSOC);
                    $row['candidateName'] = $isPeerResult['candidateName'];
                    $row['emailId'] = $isPeerResult['emailId'];
                    $row['mobileNumber'] = $isPeerResult['mobileNumber'];
                    $row['interviewName'] = $isPeerResult['interviewName'];
                    $row['interviewLink'] = $isPeerResult['interviewLink'];
                    $row['questionNumber'] = $isPeerResult['questionNumber'];
                    $row['feedback_request_id'] = $isPeerResult['feedback_request_id'];

                    $expertRatings = mysqli_query($databaseConnection, "SELECT GROUP_CONCAT(observation_name,' - ',observation_values SEPARATOR ', ') as expertRatings from (SELECT p.observation_name, pv.observation_values FROM expert_review_observation_details as erpd, observation_area as p, observation_values as pv, expert_review er WHERE erpd.expertReviewId = er.id and erpd.observationValueId = pv.id and pv.observation_id = p.id and p.key_skill != 0 and p.id in (2,3,9,33,34) and er.feedback_request_id = '" . $isPeerResult['feedback_request_id'] . "' and er.questionId = '" . $row['id'] . "') as temp");
                    $expertRatingsResult = mysqli_fetch_array($expertRatings, MYSQLI_ASSOC);
                    $row['expertRatings'] = $expertRatingsResult['expertRatings'];
                } else {
                    if ($row['peerResponseStatus'] != 'A' && $row['peerResponseStatus'] != 'NA') {
                        $isPeerAvailableQuery = "select u.firstName as candidateName, u.emailId, u.mobileNumber, i.name as interviewName, concat('https://goprac.com/review?i=', i.id, '&c=', m.candidateId, '&s=', m.interviewSessionId) as interviewLink, iqt.sequence as questionNumber, fr.id as feedback_request_id from mergedVideos m inner join users u on u.id = m.candidateId inner join interview i on i.id = m.interviewId inner join interview_questions_transection iqt on iqt.interviewId = m.interviewId and iqt.questionId = m.questionId inner join feedback_request fr on fr.interviewSessionId = m.interviewSessionId where m.mergeId IN (" . $row['peerResponseStatus'] . ");";
                        $isPeerAvailable = mysqli_query($databaseConnection, $isPeerAvailableQuery);
                        $isPeerResult = mysqli_fetch_all($isPeerAvailable, MYSQLI_ASSOC);
                        for ($i = 0; $i < sizeof($isPeerResult); $i++) {
                            $row['candidateName'] = $isPeerResult[$i]['candidateName'];
                            $row['emailId'] = $isPeerResult[$i]['emailId'];
                            $row['mobileNumber'] = $isPeerResult[$i]['mobileNumber'];
                            $row['interviewName'] = $isPeerResult[$i]['interviewName'];
                            $row['interviewLink'] = $isPeerResult[$i]['interviewLink'];
                            $row['questionNumber'] = $isPeerResult[$i]['questionNumber'];
                            $row['feedback_request_id'] = $isPeerResult[$i]['feedback_request_id'];

                            $expertRatings = mysqli_query($databaseConnection, "SELECT GROUP_CONCAT(observation_name,' - ',observation_values SEPARATOR ', ') as expertRatings from (SELECT p.observation_name, pv.observation_values FROM expert_review_observation_details as erpd, observation_area as p, observation_values as pv, expert_review er WHERE erpd.expertReviewId = er.id and erpd.observationValueId = pv.id and pv.observation_id = p.id and p.key_skill != 0 and p.id in (2,3,9,33,34) and er.feedback_request_id = '" . $isPeerResult[$i]['feedback_request_id'] . "' and er.questionId = '" . $row['id'] . "') as temp");
                            $expertRatingsResult = mysqli_fetch_array($expertRatings, MYSQLI_ASSOC);
                            $row['expertRatings'] = $expertRatingsResult['expertRatings'];

                            array_push($main_data, $row);
                            $execute = false;
                        }
                    } else {
                        $row['candidateName'] = NULL;
                        $row['emailId'] = NULL;
                        $row['mobileNumber'] = NULL;
                        $row['interviewName'] = NULL;
                        $row['interviewLink'] = NULL;
                        $row['questionNumber'] = NULL;
                        $row['feedback_request_id'] = NULL;
                        $row['expertRatings'] = NULL;
                    }
                }
                if ($row['peerResponseStatus'] == 'A') {
                    $getAvailableCount = mysqli_query($databaseConnection, "select count(temp.id) as peerAvailableCount from  (select er.id from mergedVideos m inner join feedback_request fr on fr.interviewSessionId = m.interviewSessionId inner join expert_review er on er.feedback_request_id = fr.id where m.interviewSessionId is not null and m.rejected='N' and  er.questionId = '" . $row['id'] . "' and fr.review_status='2' and er.overallRating > 4 and er.overallRating !='videoIssue' group by fr.interviewSessionId) as temp");
                    $PeerAvailableCountResult = mysqli_fetch_array($getAvailableCount, MYSQLI_ASSOC);
                    $row['peerAvailableCount'] = $PeerAvailableCountResult['peerAvailableCount'];
                }
                /* this for total peer response video selected count */
                if ($row['peerResponseStatus'] != 'A' && $row['peerResponseStatus'] != 'NA' && $row['mbr_id'] == 0) {
                    $row['selectedPeerCount'] = count(explode(',', $row['peerResponseStatus']));
                }
                if ($execute) {
                    array_push($main_data, $row);
                }
            }

            $to_encode = array(
                'result' => "success",
                'status' => 1,
                'data' => $main_data,
                'count' => $count_result,
                'synched_at' => timeAgo($synchResult['synched_at'])
            );
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'synched_at' => timeAgo($synchResult['synched_at']),
                'errorCode' => "in Error while retrieving question information.",
                'qry' => $data . " limit " . $start . "," . $limit
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while retrieving question information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['questionInfo'])) {
    /* it is called when we edit interview in manage interview */
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $questionId = $json['questionId'];
        $sql = "select q.*, t.name as topic_name, fs.favourite_subject as subject_name, c.name as concept_name from questions q left outer join topic t on q.topic_id = t.id left outer join favourite_subject fs on fs.id = q.subjectId left outer join concepts c on c.id = q.conceptId where q.id='" . $questionId . "'";
        $query = mysqli_query($databaseConnection, $sql);

        if (mysqli_num_rows($query) >= 1) {
            $values = array();
            //$row = mysqli_fetch_array($query, MYSQLI_ASSOC);
            while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {

                $keySkillQuery = mysqli_query($databaseConnection, "SELECT q.key_skill_id, group_concat(ks.key_skill SEPARATOR ', ') AS key_skill_name FROM questions q, key_skill ks WHERE FIND_IN_SET(ks.id, q.key_skill_id) and q.id = '" . $row['id'] . "';");
                $keySkillResult = mysqli_fetch_array($keySkillQuery, MYSQLI_ASSOC);
                $row['key_skill_name'] = $keySkillResult['key_skill_name'];

                $values[] = $row;
            }
            $to_encode = $values;
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "out Error while retrieving Interview information"
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving Interview information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['deleteQuestion'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $questionId = $json['questionId'];

        $sql = "update questions set isFollowUp='N', deleted_at = CASE when deleted_at is null THEN CURRENT_DATE else null end where id=" . $questionId;
        if (mysqli_query($databaseConnection, $sql)) {
            $updateInterviewStatus = mysqli_query($databaseConnection, "update interview set isActive='N' where id IN (select interviewId from interview_questions_transection where questionId='" . $questionId . "');");
            $to_encode = array(
                'status' => 1,
                'result' => "success"
            );
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "out Error while retrieving Interview information"
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving Interview information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['deleteQuestionFromInterview'])) {
    /* added for delete question from interview 11-06-2021  by Naraayn*/
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $questionId = $json['questionId'];
        $interviewId = $json['interviewId'];

        $sql = "update `interview_questions_transection` set deleted_at = CASE when deleted_at is null THEN CURRENT_DATE else null end where questionId='" . $questionId . "' and interviewId='" . $interviewId . "';";
        if (mysqli_query($databaseConnection, $sql)) {
            $updateInterviewStatus = mysqli_query($databaseConnection, "update interview set isActive='N' where id='" . $interviewId . "'");
            $to_encode = array(
                'status' => 1,
                'result' => "success"
            );
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "out Error while retrieving Interview information"
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving Interview information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['updateQuestion'])) {
    /*$data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {*/
    $questionId = $_POST['question_id'];
    $topic_id = $_POST['topic_id'];
    $youtubeId = $_POST['youtubeId'] == '' ? '314664775' : $_POST['youtubeId'];
    $concept_id = $_POST['concept_id'];
    $subject_id = $_POST['subject_id'];
    //$domainId = explode(',', $_POST['domainId']);
    $filename = $_POST['question_id'];

    if ($_POST['removeImg'] == 'true') {
        $basename = NULL;
        $upadeQuesDiagram = mysqli_query($databaseConnection, "update questions set quesDiagram=NULL where id='" . $questionId . "'");
    }
    if ($_FILES['quesDiagram']['name'] != "") {
        $extension = pathinfo($_FILES["quesDiagram"]["name"], PATHINFO_EXTENSION); //png
        $basename = $filename . '.' . $extension;
        $upadeQuesDiagram = mysqli_query($databaseConnection, "update questions set quesDiagram='" . $basename . "' where id='" . $questionId . "'");
    }

    if ($_POST['otherTopic'] != "") {
        $topicQuery = mysqli_query($databaseConnection, "insert into topic(name) values ('" . addslashes($_POST['otherTopic']) . "');");
        $topic_id = mysqli_insert_id($databaseConnection);
    }

    if ($_POST['otherConcept'] != "") {
        $topicQuery = mysqli_query($databaseConnection, "insert into concepts(name) values ('" . addslashes($_POST['otherConcept']) . "');");
        $concept_id = mysqli_insert_id($databaseConnection);
    }

    if ($_POST['otherSubject'] != "") {
        $topicQuery = mysqli_query($databaseConnection, "insert into favourite_subject(favourite_subject, isActiveForMentorship) values ('" . addslashes($_POST['otherSubject']) . "', 'N');");
        $subject_id = mysqli_insert_id($databaseConnection);
    }

    // $sql = "UPDATE questions SET 
    //         youtubeId = '$youtubeId',
    //         thinkingTime = '" . $_POST['thinkingTime'] . "',
    //         priorityStatus = '" . $_POST['highPriority'] . "',
    //         expertApproval = '" . $_POST['expertApproval'] . "',
    //         answerDuration = '" . $_POST['answerDuration'] . "',
    //         questionType = '" . $_POST['questionType'] . "',
    //         questionText = '" . addslashes($_POST['questionText']) . "',
    //         topic_id = '$topic_id',
    //         key_skill_id = '" . $_POST['keySkillId'] . "',
    //         questionLevel = '" . $_POST['questionLevel'] . "',
    //         shortExpectedAns = '" . addslashes($_POST['shortExpectedAns']) . "',
    //         isActive = 'Y',
    //         isWbRequired = '" . $_POST['isWbRequired'] . "',
    //         instruction = NULLIF('" . addslashes($_POST['instruction']) . "', ''),
    //         eligibleStreamId = '" . $_POST['target_audience'] . "',
    //         subjectId = '$subject_id',
    //         conceptId = '$concept_id',
    //         tutorialLink = NULLIF('" . addslashes($_POST['tutorialLink']) . "', ''),
    //         remarks = NULLIF('" . addslashes($_POST['remarks']) . "', ''),
    //         clusterLevel = '" . $_POST['questionLevel'] . "',
    //         idk1 = NULLIF('" . $_POST['idk1'] . "', ''),
    //         idk2 = NULLIF('" . $_POST['idk2'] . "', ''),
    //         idk1Ans = NULLIF('" . addslashes($_POST['idk1Ans']) . "', ''),
    //         idk2Ans = NULLIF('" . addslashes($_POST['idk2Ans']) . "', ''),
    //         editAt = NOW()
    //     WHERE id = $questionId";


    // Step 1: Fetch existing values
    $existingQuery = mysqli_query($databaseConnection, "SELECT questionText, shortExpectedAns FROM questions WHERE id = $questionId");
    $existingData = mysqli_fetch_assoc($existingQuery);

    // Step 2: Sanitize new inputs
    $questionText = $_POST['questionText'];
    $shortExpectedAns = $_POST['shortExpectedAns'];


    $newIdk1 = $_POST['idk1'];
    $newIdk2 = $_POST['idk2'];
    $newIdk1Ans = $_POST['idk1Ans'];
    $newIdk2Ans = $_POST['idk2Ans'];


    $setAlternateStatus = false;

    $allEmpty = (
        trim($newIdk1) === '' &&
        trim($newIdk2) === '' &&
        trim($newIdk1Ans) === '' &&
        trim($newIdk2Ans) === ''
    );

    // Compare old and new values
    $anyChanged = (
        $existingData['questionText'] !== $questionText ||
        $existingData['shortExpectedAns'] !== $shortExpectedAns
    );

    if ($anyChanged || $allEmpty) {
        $setAlternateStatus = true;
    }

    // Step 4: Build UPDATE query
    $sql = "UPDATE questions SET 
        youtubeId = '$youtubeId',
        thinkingTime = '" . $_POST['thinkingTime'] . "',
        priorityStatus = '" . $_POST['highPriority'] . "',
        expertApproval = '" . $_POST['expertApproval'] . "',
        answerDuration = '" . $_POST['answerDuration'] . "',
        questionType = '" . $_POST['questionType'] . "',
        questionText = '" . addslashes($_POST['questionText']) . "',
        topic_id = '$topic_id',
        key_skill_id = '" . $_POST['keySkillId'] . "',
        questionLevel = '" . $_POST['questionLevel'] . "',
        shortExpectedAns = '" . addslashes($_POST['shortExpectedAns']) . "',
        isActive = 'Y',
        isWbRequired = '" . $_POST['isWbRequired'] . "',
        instruction = NULLIF('" . addslashes($_POST['instruction']) . "', ''),
        eligibleStreamId = '" . $_POST['target_audience'] . "',
        subjectId = '$subject_id',
        conceptId = '$concept_id',
        tutorialLink = NULLIF('" . addslashes($_POST['tutorialLink']) . "', ''),
        remarks = NULLIF('" . addslashes($_POST['remarks']) . "', ''),
        clusterLevel = '" . $_POST['questionLevel'] . "',
        idk1 = NULLIF('$newIdk1', ''),
        idk2 = NULLIF('$newIdk2', ''),
        idk1Ans = NULLIF('" . addslashes($newIdk1Ans) . "', ''),
        idk2Ans = NULLIF('" . addslashes($newIdk2Ans) . "', ''),";

    // Step 5: Conditionally include alternateQuestionStatus
    if ($setAlternateStatus) {
        $sql .= " alternateQuestionStatus = '0',";
    }

    $sql .= " editAt = NOW() WHERE id = $questionId";

    if (mysqli_query($databaseConnection, $sql)) {
        /* change in condition value of priorityStatus which is previously know as highPriority will be now 0,1,2 */
        if ($_POST['isFollowUp'] != 'N' && ($_POST['highPriority'] == '1' || $_POST['highPriority'] == '2')) {
            if ($_POST['isFollowUp'] == 'Y') {
                $query = "SELECT id,isFollowUp FROM questions  WHERE id = '" . $questionId . "' UNION SELECT id, isFollowUp FROM questions WHERE id in (SELECT lv FROM (SELECT @pv:=(SELECT GROUP_CONCAT(id SEPARATOR ',') FROM questions WHERE isFollowUp IN (@pv)) AS lv FROM questions JOIN (SELECT @pv:='" . $questionId . "')tmp WHERE isFollowUp IN (@pv)) a) ORDER BY isFollowUp <> 'Y', isFollowUp;";
            } else {
                $query = "SELECT T2.id, T2.isFollowUp FROM ( SELECT @r AS _id, (SELECT @r := isFollowUp FROM questions WHERE id = _id) AS isFollowUp, @l := @l + 1 AS lvl FROM (SELECT @r := '" . $questionId . "', @l := 'Y') vars, questions h WHERE @r <> 'Y') T1 JOIN questions T2 ON T1._id = T2.id UNION SELECT id,isFollowUp FROM questions WHERE id in (SELECT lv FROM (SELECT @pv:=(SELECT GROUP_CONCAT(id SEPARATOR ',') FROM questions WHERE isFollowUp IN (@pv)) AS lv FROM questions JOIN (SELECT @pv:='" . $questionId . "')tmp WHERE isFollowUp IN (@pv)) a) ORDER BY isFollowUp <> 'Y', isFollowUp;";
            }
            $result = mysqli_query($databaseConnection, $query);
            if (mysqli_num_rows($result) >= 1) {
                while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {

                    $updateHighPriority = mysqli_query($databaseConnection, "Update questions set priorityStatus='" . $_POST['highPriority'] . "' where id='" . $row['id'] . "';");
                }
            }
        }


        if ($_FILES['quesDiagram']['name'] != "") {
            $file_tmp = $_FILES['quesDiagram']['tmp_name'];
            if (file_exists("../pracschool_app/public/interviewDiagram/" . $basename)) {
                unlink("../pracschool_app/public/interviewDiagram/" . $basename);
                move_uploaded_file($file_tmp, "../pracschool_app/public/interviewDiagram/" . $basename);
            } else {
                move_uploaded_file($file_tmp, "../pracschool_app/public/interviewDiagram/" . $basename);
            }
        }
        $to_encode = array(
            'status' => 1,
            'result' => "success"
        );
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while updating Interview information" . $sql
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getFollowupEngineFilters'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['candidateId'];
        $values = array();
        $data7 = "select * from favourite_subject order by id=29,favourite_subject";
        $query7 = mysqli_query($databaseConnection, $data7);
        $values7 = mysqli_fetch_all($query7, MYSQLI_ASSOC);
        $values['favourite_subject'] = $values7;
        // sibin oct 27 for interview name filter
        $data8 = "select pr.id,case when pr.interviewName is not null then pr.interviewName else ac.name end as name from preInterview pr inner join aspiration_company ac on ac.id=pr.company_Id group by pr.id desc";
        $query8 = mysqli_query($databaseConnection, $data8);
        $values8 = mysqli_fetch_all($query8, MYSQLI_ASSOC);
        $values['interview_name'] = $values8;

        $to_encode = $values;
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while getting Interview information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getFollowupEngineInterviewnameSubject'])) {
    // sibin 28 oct 2022 method used in expert-calculation and follow-up engine both pages.
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $companyId = $json['companyId'];
        $values = array();
        $data7 = "select distinct fs.id,fs.favourite_subject from favourite_subject fs inner join scps_transaction scps on scps.subject=fs.id where scps.preInterviewId IN (" . implode(",", $companyId) . ") order by fs.favourite_subject ASC";

        $query7 = mysqli_query($databaseConnection, $data7);
        $values7 = mysqli_fetch_all($query7, MYSQLI_ASSOC);
        $values['favourite_subject'] = $values7;

        $to_encode = $values;
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while getting Interview information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getAssessmentWorkFilters'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['candidateId'];
        $values = array();
        $data7 = "select * from favourite_subject order by id=29,favourite_subject";
        $query7 = mysqli_query($databaseConnection, $data7);
        $values7 = mysqli_fetch_all($query7, MYSQLI_ASSOC);
        $values['favourite_subject'] = $values7;
        $values['favourite_subject'] = $values7;
        $to_encode = $values;
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while getting Interview information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getContentWorkFilters'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['candidateId'];
        $values = array();
        $data7 = "select * from favourite_subject order by id=29,favourite_subject";
        $query7 = mysqli_query($databaseConnection, $data7);
        $values7 = mysqli_fetch_all($query7, MYSQLI_ASSOC);
        $values['favourite_subject'] = $values7;
        $values['favourite_subject'] = $values7;
        $to_encode = $values;
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while getting Interview information"
        );
    }
    echo json_encode($to_encode);
}
// node-api
elseif (isset($_GET['getQuestionDashboardAllFilters'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['candidateId'];
        $values = array();

        $data1 = "select * from topic order by id=1,name";
        $query1 = mysqli_query($databaseConnection, $data1);
        $values1 = mysqli_fetch_all($query1, MYSQLI_ASSOC);

        $data2 = "select id,name from concepts order by id=1,name";
        $query2 = mysqli_query($databaseConnection, $data2);
        $values2 = mysqli_fetch_all($query2, MYSQLI_ASSOC);

        $data3 = "select * from key_skill where id not in (4,5) order by key_skill";
        $query3 = mysqli_query($databaseConnection, $data3);
        $values3 = mysqli_fetch_all($query3, MYSQLI_ASSOC);

        $data4 = "SELECT questionLevel FROM `questions` where questionLevel is not null and questionLevel !='' group by questionLevel";
        $query4 = mysqli_query($databaseConnection, $data4);
        $values4 = mysqli_fetch_all($query4, MYSQLI_ASSOC);

        // $data6 = "SELECT * FROM `menu` order by name";
        // $query6 = mysqli_query($databaseConnection, $data6);
        // $values6 = mysqli_fetch_all($query6, MYSQLI_ASSOC);


        $data7 = "select * from favourite_subject order by id=29,favourite_subject";
        $query7 = mysqli_query($databaseConnection, $data7);
        $values7 = mysqli_fetch_all($query7, MYSQLI_ASSOC);

        $data8 = "select * from stream order by id=11,stream";
        $query8 = mysqli_query($databaseConnection, $data8);
        $values8 = mysqli_fetch_all($query8, MYSQLI_ASSOC);

        $data9 = "select * from favourite_domain order by id=39,name";
        $query9 = mysqli_query($databaseConnection, $data9);
        $values9 = mysqli_fetch_all($query9, MYSQLI_ASSOC);

        $data10 = "select * from aspiration_company order by id=40,name";
        $query10 = mysqli_query($databaseConnection, $data10);
        $values10 = mysqli_fetch_all($query10, MYSQLI_ASSOC);

        $data11 = "select id,name from product order by id";
        $query11 = mysqli_query($databaseConnection, $data11);
        $values11 = mysqli_fetch_all($query11, MYSQLI_ASSOC);

        // $data12 = "select id,name from category where isValid = 'Y' order by id";
        // $query12 = mysqli_query($databaseConnection, $data12);
        // $values12 = mysqli_fetch_all($query12, MYSQLI_ASSOC);

        // $data13 = "select id,name from interview where isActive = 'Y' and deleted_at is null order by name";
        // $query13 = mysqli_query($databaseConnection, $data13);
        // $values13 = mysqli_fetch_all($query13, MYSQLI_ASSOC);


        $data14 = "select * from category";
        $query14 = mysqli_query($databaseConnection, $data14);
        $values14 = mysqli_fetch_all($query14, MYSQLI_ASSOC);

        $data15 = "select name,id from panel where deleted_at is null and expertStatus=1 order by name ";
        $query15 = mysqli_query($databaseConnection, $data15);
        $values15 = mysqli_fetch_all($query15, MYSQLI_ASSOC);

        $data16 = "SELECT * FROM `sector`";
        $query16 = mysqli_query($databaseConnection, $data16);
        $values16 = mysqli_fetch_all($query16, MYSQLI_ASSOC);

        $data17 = "SELECT * FROM `aspiration_company` ORDER BY `name` ASC";
        $query17 = mysqli_query($databaseConnection, $data17);
        $values17 = mysqli_fetch_all($query17, MYSQLI_ASSOC);

        $data18 = "select * from favourite_subject where active='Y' order by id ";
        $query18 = mysqli_query($databaseConnection, $data18);
        $values18 = mysqli_fetch_all($query18, MYSQLI_ASSOC);

        $values['topic'] = $values1;
        $values['concepts'] = $values2;
        $values['key_skill'] = $values3;
        $values['questionLevel'] = $values4;
        $values['interviewLevel'] = $values4;
        // $values['menu'] = $values6;
        $values['favourite_subject'] = $values7;
        $values['stream'] = $values8;
        //$values['favourite_domain'] = $values9;
        $values['aspiration_company'] = $values10;
        $values['product_list'] = $values11;
        //$values['category_list'] = $values12;
        //$values['interview_list'] = $values13;
        $values['category'] = $values14;
        $values['referrerName'] = $values15;
        $values['sectors'] = $values16;
        $values['companyList'] = $values17;
        $values['activeSubject'] = $values18;

        $to_encode = $values;
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while getting Interview information"
        );
    }
    echo json_encode($to_encode);
}
elseif (isset($_GET['getQuestionDashboardFilters'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['candidateId'];
        $values = array();

        $data1 = "select * from topic order by id=1,name";
        $query1 = mysqli_query($databaseConnection, $data1);
        $values1 = mysqli_fetch_all($query1, MYSQLI_ASSOC);

        $data2 = "select id,name from concepts order by id=1,name";
        $query2 = mysqli_query($databaseConnection, $data2);
        $values2 = mysqli_fetch_all($query2, MYSQLI_ASSOC);

        $data3 = "select * from key_skill where id not in (4,5) order by key_skill";
        $query3 = mysqli_query($databaseConnection, $data3);
        $values3 = mysqli_fetch_all($query3, MYSQLI_ASSOC);

        $data4 = "SELECT questionLevel FROM `questions` where questionLevel is not null and questionLevel !='' group by questionLevel";
        $query4 = mysqli_query($databaseConnection, $data4);
        $values4 = mysqli_fetch_all($query4, MYSQLI_ASSOC);

        $data6 = "SELECT * FROM `menu` order by name";
        $query6 = mysqli_query($databaseConnection, $data6);
        $values6 = mysqli_fetch_all($query6, MYSQLI_ASSOC);

        $data7 = "select * from favourite_subject order by id=29,favourite_subject";
        $query7 = mysqli_query($databaseConnection, $data7);
        $values7 = mysqli_fetch_all($query7, MYSQLI_ASSOC);

        $data8 = "select * from stream order by id=11,stream";
        $query8 = mysqli_query($databaseConnection, $data8);
        $values8 = mysqli_fetch_all($query8, MYSQLI_ASSOC);

        $data9 = "select * from favourite_domain order by id=39,name";
        $query9 = mysqli_query($databaseConnection, $data9);
        $values9 = mysqli_fetch_all($query9, MYSQLI_ASSOC);

        $data10 = "select * from aspiration_company order by id=40,name";
        $query10 = mysqli_query($databaseConnection, $data10);
        $values10 = mysqli_fetch_all($query10, MYSQLI_ASSOC);

        $data11 = "select id,name from product order by id";
        $query11 = mysqli_query($databaseConnection, $data11);
        $values11 = mysqli_fetch_all($query11, MYSQLI_ASSOC);

        $data12 = "select id,name from category where isValid = 'Y' order by id";
        $query12 = mysqli_query($databaseConnection, $data12);
        $values12 = mysqli_fetch_all($query12, MYSQLI_ASSOC);

        $data13 = "select id,name from interview where isActive = 'Y' and deleted_at is null  and categoryType != '9' order by name";
        $query13 = mysqli_query($databaseConnection, $data13);
        $values13 = mysqli_fetch_all($query13, MYSQLI_ASSOC);

        $values['topic'] = $values1;
        $values['concepts'] = $values2;
        $values['key_skill'] = $values3;
        $values['questionLevel'] = $values4;
        $values['interviewLevel'] = $values4;
        $values['menu'] = $values6;
        $values['favourite_subject'] = $values7;
        $values['stream'] = $values8;
        $values['favourite_domain'] = $values9;
        $values['aspiration_company'] = $values10;
        $values['product_list'] = $values11;
        $values['category_list'] = $values12;
        $values['interview_list'] = $values13;

        $to_encode = $values;
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while getting Interview information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getExpertAdviceFilters'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['candidateId'];
        $values = array();

        $data1 = "select * from topic order by id=1,name";
        $query1 = mysqli_query($databaseConnection, $data1);
        $values1 = mysqli_fetch_all($query1, MYSQLI_ASSOC);

        $data2 = "select id,name from concepts order by id=1,name";
        $query2 = mysqli_query($databaseConnection, $data2);
        $values2 = mysqli_fetch_all($query2, MYSQLI_ASSOC);

        $data3 = "select * from key_skill where id not in (4,5) order by key_skill";
        $query3 = mysqli_query($databaseConnection, $data3);
        $values3 = mysqli_fetch_all($query3, MYSQLI_ASSOC);

        $data4 = "SELECT questionLevel FROM `questions` where questionLevel is not null and questionLevel !='' group by questionLevel";
        $query4 = mysqli_query($databaseConnection, $data4);
        $values4 = mysqli_fetch_all($query4, MYSQLI_ASSOC);

        $data7 = "select * from favourite_subject order by id=29,favourite_subject";
        $query7 = mysqli_query($databaseConnection, $data7);
        $values7 = mysqli_fetch_all($query7, MYSQLI_ASSOC);

        $data8 = "select * from stream order by id=11,stream";
        $query8 = mysqli_query($databaseConnection, $data8);
        $values8 = mysqli_fetch_all($query8, MYSQLI_ASSOC);


        $values['topic'] = $values1;
        $values['concepts'] = $values2;
        $values['key_skill'] = $values3;
        $values['questionLevel'] = $values4;
        $values['favourite_subject'] = $values7;
        $values['stream'] = $values8;

        $to_encode = $values;
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while getting Interview information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getInterviewProfileFilters'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['candidateId'];
        $values = array();


        $data7 = "select * from favourite_subject order by id=29,favourite_subject";
        $query7 = mysqli_query($databaseConnection, $data7);
        $values7 = mysqli_fetch_all($query7, MYSQLI_ASSOC);

        $data8 = "select * from stream order by id=11,stream";
        $query8 = mysqli_query($databaseConnection, $data8);
        $values8 = mysqli_fetch_all($query8, MYSQLI_ASSOC);

        $data11 = "select id,name from product order by id";
        $query11 = mysqli_query($databaseConnection, $data11);
        $values11 = mysqli_fetch_all($query11, MYSQLI_ASSOC);

        $data12 = "select id,name from category where isValid = 'Y' order by id";
        $query12 = mysqli_query($databaseConnection, $data12);
        $values12 = mysqli_fetch_all($query12, MYSQLI_ASSOC);

        $data13 = "select id,name from interview where isActive = 'Y' and deleted_at is null order by name";
        $query13 = mysqli_query($databaseConnection, $data13);
        $values13 = mysqli_fetch_all($query13, MYSQLI_ASSOC);

        $values['favourite_subject'] = $values7;
        $values['stream'] = $values8;
        $values['product_list'] = $values11;
        $values['category_list'] = $values12;
        $values['interview_list'] = $values13;

        $to_encode = $values;
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while getting Interview information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getQuestionReportFilters'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['candidateId'];
        $values = array();


        $data1 = "select * from topic order by id=1,name";
        $query1 = mysqli_query($databaseConnection, $data1);
        $values1 = mysqli_fetch_all($query1, MYSQLI_ASSOC);

        $data2 = "select id,name from concepts order by id=1,name";
        $query2 = mysqli_query($databaseConnection, $data2);
        $values2 = mysqli_fetch_all($query2, MYSQLI_ASSOC);

        $data7 = "select * from favourite_subject order by id=29,favourite_subject";
        $query7 = mysqli_query($databaseConnection, $data7);
        $values7 = mysqli_fetch_all($query7, MYSQLI_ASSOC);

        $data8 = "select * from stream order by id=11,stream";
        $query8 = mysqli_query($databaseConnection, $data8);
        $values8 = mysqli_fetch_all($query8, MYSQLI_ASSOC);

        $data10 = "select * from aspiration_company order by id=40,name";
        $query10 = mysqli_query($databaseConnection, $data10);
        $values10 = mysqli_fetch_all($query10, MYSQLI_ASSOC);


        $values['topic'] = $values1;
        $values['concepts'] = $values2;
        $values['favourite_subject'] = $values7;
        $values['stream'] = $values8;
        $values['aspiration_company'] = $values10;

        $to_encode = $values;
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while getting Interview information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getEligibleInterviews'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $panelId = $json['panelId'];
        $result = array();

        $sql = "select i.id,i.name,i.targetAudience,i.role,i.industry,i.assessmentParameters from `interview` i where i.deleted_at is null and i.isActive='Y' and i.panelId != '" . $panelId . "' and i.categoryType in (1,2,6,7,8) order by name";
        $query = mysqli_query($databaseConnection, $sql);
        if (mysqli_num_rows($query) >= 1) {
            while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
                $row['url'] = "/interviewDetails?id=" . $row['id'];
                $row['select'] = false;

                $panel_query = mysqli_query($databaseConnection, "select id,name,emailId,phonenumber, eligibleInterviewForReview from `panel` where id='" . $panelId . "' and deleted_at is null");
                $panel = mysqli_fetch_assoc($panel_query);
                $interviewId = explode(",", $panel['eligibleInterviewForReview']);
                for ($i = 0; $i < count($interviewId); $i++) {
                    if ($interviewId[$i] == $row['id']) {
                        $row['select'] = true;
                    }
                }
                array_push($result, $row);
            }
            $to_encode = array(
                'status' => 1,
                'result' => "success",
                'eligibleInterview' => $panel['eligibleInterviewForReview'],
                'list' => $result
            );
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "in Error while getting Interview information"
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while getting Interview information"
        );
    }
    echo json_encode($to_encode);
}
// node-api
elseif (isset($_GET['getExpertList'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $panelId = $json['panelId'];
        $values = array();

        // $sql="select * from `panel` where deleted_at is null and linkedinProfile != '' and specilization != '' and panelDescription != '' and companiesWorked != '' order by name";
        $sql = "select * from `panel` where deleted_at is null and publishStatus=1 order by experience";
        $query = mysqli_query($databaseConnection, $sql);
        if (mysqli_num_rows($query) >= 1) {

            while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
                $areaOfQuery = mysqli_query($databaseConnection, "SELECT group_concat(fs.favourite_subject SEPARATOR ', ') AS areaOfExpertise_name FROM panel pd, favourite_subject fs WHERE FIND_IN_SET(fs.id, pd.areaOfExpertiseId) and pd.id = '" . $row['id'] . "'");
                $areaOfResult = mysqli_fetch_array($areaOfQuery, MYSQLI_ASSOC);
                $row['areaOfExpertise_name'] = $areaOfResult['areaOfExpertise_name'];
                array_push($values, $row);
            }
            $sqlTotal = "select * from `panel` where deleted_at is null order by name";
            $queryTotal = mysqli_query($databaseConnection, $sqlTotal);
            $to_encode = array(
                'status' => 1,
                'result' => "success",
                'list' => $values,
                'totalExpert' => mysqli_num_rows($queryTotal)
            );
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "in Error while getting Interview information",
                'totalExpert' => 0
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while getting Interview information"
        );
    }
    echo json_encode($to_encode);
}
elseif (isset($_GET['candidateDataLogged'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['candidateId'];
        $message = $json['message'];

        $query = mysqli_query($databaseConnection, "INSERT INTO `candidate_log`(`userId`, `comments`, `logTime`) VALUES ('" . $candidateId . "', '" . $message . "', NOW())");
        if ($query) {
            $to_encode = array(
                'status' => 1,
                'result' => "success"
            );
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "in Error while saving information",
                'qry' => $query
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while saving information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getSubjectData'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $menuName = $json['menuName'];
        $subjectName = $json['subjectName'];
        $subjectData = array();

        $stream_subject_query = mysqli_query($databaseConnection, "select m.* from menu m where m.name = '" . $menuName . "' order by name");
        if (mysqli_num_rows($stream_subject_query) >= 1) {
            while ($row = mysqli_fetch_array($stream_subject_query, MYSQLI_ASSOC)) {
                /*if($row['id'] == 10) {
                    $subject_query = mysqli_query($databaseConnection, "select fs.* from favourite_subject fs inner join menu_subject_transection mst on fs.id = mst.subject_id inner join menu m on mst.menu_id = m.id where m.id = '".$row['id']."' GROUP BY fs.id order by favourite_subject");
                } else {*/
                $subject_query = mysqli_query($databaseConnection, "select fs.* from favourite_subject fs inner join menu_subject_transection mst on fs.id = mst.subject_id inner join menu m on mst.menu_id = m.id INNER JOIN interview i ON fs.id = i.subject_id where m.id = '" . $row['id'] . "' GROUP BY fs.id order by favourite_subject");
                /* }*/
                if (mysqli_num_rows($subject_query) > 0) {
                    $result = mysqli_fetch_all($subject_query, MYSQLI_ASSOC);
                    $row['subjectData'] = $result;
                } else {
                    $row['subjectData'] = [];
                }
                array_push($subjectData, $row);
            }
            $to_encode = array(
                'status' => 1,
                'result' => "success",
                'list' => $subjectData
            );
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "in Error while getting Interview information"
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while getting Interview information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getSectorData'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $menuName = $json['menuName'];
        $subjectName = $json['sectorName'];
        $subjectData = array();



        if ($menuName == 'Events') {
            $stream_subject_query = mysqli_query($databaseConnection, "select m.id , 'Events' as name,m.sequence from menu m where m.name = 'Employability Test' order by name");

        } else {
            $stream_subject_query = mysqli_query($databaseConnection, "select m.* from menu m where m.name in( '" . $menuName . "','Assessment Interviews','Competition Interviews') order by name");

        }

        // $result = mysqli_fetch_all($stream_subject_query, MYSQLI_ASSOC);



        // $stream_subject_query = mysqli_query($databaseConnection, "SELECT st.sector as `sId`,s.name FROM `scps_transaction` st INNER JOIN sector s ON s.id = st.sector GROUP BY s.id");
        if (mysqli_num_rows($stream_subject_query) >= 1) {

            $data = mysqli_fetch_all($stream_subject_query, MYSQLI_ASSOC);

            array_push($subjectData, $data);

            // while ($row = mysqli_fetch_array($stream_subject_query, MYSQLI_ASSOC)) {
            /*if($row['id'] == 10) {
                $subject_query = mysqli_query($databaseConnection, "select fs.* from favourite_subject fs inner join menu_subject_transection mst on fs.id = mst.subject_id inner join menu m on mst.menu_id = m.id where m.id = '".$row['id']."' GROUP BY fs.id order by favourite_subject");
            } else {*/
            // $subject_query = mysqli_query($databaseConnection, "select fs.* from favourite_subject fs inner join menu_subject_transection mst on fs.id = mst.subject_id inner join menu m on mst.menu_id = m.id INNER JOIN interview i ON fs.id = i.subject_id where m.id = '" . $row['id'] . "' GROUP BY fs.id order by favourite_subject");

            if ($menuName == 'Events') {
                $subject_query = mysqli_query($databaseConnection, "SELECT st.sector as `sId`,CASE WHEN s.name = 'IT Services' THEN 'SRM AP: Employability Test' ELSE 'NIT Hamirpur: Employability Test' END as favourite_subject  FROM `scps_transaction` st INNER JOIN sector s ON s.id = st.sector GROUP BY s.id Limit 2");
            } else {
                $subject_query = mysqli_query($databaseConnection, "SELECT st.sector as `sId`,s.name as favourite_subject  FROM `scps_transaction` st INNER JOIN sector s ON s.id = st.sector GROUP BY s.id");
            }

            /* }*/
            if (mysqli_num_rows($subject_query) > 0) {
                $result = mysqli_fetch_all($subject_query, MYSQLI_ASSOC);

                // $row['subjectData'] = $result;
            } else {
                $result = [];
                // $row['subjectData'] = [];
            }
            array_push($subjectData, $result);
            // }
            $to_encode = array(
                'status' => 1,
                'result' => "success",
                'list' => $subjectData
            );
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "in Error while getting Interview information"
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while getting Interview information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getSubjectInterview'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $menuName = $json['menuName'];
        $subjectName = $json['subjectName'];
        $result = array();
        $interviews = array();
        $interviewValues = array();
        $panelValues = array();

        if ($subjectName == 'null' || $subjectName == '') {
            $interviewData = "select i.*,c.name as categoryName, m.id as menu_id, cp.name as concept_name from `interview` i inner join category c on i.categoryType = c.id left outer join favourite_subject fs on i.subject_id = fs.id left outer join menu_subject_transection mst on fs.id = mst.subject_id left outer join menu m on mst.menu_id = m.id left outer join concepts cp on cp.id = i.concept_id where i.deleted_at is null and i.isActive='Y' and i.categoryType in (1,2,6,7,8) and m.name = '" . $menuName . "' order by i.categoryType desc,i.name";
        } else {
            $interviewData = "select i.*,c.name as categoryName, m.id as menu_id, cp.name as concept_name from `interview` i inner join category c on i.categoryType = c.id left outer join favourite_subject fs on i.subject_id = fs.id left outer join menu_subject_transection mst on fs.id = mst.subject_id left outer join menu m on mst.menu_id = m.id left outer join concepts cp on cp.id = i.concept_id where i.deleted_at is null and i.isActive='Y' and i.categoryType in (1,2,6,7,8) and fs.favourite_subject = '" . $subjectName . "' and m.name = '" . $menuName . "' order by i.categoryType desc,i.name";
        }

        $interviewQuery = mysqli_query($databaseConnection, $interviewData);
        if (mysqli_num_rows($interviewQuery) >= 1) {
            while ($interviewValues = mysqli_fetch_array($interviewQuery, MYSQLI_ASSOC)) {

                $totalAttendedInterviewData = "select count(*) as totalAttendedInterview  from (select count(*) as totalInterview from mergedVideos where interviewId = '" . $interviewValues['id'] . "' group by interviewSessionId) as totalInterviews;";
                $totalAttendedInterviewQuery = mysqli_query($databaseConnection, $totalAttendedInterviewData);
                $totalAttendedInterviewValues = mysqli_fetch_all($totalAttendedInterviewQuery, MYSQLI_ASSOC);

                $panelData = "select * from panel where deleted_at is null and id = '" . $interviewValues['panelId'] . "'";
                $panelQuery = mysqli_query($databaseConnection, $panelData);
                if (mysqli_num_rows($panelQuery) >= 1) {

                    $panelValues = mysqli_fetch_all($panelQuery, MYSQLI_ASSOC);

                    $otherInterviewData = "select * from `interview` where panelId='" . $panelValues[0]['id'] . "' and deleted_at is null  and isActive='Y' and not id = '" . $interviewValues['id'] . "' and categoryType in (1,2,6,7,8)";
                    $otherInterviewQuery = mysqli_query($databaseConnection, $otherInterviewData);
                    if (mysqli_num_rows($otherInterviewQuery) >= 1) {
                        $otherInterviewValues = mysqli_fetch_all($otherInterviewQuery, MYSQLI_ASSOC);
                    } else {
                        $otherInterviewValues = 0;
                    }
                    $panelValues[0]['otherInterviews'] = $otherInterviewValues;
                    $interviewValues['panelId'] = $panelValues;
                    $interviewValues['totalAttendedInterview'] = $totalAttendedInterviewValues[0]['totalAttendedInterview'];
                } else {
                    $to_encode = array(
                        'result' => "info",
                        'status' => 0,
                        'errorCode' => "No panel information found."
                    );
                }
                array_push($interviews, $interviewValues);
            }
            $result['interviews'] = $interviews;
            $to_encode = $result;
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "in Error while getting Interview information",
                'query' => $interviewData
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while getting Interview information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getEmployabilityInterview'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $menuName = $json['menuName'];
        $sectorName = $json['sectorName'];
        $result = array();
        $interviews = array();
        $interviewValues = array();
        $panelValues = array();
        $filter = " WHERE 1 ";
        if ($menuName == 'Events') {
            if ($sectorName != 'null' && $sectorName != '') {
                $sectorName = $sectorName == "SRM AP: Employability Test" ? 'IT Services' : ($sectorName == 'IT Services' ? 'IT Services' : 'IT Product');
                $filter .= " AND s.name = '" . $sectorName . "'";
            }
        } else {
            if ($sectorName != 'null' && $sectorName != '') {
                $filter .= " AND s.name = '" . $sectorName . "'";
            }
        }


        if ($menuName == 'Events') {
            $interviewData = "SELECT s.id,s.name as `name`,6 as productId,st.sector as sectorId,'Freshers' as targetAudience,'25-30 min' as duration,9 as categoryType,'Medium' as interviewLevel FROM `scps_transaction` st  INNER JOIN sector s ON s.id = st.sector " . $filter . " GROUP BY st.sector limit 2";

        } else {
            $interviewData = "SELECT s.id,s.name as `name`,6 as productId,st.sector as sectorId,'Freshers' as targetAudience,'25-30 min' as duration,9 as categoryType,'Medium' as interviewLevel FROM `scps_transaction` st  INNER JOIN sector s ON s.id = st.sector " . $filter . " GROUP BY st.sector;";
        }


        $interviewQuery = mysqli_query($databaseConnection, $interviewData);
        if (mysqli_num_rows($interviewQuery) >= 1) {
            while ($interviewValues = mysqli_fetch_array($interviewQuery, MYSQLI_ASSOC)) {
                array_push($interviews, $interviewValues);
            }
            $result['interviews'] = $interviews;
            $to_encode = $result;
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "in Error while getting Interview information",
                'query' => $interviewData
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while getting Interview information"
        );
    }
    echo json_encode($to_encode);
}
// node-api
elseif (isset($_GET['getCompanyInterview'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $menuName = $json['menuName'];
        $sectorName = $json['sectorName'];
        // $userId=$json['userId'];
        $result = array();
        $interviews = array();
        $interviewValues = array();
        $panelValues = array();
        $filter = " WHERE 1 ";

        $userId = isset($json['userId']) ? $json['userId'] : 'NULL';
        $emailId = '';


        if ($sectorName != 'null' && $sectorName != '')
            $filter .= " AND s.name = '" . $sectorName . "'";

        if ($json['productId'] != '' && $json['productId'] != null) {
            $filter .= " AND pr.productId in (" . $json['productId'] . ")";
        }
        if ($json['productId'] == 1) {
            $filter .= " AND pr.interviewType in ('job')";
        }

        if ($json['preInterviewId'] != '') {
            $filter .= " And pr.id in (" . $json['preInterviewId'] . ")";
        }

        if ($json['userType'] != 'admin' || $json['userType'] == '') {
            $filter .= " And pr.interviewType not in ('college') ";
        }

        if ($json['interviewType'] == 'competition') {
            $filter .= " AND pr.interviewType in ('competition')";
        }

        if ($userId != null) {
            $query = "SELECT emailId FROM users WHERE id = '" . $userId . "'";
            $getData = mysqli_query($databaseConnection, $query);

            if (mysqli_num_rows($getData) > 0) {
                $result = mysqli_fetch_assoc($getData);
                $emailId = $result['emailId'];
            }
        }

        //Shrikant changed : 13/2/2024
        $interviewData = "SELECT jobMatch('$emailId', pr.id) as jobMatch, c.id,case when (c.id=0 or c.id is null) 
        then pr.interviewName when pr.interviewName is not null 
        then pr.interviewName else c.name end as `name`,pr.productId as productId,st.sector as sectorId,pr.targetAudience as targetAudience,pr.duration 
        as duration,pr.categoryType as categoryType,pr.interviewLevel as interviewLevel,st.assessmenttype as assessmenttype,pr.id as preInterviewId,
        case when pr.interviewExpireDate>=now() or pr.interviewExpireDate is null then 'Active' else 'Inactive' end as status,
        case when st.preInterviewId is null and pr.jobCategory in('interview') then 'dummy' else 'real' end as intCat,
        pp.fieldValue AS jobWorkExperience,pp2.fieldValue AS jobLocation  FROM preInterview pr left join `scps_transaction` st on st.
        preInterviewId=pr.id LEFT JOIN aspiration_company c ON st.company = c.id LEFT JOIN sector s ON s.id = st.sector LEFT JOIN  profilePreferences pp ON pr.id = pp.preInterviewId AND pp.fieldName = 'workExperience' LEFT JOIN profilePreferences pp2 ON pr.id = pp2.preInterviewId AND pp2.
        fieldName = 'currentLocation' where pr.publish = 'Y' AND
        (pr.interviewExpireDate >= NOW()) AND pr.serviceType != 'IAS' and pr.interviewStatus in ('Active') GROUP BY pr.id ORDER BY jobMatch DESC
        ";

        $interviewQuery = mysqli_query($databaseConnection, $interviewData);
        if (mysqli_num_rows($interviewQuery) >= 1) {
            while ($interviewValues = mysqli_fetch_array($interviewQuery, MYSQLI_ASSOC)) {
                array_push($interviews, $interviewValues);
            }
            $result['interviews'] = $interviews;
            // $result['locations'] = $locationList;
        } else {
            $result['interviews'] = null;
            // $to_encode = array(
            //     'status' => 0,
            //     'result' => "error",
            //     'errorCode' => "in Error while getting Interview information",
            //     'query' => $interviewData
            // );
        }
        $filter1 = "SELECT id,cityName FROM locations where id not in (512,518,513,516,514,515,517,519) ORDER BY cityName ASC;";
        $filter1Result = mysqli_query($databaseConnection, $filter1);

        $locationList = mysqli_fetch_all($filter1Result, MYSQLI_ASSOC);
        $result['locations'] = $locationList;

        $to_encode = $result;
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while getting Interview information"
        );
    }
    echo json_encode($to_encode);
}
elseif (isset($_GET['getHomepageSubjectInterview'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['candidateId'];

        $interviews = array();
        $interviewValues = array();
        $panelValues = array();

        $query = "SELECT u.id, s.stream as streamName, if(pd.specialization is not NULL and pd.specialization!='11',pd.specialization,1) as stream FROM `users` u left outer join professionaldetails pd on u.id = pd.candidateId left outer join stream s on pd.specialization = s.id WHERE u.id = '" . $candidateId . "'";
        $getData = mysqli_query($databaseConnection, $query);
        $result = mysqli_fetch_assoc($getData);

        $interviewData = "select i.*,c.name as categoryName, m.id as menu_id, m.name as menuName, fs.favourite_subject as subject_name from `interview` i inner join category c on i.categoryType = c.id left outer join favourite_subject fs on i.subject_id = fs.id left outer join menu_subject_transection mst on fs.id = mst.subject_id left outer join menu m on mst.menu_id = m.id left outer join menu_stream_transection ms on m.id = ms.menu_id left outer join stream s on ms.stream_id = s.id where i.deleted_at is null  and i.isActive='Y' and i.categoryType in (1,2,6,7,8) and s.id = '" . $result['stream'] . "'";

        $interviewQuery = mysqli_query($databaseConnection, $interviewData);
        if (mysqli_num_rows($interviewQuery) >= 1) {
            while ($interviewValues = mysqli_fetch_array($interviewQuery, MYSQLI_ASSOC)) {

                $totalAttendedInterviewData = "select count(*) as totalAttendedInterview  from (select count(*) as totalInterview from mergedVideos where interviewId = '" . $interviewValues['id'] . "' group by interviewSessionId) as totalInterviews;";
                $totalAttendedInterviewQuery = mysqli_query($databaseConnection, $totalAttendedInterviewData);
                $totalAttendedInterviewValues = mysqli_fetch_all($totalAttendedInterviewQuery, MYSQLI_ASSOC);

                $panelData = "select * from panel where deleted_at is null and id = '" . $interviewValues['panelId'] . "'";
                $panelQuery = mysqli_query($databaseConnection, $panelData);
                if (mysqli_num_rows($panelQuery) >= 1) {

                    $panelValues = mysqli_fetch_all($panelQuery, MYSQLI_ASSOC);

                    $otherInterviewData = "select * from `interview` where panelId='" . $panelValues[0]['id'] . "' and deleted_at is null  and isActive='Y' and not id = '" . $interviewValues['id'] . "' and categoryType in (1,2,6,7,8)";
                    $otherInterviewQuery = mysqli_query($databaseConnection, $otherInterviewData);
                    if (mysqli_num_rows($otherInterviewQuery) >= 1) {
                        $otherInterviewValues = mysqli_fetch_all($otherInterviewQuery, MYSQLI_ASSOC);
                    } else {
                        $otherInterviewValues = 0;
                    }
                    $panelValues[0]['otherInterviews'] = $otherInterviewValues;
                    $interviewValues['panelId'] = $panelValues;
                    $interviewValues['totalAttendedInterview'] = $totalAttendedInterviewValues[0]['totalAttendedInterview'];
                    $interviewValues['startTime'] = NULL;
                    $interviewValues['endTime'] = NULL;
                } else {
                    $to_encode = array(
                        'result' => "info",
                        'status' => 0,
                        'errorCode' => "No panel information found."
                    );
                }
                array_push($interviews, $interviewValues);
            }
            $to_encode = $interviews;
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "in Error while getting Interview information",
                'streamName' => $result['streamName']
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while getting Interview information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['saveEligibleInterviews'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $panelId = $json['panelId'];
        $eligibleInterviewForReview = $json['eligibleInterviewForReview'];
        $sql = "update panel set eligibleInterviewForReview = '" . $eligibleInterviewForReview . "' where id = '" . $panelId . "';";
        $query = mysqli_query($databaseConnection, $sql);
        if ($query) {
            $to_encode = array(
                'status' => 1,
                'result' => "success"
            );
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "in Error while getting Interview information"
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while getting Interview information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['red5ProServerLoad'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['candidateId'];
        $filecount = 0;
        if ($server == 'live') {
            $directory = "/usr/local/red5pro/webapps/live/streams/";
            $files = glob($directory . "*.info");

            // foreach (glob($directory . "*.info") as $filename) {

            // }

            if ($files) {
                $filecount = count($files);

                $message = "<p>Dear, Jasmeet,</p>
                <p> WE have reached " . $filecount . " concurrent connection it will be soon touch  thersold of 35 info files at red5pro server. Please remove it </P>

                <p>Regards,</p>
                <p>GoPrac Team, Bangalore</p>
                <p>Forum of Industry Professionals</p>
                ";

                if ($filecount >= 90) {
                    sendEmailToUser('jasmeet@goprac.com', null, 'Info Files will reached 95 limit soon', $message);
                }
                $to_encode = array(
                    'status' => 1,
                    'result' => "success",
                    'files' => $filecount,
                    'currentTime' => round(microtime(true) * 1000)
                );
            } else {
                $to_encode = array(
                    'status' => 1,
                    'result' => "success",
                    'msg' => "no red5pro info files",
                    'currentTime' => round(microtime(true) * 1000)
                );
            }
        } else {
            $to_encode = array(
                'status' => 1,
                'result' => "success",
                'msg' => "localhost",
                'files' => $filecount,
                'currentTime' => round(microtime(true) * 1000)
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while getting red5pro information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['sendMailToAdmin'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {

        // $message = "<p>Dear, Jasmeet,</p>
        // <p> WE have reached ". $json['activeUser'] ." concurrent connection it will be soon touch  thersold of 100 info files at red5pro server. Please remove it </P>

        // <p>Regards,</p>
        // <p>GoPrac Team, Bangalore</p>
        // <p>Forum of Industry Professionals</p>
        // ";
        sendEmailToUser('jasmeet@goprac.com', null, "Info Files will reached " . $json['activeUser'] . " limit soon", $json['message']);
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "Mail Could not send"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['red5ProServerLoadForStat'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['candidateId'];
        $infofiles = 0;
        $mtufiles = 0;
        $serfiles = 0;
        $metafiles = 0;
        if ($server == 'live') {
            $directory = "/usr/local/red5pro/webapps/live/streams/";
            $infofiles = glob($directory . "*.info");
            $mtufiles = glob($directory . "*.m3u8");
            $serfiles = glob($directory . "*.ser");
            $metafiles = glob($directory . "*.meta");
            if ($infofiles || $mtufiles || $serfiles || $metafiles) {
                $filecount['info'] = count($infofiles);
                $filecount['mtu'] = count($mtufiles);
                $filecount['ser'] = count($serfiles);
                $filecount['meta'] = count($metafiles);
                $to_encode = array(
                    'status' => 1,
                    'result' => "success",
                    'files' => $filecount,
                    'currentTime' => round(microtime(true) * 1000)
                );
            } else {
                $filecount['info'] = count($infofiles);
                $filecount['mtu'] = count($mtufiles);
                $filecount['ser'] = count($serfiles);
                $filecount['meta'] = count($serfiles);
                $to_encode = array(
                    'status' => 1,
                    'result' => "success",
                    'files' => $filecount,
                    'msg' => "no red5pro info files",
                    'currentTime' => round(microtime(true) * 1000)
                );
            }
        } else {
            $filecount['info'] = $infofiles;
            $filecount['mtu'] = $mtufiles;
            $filecount['ser'] = $serfiles;
            $filecount['meta'] = $serfiles;
            $to_encode = array(
                'status' => 1,
                'result' => "success",
                'msg' => "localhost",
                'files' => $filecount,
                'currentTime' => round(microtime(true) * 1000)
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while getting red5pro information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['exportFeedbackData'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userType = $json['userType'];
        $userId = $json['userId'];
        $filter_query = "";
        $alldata = array();
        $values = array();

        $order_query = " order by m.interviewSessionId desc ";
        $query = "select u.id as userId, u.firstName as name, u.emailId, u.mobileNumber, cl.collegeName, st.stream as specialization, pd.year, pd.specialization as str_id, m.interviewSessionId as sessionId, i.name as interview_name, i.id as intId, fbr.id as fbr_id, fbr.review_status as fbr_status, COUNT(m.questionId) as QA,CASE WHEN i.categoryType = 9 THEN  (SELECT COUNT( CASE WHEN iqt.attemptStatus='Respond' THEN iqt.questionId ELSE NULL END) FROM interview_questions_transection iqt inner join questions qs on qs.id = iqt.questionId WHERE iqt.interviewId=m.interviewId and qs.deleted_at is null and iqt.deleted_at is null and qs.expertAdvice is not null) ELSE (SELECT COUNT(iqt.questionId) FROM interview_questions_transection iqt inner join questions qs on qs.id = iqt.questionId WHERE iqt.interviewId=m.interviewId and qs.deleted_at is null and iqt.deleted_at is null and qs.expertAdvice is not null) END  as NoOfGuidanceVideo, CASE WHEN i.categoryType = 9 THEN  (SELECT COUNT( CASE WHEN iqt.attemptStatus is not NULL THEN iqt.questionId ELSE NULL END) FROM interview_questions_transection iqt inner join questions qs on qs.id = iqt.questionId WHERE iqt.interviewId=m.interviewId and qs.deleted_at is null and iqt.deleted_at is null) ELSE (SELECT COUNT(iqt.questionId) FROM interview_questions_transection iqt inner join questions qs on qs.id = iqt.questionId WHERE iqt.interviewId=m.interviewId and qs.deleted_at is null and iqt.deleted_at is null) -1 END as QT, case when (CASE WHEN i.categoryType = 9 THEN  (SELECT COUNT( CASE WHEN iqt.AttemptStatus is not NULL THEN iqt.questionId ELSE NULL END) FROM interview_questions_transection iqt inner join questions qs on qs.id = iqt.questionId WHERE iqt.interviewId=m.interviewId and qs.deleted_at is null and iqt.deleted_at is null) ELSE (SELECT COUNT(iqt.questionId) FROM interview_questions_transection iqt inner join questions qs on qs.id = iqt.questionId WHERE iqt.interviewId=m.interviewId and qs.deleted_at is null and iqt.deleted_at is null) -1 END)=COUNT(m.questionId) then 'Full' else concat(COUNT(m.questionId),'/',CASE WHEN i.categoryType = 9 THEN  (SELECT COUNT( CASE WHEN iqt.attemptStatus is not NULL THEN iqt.questionId ELSE NULL END) FROM interview_questions_transection iqt inner join questions qs on qs.id = iqt.questionId WHERE iqt.interviewId=m.interviewId and qs.deleted_at is null and iqt.deleted_at is null) ELSE (SELECT COUNT(iqt.questionId) FROM interview_questions_transection iqt inner join questions qs on qs.id = iqt.questionId WHERE iqt.interviewId=m.interviewId and qs.deleted_at is null and iqt.deleted_at is null) -1 END) END as activity, fr.* from interview i, mergedVideos m inner join users u on u.id = m.candidateId inner join professionaldetails pd on pd.candidateId = u.id left outer join stream st on pd.specialization=st.id left outer join colleges cl on cl.id = pd.college left outer join feedback_request fbr on fbr.interviewSessionId = m.interviewSessionId left outer join feedback_report fr on fr.feedbackRequestId = fbr.id where m.interviewId=i.id and u.active='Y' and u.deleted_at is null and fbr.review_status = '2' ";
        $data = '';
        if ($userType == 'college') {
            $college_query = mysqli_query($databaseConnection, "select * from `users` u1 where u1.id =" . $json['userId'] . " order by id limit 1");
            $college = mysqli_fetch_array($college_query, MYSQLI_ASSOC);
            $filter_query .= " and pd.college in (" . $college['college_id'] . ")";
        } elseif ($userType == 'mentor') {
            $filter_query .= " and pd.assignMentorId in (" . $json['userId'] . ")";
        } elseif ($userType == 'student') {
            $filter_query .= " and u.id=" . $json['userId'];
        }
        $data = $query . $filter_query . " group by m.interviewSessionId " . $order_query;

        $query = mysqli_query($databaseConnection, $data);
        if (mysqli_num_rows($query) > 0) {
            $total_data['count'] = mysqli_num_rows($query);
            $total_data['data'] = mysqli_fetch_all($query, MYSQLI_ASSOC);
            $to_encode = $total_data;
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "in Error while retrieving Review information"
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving Review information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['exportFeedbackOnReviewData'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userType = $json['userType'];

        $sql = "SELECT ff.candidateId, ff.feedbackSubmitDate, u.firstName as candidateName, u.mobileNumber as candidateMobile, u.emailId as candidateEmail, cl.collegeName as college,
            CASE
                WHEN isAgree = 1 THEN 'Strongly Agree'
                WHEN isAgree = 2 THEN 'Agree'
                ELSE isAgree
            END as agreeWithOverallFeedback, isAgreeMsg as agreeWithOverallFeedbackMsg,
            CASE
                WHEN detailedFeedback = 1 THEN 'Yes'
                WHEN detailedFeedback = 2 THEN 'No'
                ELSE detailedFeedback
            END as detailedFeedbackForEachQuestion, detailedFeedbackMsg as detailedFeedbackForEachQuestionMsg,
            CASE
                WHEN actionableInputs = 1 THEN 'Yes'
                WHEN actionableInputs = 2 THEN 'No'
                ELSE actionableInputs
            END as feedbackHaveActionableInputs, actionableInputsMsg as feedbackHaveActionableInputsMsg,
            CASE
                WHEN improvingYourself = 1 THEN 'Yes'
                WHEN improvingYourself = 2 THEN 'No'
                ELSE improvingYourself
            END as feedbackByExpertWillHelp, improvingYourselfMsg as feedbackByExpertWillHelpMsg,
            otherFeedback as anyOtherFeedback,
            CASE
                WHEN rateAssessmentReport = 1 THEN 'Yes'
                WHEN rateAssessmentReport = 2 THEN 'No'
                WHEN rateAssessmentReport = 3 THEN 'May be'
                ELSE rateAssessmentReport
            END as rateAssessmentReport, rateAssessmentReportMsg as candidateCommentOnAssementReport 
            FROM feedbackonfeedback ff inner join users u on u.id = ff.candidateId inner join professionaldetails pd on pd.candidateId=u.id left outer join colleges cl on cl.id=pd.college";

        $query = mysqli_query($databaseConnection, $sql);
        if (mysqli_num_rows($query) > 0) {
            $total_data['count'] = mysqli_num_rows($query);
            $row = mysqli_fetch_all($query, MYSQLI_ASSOC);
            $total_data['data'] = $row;
            $to_encode = $total_data;
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "in Error while retrieving Review information"
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while retrieving Review information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['exportIncompletedFeedbackData'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userType = $json['userType'];

        $sql = "SELECT r.candidateId, r.ratingsSubmitTime, u.firstName as candidateName, u.mobileNumber as candidateMobile, u.emailId as candidateEmail, cl.collegeName as college,
            CASE
                WHEN isSubmit = 'Y' THEN 'Yes'
                WHEN isSubmit = 'N' THEN 'No'
                ELSE isSubmit
            END as interviewCompleted,
            CASE
                WHEN bandwidth = '1' THEN 'Yes'
                WHEN bandwidth = '0' THEN 'No'
                ELSE bandwidth
            END as networkBandwidthIsLow,
            CASE
                WHEN expert = '1' THEN 'Yes'
                WHEN expert = '0' THEN 'No'
                ELSE expert
            END as notLikeTheQuestion,
            CASE
                WHEN relevance = '1' THEN 'Yes'
                WHEN relevance = '0' THEN 'No'
                ELSE relevance
            END as interviewIsNotRelavant,
            CASE
                WHEN otherWork = '1' THEN 'Yes'
                WHEN otherWork = '0' THEN 'No'
                ELSE otherWork
            END as someOtherImportantWorkToFinish,
            CASE
                WHEN siteIssue = '1' THEN 'Yes'
                WHEN siteIssue = '0' THEN 'No'
                ELSE siteIssue
            END as expertVideoAudioWhiteboardIssue,
            feedbackReason as candidateFeedback from ratings r inner join users u on u.id = r.candidateId inner join professionaldetails pd on pd.candidateId=u.id left outer join colleges cl on cl.id=pd.college WHERE isSubmit = 'N'";

        $query = mysqli_query($databaseConnection, $sql);
        if (mysqli_num_rows($query) > 0) {
            $total_data['count'] = mysqli_num_rows($query);
            $row = mysqli_fetch_all($query, MYSQLI_ASSOC);
            $total_data['data'] = $row;
            $to_encode = $total_data;
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "in Error while retrieving Review information"
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving Review information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['exportCompletedFeedbackData'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userType = $json['userType'];

        $sql = "SELECT r.candidateId, r.ratingsSubmitTime, u.firstName as candidateName, u.mobileNumber as candidateMobile, u.emailId as candidateEmail, cl.collegeName as college,
            CASE
                WHEN isSubmit = 'Y' THEN 'Yes'
                WHEN isSubmit = 'N' THEN 'No'
                ELSE isSubmit
            END as interviewCompleted,
            userInterface as userExperienceRatingOutOfFive, interviewQuality as qualityOfInterviewRatingOutOfFive,
            CASE
                WHEN complexBtn = '1' THEN 'Simple'
                WHEN complexBtn = '2' THEN 'Medium'
                WHEN complexBtn = '3' THEN 'Hard'
                ELSE complexBtn
            END as complexityOfInterviewQuestions,
            CASE
                WHEN relevantQues = '1' THEN 'Yes'
                WHEN relevantQues = '2' THEN 'May Be'
                WHEN relevantQues = '3' THEN 'No'
                ELSE relevantQues
            END as isQuestionsRelevant,
            CASE
                WHEN recommendInt = '1' THEN 'Yes'
                WHEN recommendInt = '2' THEN 'No'
                ELSE recommendInt
            END as recommendThisInterviewToOthers,
            feedbackReason as candidateFeedback from ratings r inner join users u on u.id = r.candidateId inner join professionaldetails pd on pd.candidateId=u.id left outer join colleges cl on cl.id=pd.college WHERE isSubmit = 'Y'";

        $query = mysqli_query($databaseConnection, $sql);
        if (mysqli_num_rows($query) > 0) {
            $total_data['count'] = mysqli_num_rows($query);
            $row = mysqli_fetch_all($query, MYSQLI_ASSOC);
            $total_data['data'] = $row;
            $to_encode = $total_data;
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "in Error while retrieving Review information"
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving Review information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getReviewData'])) {
    // node-api
    // changes for new rating by Anuj 02-02-2022 
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    $skillMatchResult = '';
    $profileMatchResult = '';
    if (isset($json)) {
        $interviewId = $json['interviewId'];
        $candidateId = $json['candidateId'];
        $usertype = $json['usertype'];
        $interviewSessionId = $json['interviewSessionId'];
        $communicationSkill = 0;
        $confidence = 0;
        $energyLevel = 0;
        $reviewId = 0;
        $requested_url = $json['url'];
        $preInterviewId = '';
        $emailId = '';
        $interview_type = '';
        $jobPreId = '';
        $workExperienceRange = '';
        $intCount = 0;
        $intName = '';

        $preId = "SELECT MAX(preinterviewId) AS maxPreinterviewId FROM interviewSchedule WHERE candidate_id = $candidateId";
        $preInterviewIdResult = mysqli_query($databaseConnection, $preId);

        if ($preInterviewIdResult) {
            $row = mysqli_fetch_assoc($preInterviewIdResult);
            if ($row) {
                $preInterviewId = $row['maxPreinterviewId'];
            }
        }



        $emailid = "SELECT emailId as email FROM interviewSchedule WHERE candidate_id = $candidateId and preInterviewId = $preInterviewId";
        $emailResult = mysqli_query($databaseConnection, $emailid);

        if ($emailResult) {
            $row = mysqli_fetch_assoc($emailResult);
            if ($row) {
                $emailId = $row['email'];
            }
        }
        $suitability = "SELECT $candidateId and preInterviewId = $preInterviewId";
        $emailResult = mysqli_query($databaseConnection, $emailid);

        if ($emailResult) {
            $row = mysqli_fetch_assoc($emailResult);
            if ($row) {
                $emailId = $row['email'];
            }
        }

        $sql = "select i.id as interviewId,
        i.preInterviewId,
        pr.interviewType,
        pr.serviceType,
        i.sector_id,
        i.companyId,
        pr.interviewName as interviewName,
        relavant_role.name as roleName,
        i.productId as interviewProductId,
        p.name as productName,
         m.interviewSessionId,
         u.id as candidateId,
         u.firstName,
         u.usertype as userType,
         u.mobileNumber,u.emailId,
         count(DISTINCT m.mergeId) as totalAttemptedQuestion,CASE WHEN i.categoryType = 9 THEN  (SELECT COUNT( CASE WHEN iqt.attemptStatus is not NULL THEN iqt.questionId ELSE NULL END) FROM interview_questions_transection iqt inner join questions qs on qs.id = iqt.questionId WHERE iqt.interviewId=m.interviewId and qs.deleted_at is null and iqt.deleted_at is null) ELSE (SELECT COUNT(iqt.questionId) FROM interview_questions_transection iqt inner join questions q on q.id = iqt.questionId WHERE iqt.interviewId=m.interviewId and q.deleted_at is null and iqt.deleted_at is null)-1 END as totalQuestion,fs.favourite_subject as subjectName
         from mergedVideos m
         inner join interview i on i.id = m.interviewId
         inner join users u on u.id = m.candidateId
         inner join product p on p.id=i.productId
         LEFT OUTER JOIN `favourite_subject` fs ON fs.id = i.subject_id
         left join preInterview pr on pr.id=i.preInterviewId
         LEFT JOIN relavant_role ON relavant_role.id = pr.roleId AND pr.roleId <> 0
         where m.interviewId = '" . $interviewId . "' and m.candidateId = '" . $candidateId . "' and m.interviewSessionId = '" . $interviewSessionId . "' GROUP by m.interviewSessionId";


        $query = mysqli_query($databaseConnection, $sql);
        if (mysqli_num_rows($query) >= 1) {
            $values = array();
            $row = mysqli_fetch_assoc($query);
            $preIntId = $row['preInterviewId'];
            $interview_type = $row['interviewType'];
            $intName = $row['interviewName'];
            //added by shrikant : 8/1/2024
            $pSkill = "select jobMatch('$emailId', $preIntId) AS profileMatchResult";
            $result1 = mysqli_query($databaseConnection, $pSkill);

            if ($result1) {
                $resultData = mysqli_fetch_assoc($result1);
                if ($resultData) {
                    $profileMatchResult = $resultData['profileMatchResult'];

                }
            }

            $interviewCountQuery = "select count(*) as interviewCount from interview i inner join preInterview pr on i.preInterviewId=pr.id inner join feedback_request fr on fr.interviewId=i.id where pr.id='" . $preIntId . "' and pr.interviewName='" . $intName . "' and fr.candidateId='" . $candidateId . "' and fr.review_status=2";
            $interviewCountQueryResult = mysqli_query($databaseConnection, $interviewCountQuery);

            if ($interviewCountQueryResult) {
                $resultData5 = mysqli_fetch_assoc($interviewCountQueryResult);
                if ($resultData5) {
                    $intCount = $resultData5['interviewCount'];
                    $row['intCount'] = $intCount;
                }
            }

            if ($interview_type == 'job') {
                $workExp = "SELECT fieldValue as fieldValues 
            FROM profilePreferences 
            WHERE fieldName = 'workExperience' AND preInterviewId = '" . $preIntId . "'";
                $workExpResult = mysqli_query($databaseConnection, $workExp);

                if ($workExpResult) {
                    $resultData1 = mysqli_fetch_assoc($workExpResult);
                    if ($resultData1) {
                        $workExperienceRange = $resultData1['fieldValues'];
                        $row['workExperienceRange'] = $workExperienceRange;
                    }
                }

            } else if ($interview_type == 'Practice') {

                $jobPreIdQuery = "SELECT Max(jobPreInterviewId) as jobPreId FROM jobPracticeMapping WHERE practicePreInterviewId = '" . $preIntId . "'";
                $jobPreIdQueryResult = mysqli_query($databaseConnection, $jobPreIdQuery);

                if ($jobPreIdQueryResult) {
                    $resultData2 = mysqli_fetch_assoc($jobPreIdQueryResult);
                    if ($resultData2) {
                        $jobPreId = $resultData2['jobPreId'];
                        $row['jobPreId'] = $jobPreId;
                    }
                }
                if ($jobPreId != '' && $jobPreId != null) {
                    $workExp = "SELECT fieldValue as fieldValues 
            FROM profilePreferences 
            WHERE fieldName = 'workExperience' AND preInterviewId = '" . $jobPreId . "'";
                    $workExpResult = mysqli_query($databaseConnection, $workExp);

                    if ($workExpResult) {
                        $resultData1 = mysqli_fetch_assoc($workExpResult);
                        if ($resultData1) {
                            $workExperienceRange = $resultData1['fieldValues'];
                            $row['workExperienceRange'] = $workExperienceRange;
                        }
                    }
                }
            }

            $totalTimeQry = mysqli_query($databaseConnection, "select SEC_TO_TIME(SUM(TIME_TO_SEC(m.totalTime)) + SUM(TIME_TO_SEC(vwd.prwatchDuration)) + SUM(TIME_TO_SEC(vwd.psWatchDuration)) + SUM(TIME_TO_SEC(vwd.gvWatchDuration))) as timeTakenByCandidate from mergedVideos m inner join video_watched_details vwd on vwd.mergeId = m.mergeId where m.interviewSessionId = '" . $interviewSessionId . "'");
            $totalTimeResult = mysqli_fetch_assoc($totalTimeQry);
            $row['timeTakenByCandidate'] = $totalTimeResult['timeTakenByCandidate'];

            $fr_query = mysqli_query($databaseConnection, "select * from feedback_request where interviewSessionId like '" . $interviewSessionId . "' limit 0,1");

            if (mysqli_num_rows($fr_query) >= 1) {
                $fr_row = mysqli_fetch_assoc($fr_query);

                $row['linkPdf2'] = $fr_row['reportpdf2'];
                $row['linkPdf1'] = $fr_row['reportpdf1'];
                $row['requestDate'] = $fr_row['requestDate'];

                // cleanup
                // $reviewedExpertDetails = mysqli_query($databaseConnection, "select * from panel where id in (select expertId from feedback_status_question where feedbackRequestId = '" . $fr_row['id'] . "') and id != 62 ");

                // if (mysqli_num_rows($reviewedExpertDetails) > 0) {
                //     $reviewedExpertDetailsResult = mysqli_fetch_all($reviewedExpertDetails, MYSQLI_ASSOC);
                //     for ($i = 0; $i < count($reviewedExpertDetailsResult); $i++) {
                //         $reviewedExpertDetailsResult[$i]['companiesWorked'] = explode(",", $reviewedExpertDetailsResult[$i]['companiesWorked'])[0];
                //     }
                //     $row['feedbackReviewedExpertDetails'] = $reviewedExpertDetailsResult;
                // } else {
                //     $row['feedbackReviewedExpertDetails'] = [];
                // }

                $row['feedbackReviewedExpertDetails'] = [];

                if ($fr_row['id'] !== null) {
                    //Shrikant changes : 5/3/2024
                    // $suitability = mysqli_query($databaseConnection, "select  CalculateApplicantSuitability('" . $fr_row['id'] . "',".$interviewId.") as suitability");
                    $suitability = mysqli_query($databaseConnection, "select suitability as suitabilities from  feedback_request where id= '" . $fr_row['id'] . "' ");

                    if (mysqli_num_rows($suitability) > 0) {
                        $suitabilityResults = mysqli_fetch_all($suitability, MYSQLI_ASSOC);
                        if ($suitabilityResults[0]['suitabilities'] != 'N/A') {
                            $row['applicantSuitability'] = $suitabilityResults[0]['suitabilities'];
                        } else {
                            $row['applicantSuitability'] = 'N/A';
                        }

                    } else {
                        $row['applicantSuitability'] = 'N/A';
                    }
                } else {
                    $row['applicantSuitability'] = 'N/A';
                }

                // echo $fr_row['intScore'];
                // exit();

                if ($fr_row['intScore'] !== null && $fr_row['intScore'] !== -1) {
                    // echo "SELECT applicantPercentile('" . $fr_row['intScore'] . "', " . $preIntId . ") AS percentile";
                    $percentile = mysqli_query($databaseConnection, "SELECT applicantPercentile('" . $fr_row['intScore'] . "', " . $preIntId . ") AS percentile");

                    if (mysqli_num_rows($percentile) > 0) {
                        $percentileResults = mysqli_fetch_all($percentile, MYSQLI_ASSOC);
                        $row['applicantPercentile'] = $percentileResults[0]['percentile'];
                    } else {
                        $row['applicantPercentile'] = 'N/A';
                    }
                } else {
                    $row['applicantPercentile'] = 'N/A';
                }

                $row['intScore'] = $fr_row['intScore'];
                $row['fbr_status'] = $fr_row['review_status'];
                $row['fbr_id'] = $fr_row['id'];
                $row['isFeedbackOnFeedbackGiven'] = $fr_row['isFbOnFbGiven'];


                $returnedValue = subjectWiseScore($databaseConnection, $interviewId, $fr_row['id']);

                // cleanup
                // $skillScore = skillWiseScore($databaseConnection, $interviewId);
                // $row['technicalsubjectsScore'] = $skillScore;

                // cleanup
                // $er_query = "select er.questionId, q.key_skill_id, ks.key_skill, q.subjectId from expert_review er inner join questions q on q.id=er.questionId inner join key_skill ks on ks.id=q.key_skill_id 
                //              where er.interviewId= '$interviewId' group by q.key_skill_id,q.subjectId";

                // $er_queryResult = mysqli_query($databaseConnection, $er_query);

                // // Check if there are any results
                // if (mysqli_num_rows($er_queryResult) > 0) {
                //     $er_queryResultData = mysqli_fetch_all($er_queryResult, MYSQLI_ASSOC);
                //     $row['technicalsubjectsScoreskilldata'] = $er_queryResultData;
                // } else {
                //     $row['technicalsubjectsScoreskilldata'] = null;
                // }

                // Query 1: Candidate-specific ratings
                $query1 = "SELECT q.key_skill_id, ks.key_skill, er.overallRating, q.subjectId
                                FROM expert_review er
                                INNER JOIN questions q ON q.id = er.questionId
                                INNER JOIN key_skill ks ON ks.id = q.key_skill_id
                                WHERE er.interviewId = '$interviewId'
                                AND er.overallRating <> 'videoIssue'
                                AND key_skill IN ('Domain Knowledge', 'Problem Solving Skill', 'Analytical & Critical Thinking', 'Problem Understanding', 'Computational Thinking', 'Statistical Thinking', 'Design Thinking', 'Creative Thinking', 'Systems Thinking', 'Logical Thinking', 'Critical Thinking', 'Analytical Thinking', 'Strategic Thinking', 'Agile and Lean Thinking', 'Problem Solving')
                                GROUP BY ks.key_skill;
                                ";

                // echo $query1;

                $result1 = $databaseConnection->query($query1);

                $row['candidateSpecificRatings'] = [];

                if ($result1->num_rows > 0) {
                    while ($candidaterow = $result1->fetch_object()) {
                        $row['candidateSpecificRatings'][] = $candidaterow;
                    }
                } else {
                    $row['candidateSpecificRatings'] = null;
                }

                // Query 2: Platform-wide ratings
                $query2 = "SELECT q.key_skill_id, ks.key_skill, ROUND(AVG(er.overallRating), 1) AS avg_overall_rating
                            FROM expert_review er
                            INNER JOIN questions q ON q.id = er.questionId
                            INNER JOIN key_skill ks ON ks.id = q.key_skill_id
                            WHERE 1
                            AND er.overallRating <> 'videoIssue'
                            AND key_skill IN ('Domain Knowledge', 'Problem Solving Skill', 'Analytical & Critical Thinking','Problem Understanding')
                            GROUP BY ks.key_skill;
                            ";
                $result2 = $databaseConnection->query($query2);

                $row['platformWideRatings'] = [];

                if ($result2->num_rows > 0) {
                    while ($platformrow = $result2->fetch_object()) {
                        $row['platformWideRatings'][] = $platformrow;
                    }
                } else {
                    $row['platformWideRatings'] = null;
                }


                // Query 3: IndustryExpectation
                // NOTE: hardcoded  IndustryExpectation , 7.5 for problem solving and 6.5 for rest
                $query3 = "SELECT q.key_skill_id, ks.key_skill, ROUND(AVG(er.overallRating), 1) AS avg_overall_rating_old,
                        Case WHEN ks.key_skill = 'Problem Solving Skill' THEN 7
                            WHEN ks.key_skill = 'Problem Solving' THEN 7
                            WHEN ks.key_skill = 'Problem Understanding' THEN 5.5
                            ELSE 6 END AS avg_overall_rating
                            FROM  expert_review er
                            INNER JOIN questions q ON q.id = er.questionId
                            INNER JOIN key_skill ks ON ks.id = q.key_skill_id
                            WHERE 1
                            AND er.overallRating <> 'videoIssue'
                            AND key_skill in('Domain Knowledge','Problem Solving Skill','Analytical & Critical Thinking','Problem Understanding', 'Computational Thinking', 'Statistical Thinking', 'Design Thinking', 'Creative Thinking', 'Systems Thinking', 'Logical Thinking', 'Critical Thinking', 'Analytical Thinking', 'Strategic Thinking', 'Agile and Lean Thinking', 'Problem Solving')
                            GROUP BY ks.key_skill;";

                $result3 = $databaseConnection->query($query3);

                $row['IndustryExpectationRating'] = []; // Initialize as an empty array

                if ($result3->num_rows > 0) {
                    while ($sprow = $result3->fetch_object()) {
                        $row['IndustryExpectationRating'][] = $sprow; // Append each row as an object to the array
                    }
                } else {
                    $row['IndustryExpectationRating'] = null;
                }

                $dsquery2 = "SELECT q.key_skill_id, ks.key_skill, er.overallRating, q.subjectId
                                from expert_review er
                                inner join questions q on q.id = er.questionId
                                inner join key_skill ks on ks.id = q.key_skill_id
                                where 1
                                AND er.interviewId = '$interviewId'
                                AND er.overallRating <> 'videoIssue'
                                AND q.subjectId IN(134,1062,287,1,69,552,48,1273)
                                group by q.subjectId;";

                $dsresult2 = $databaseConnection->query($dsquery2);

                $row['candidateSpecificDS'] = [];

                if ($dsresult2->num_rows > 0) {
                    while ($sprow = $dsresult2->fetch_object()) {
                        $row['candidateSpecificDS'][] = $sprow;
                    }
                } else {
                    $row['candidateSpecificDS'] = null;
                }



                $dsquery1 = "SELECT q.key_skill_id,ks.key_skill,er.overallRating,ROUND(AVG(er.overallRating), 1) AS avg_overall_rating
                            FROM  expert_review er
                            INNER JOIN questions q ON q.id = er.questionId
                            INNER JOIN key_skill ks ON ks.id = q.key_skill_id
                            WHERE 1
                            AND er.overallRating <> 'videoIssue'
                            AND q.subjectId IN(134,1062,287,1,69,552,48,1273);";

                $dsresult1 = $databaseConnection->query($dsquery1);

                $row['platformWideDS'] = [];

                if ($dsresult1->num_rows > 0) {
                    while ($sprow = $dsresult1->fetch_object()) {
                        $row['platformWideDS'][] = $sprow;
                    }
                } else {
                    $row['platformWideDS'] = null;
                }

                $dsquery2 = "SELECT q.key_skill_id,ks.key_skill,er.overallRating,ROUND(AVG(er.overallRating), 1) AS avg_overall_rating_old,
                    6 AS avg_overall_rating
                    FROM  expert_review er
                    INNER JOIN questions q ON q.id = er.questionId
                    INNER JOIN key_skill ks ON ks.id = q.key_skill_id
                    LEFT JOIN interviewSchedule isc ON isc.candidate_id  = er.candidateId 
                    WHERE  1
                    AND er.overallRating <> 'videoIssue'
                    AND q.subjectId IN(134,1062,287,1,69,552,48,1273)
                    AND isc.candidateStatus  in('Joined','Profile Shared', 'Offered','Offer Drop','Offer Accepted','Client Shortlisted');";

                $dsresult2 = $databaseConnection->query($dsquery2);

                $row['IndustryExpectationDS'] = [];

                if ($dsresult2->num_rows > 0) {
                    while ($sprow = $dsresult2->fetch_object()) {
                        $row['IndustryExpectationDS'][] = $sprow;
                    }
                } else {
                    $row['IndustryExpectationDS'] = null;
                }

                // Personalised Book
                $personalisedBook = mysqli_query($databaseConnection, "select pb.subject,pb.personalisedNotes from personalisedBook pb inner join favourite_subject fs on fs.id=pb.subject where pb.feedbackRequestId = '" . $row['fbr_id'] . "';");
                if (mysqli_num_rows($personalisedBook) > 0) {
                    $personalisedBookResult = mysqli_fetch_all($personalisedBook, MYSQLI_ASSOC);
                    $row['personalisedBook'] = $personalisedBookResult;
                    $row['skillMatchResult'] = $skillMatchResult;
                    $row['profileMatchResult'] = $profileMatchResult;
                } else {
                    $row['personalisedBook'] = '';
                    $row['skillMatchResult'] = $skillMatchResult;
                    $row['profileMatchResult'] = $profileMatchResult;
                }
                // Personalised Book

                // //  user details

                $candidateStatus = mysqli_query($databaseConnection, "select isc.candidateStatus,cs.candidateStatusDescription, cs.nextStep from interviewSchedule isc inner join candidateStatus cs on cs.candidateStatus=isc.candidateStatus where isc.interviewId = '" . $interviewId . "'");
                if (mysqli_num_rows($candidateStatus) > 0) {
                    $candidateStatusRes = mysqli_fetch_assoc($candidateStatus);
                    $row['candidateStatus'] = $candidateStatusRes['candidateStatus'];
                    $row['candidateStatusDescription'] = $candidateStatusRes['candidateStatusDescription'];
                    $row['candidateStatusNextStep'] = $candidateStatusRes['nextStep'];
                } else {
                    $row['candidateStatus'] = '';
                    $row['candidateStatusDescription'] = '';
                    $row['candidateStatusNextStep'] = '';
                }

                //added by arun for getting userView
                if ($usertype === 'student' || $usertype === 'admin') {
                    $checking_individual_subscription = mysqli_query($databaseConnection, "select * from subscription s where s.candidateId=" . $candidateId . " ");

                    $subscription_amount = mysqli_fetch_assoc($checking_individual_subscription)['amount'];

                    $productId = $row['interviewProductId'];

                    $checking_usersView_table = mysqli_query($databaseConnection, "select * from usersView where candidateId=" . $candidateId . " and url='" . $requested_url . "'");
                    if (mysqli_num_rows($checking_usersView_table) >= 1) {
                        if (mysqli_fetch_assoc($checking_usersView_table)['paidStatus'] == 'Y') {
                            $row['userView'] = '1';
                            $row['adminApproval'] = '1';
                            $row['paidStatus'] = 'Y';
                        } else {
                            $row['userView'] = '0';
                            $row['adminApproval'] = '0';
                            $row['paidStatus'] = 'N';
                        }

                    } else {
                        $row['adminApproval'] = '0';

                        if ($productId == 1) {
                            $row['userView'] = '0';
                            $row['paidStatus'] = 'N';
                        } elseif ($productId == 6 && $subscription_amount <= 1) {
                            $row['userView'] = '0';
                            $row['paidStatus'] = 'N';
                        } else {

                            $checking_college_subscription = mysqli_query($databaseConnection, "select u.emailId,cl.collegeName,cl.id,cs.productId from users u inner join raw_data r on r.email_id=u.emailId inner join colleges cl on cl.collegeName=r.college_name inner join college_subscription cs on cs.collegeId=cl.id  where u.id=" . $candidateId . " and r.ispaid='Y' and FIND_IN_SET($productId,cs.productId)");

                            if (mysqli_num_rows($checking_college_subscription) >= 1) {
                                $row['userView'] = '1';
                                $row['paidStatus'] = 'Y';
                            } else {
                                $checking_individual_subscription = mysqli_query($databaseConnection, "select s.productId,s.candidateId from subscription s where s.candidateId=" . $candidateId . " and FIND_IN_SET($productId,s.productId)");


                                if (mysqli_num_rows($checking_individual_subscription) >= 1) {
                                    $row['userView'] = '1';
                                    $row['paidStatus'] = 'Y';
                                } else {
                                    $row['userView'] = '0';
                                    $row['paidStatus'] = 'N';
                                }
                            }
                        }
                    }
                    // sourabh-payment

                    $checking_interview_payment = mysqli_query($databaseConnection, "select * from payment_transaction pt where pt.user_id=" . $candidateId . " AND pt.interview_id=" . $interviewId . " AND `status` IN('PAID') ");


                    if (mysqli_num_rows($checking_interview_payment) >= 1) {
                        $payment_status_code = mysqli_fetch_assoc($checking_interview_payment)['status'];

                        if ($payment_status_code == "PAID") {
                            $row['userView'] = '1';
                            $row['paidStatus'] = 'Y';
                        }

                    }


                    // TODO : sourabh-payment remove when payment gateway becomes active
                    $checking_interview_payment = mysqli_query($databaseConnection, "select * from connect_mentor cm where cm.candidateId=" . $candidateId . " AND cm.interviewId=" . $interviewId . " AND `connectInterest` IN('paid') ");
                    
                    if (mysqli_num_rows($checking_interview_payment) >= 1) {
                        $row['userView'] = '1';
                        $row['paidStatus'] = 'Y';
                    }
                }
                

                $row['summery'] = 0;
            } else {
                $row['fbr_status'] = -1;
                $row['fbr_id'] = 0;
                $row['isFeedbackOnFeedbackGiven'] = NULL;
                $row['requestDate'] = null;
                $row['feedbackReviewedExpertDetails'] = '';
            }
            $ai_feedback_query = mysqli_query($databaseConnection, "select aif.* from ai_feedback aif inner join mergedVideos m on m.outputVideoURL = aif.outputVideoURL where m.mergeId = aif.mergeId and m.interviewSessionId = '" . $interviewSessionId . "'");
            $row['avg_ai_feedback_data'] = '';
            if (mysqli_num_rows($ai_feedback_query) > 0) {
                $ai_feedback_data = mysqli_fetch_all($ai_feedback_query, MYSQLI_ASSOC);
                for ($i = 0; $i < count($ai_feedback_data); $i++) {
                    $communicationSkill = $communicationSkill + ($ai_feedback_data[$i]['communicationSkill'] * 100);
                    $confidence = $confidence + ($ai_feedback_data[$i]['confidence'] * 100);
                    $energyLevel = $energyLevel + ($ai_feedback_data[$i]['energyLevel'] * 100);
                }
                $row['avg_ai_feedback_data'] = array(
                    'communicationSkill' => $communicationSkill / count($ai_feedback_data),
                    'confidence' => $confidence / count($ai_feedback_data),
                    'energyLevel' => $energyLevel / count($ai_feedback_data)
                );
            }

            // topics assessed
            $topic_assessed_sql = "SELECT q.id, t.id as topicId, q.subjectId, fs.favourite_subject,  t.name
                FROM `topic` t
                LEFT OUTER JOIN `questions` q ON q.topic_id = t.id
                LEFT OUTER JOIN favourite_subject fs ON q.subjectId  = fs.id
                WHERE q.id IN (
                    SELECT iqt.questionId
                    FROM interview_questions_transection iqt
                    where attemptStatus in('Respond','Respond1','Respond2', 'Skip') and iqt.interviewId = " . $interviewId . ")";

            // echo $topic_assessed_sql;
            $topic_assessed_query = mysqli_query($databaseConnection, $topic_assessed_sql);

            if (mysqli_num_rows($topic_assessed_query) >= 1) {
                $topic_assessed_rows = mysqli_fetch_all($topic_assessed_query, MYSQLI_ASSOC);
            } else {
                $topic_assessed_rows = null;
            }
            $row['topics_assessed'] = $topic_assessed_rows;
            $row['jobScreeningAnswers'] = array();

            $safeReviewPreInterviewId = (int) $preIntId;
            $safeReviewCandidateId = (int) $candidateId;
            if ($safeReviewPreInterviewId > 0 && $safeReviewCandidateId > 0) {
                $screeningAnswersQuery = "
                    SELECT
                        q.id AS questionId,
                        q.questionText,
                        q.questionType,
                        q.sortOrder,
                        a.answerText,
                        a.createdAt AS submittedAt
                    FROM jobScreeningQuestions q
                    INNER JOIN jobScreeningAnswers a
                        ON a.preInterviewId = q.preInterviewId
                        AND a.scrnQuestionId = q.id
                    WHERE q.preInterviewId = " . $safeReviewPreInterviewId . "
                        AND a.candidateId = " . $safeReviewCandidateId . "
                        AND (q.isActive IS NULL OR q.isActive = 'Y')
                        AND a.answerText IS NOT NULL
                        AND TRIM(a.answerText) != ''
                    ORDER BY q.sortOrder ASC, q.id ASC";
                $screeningAnswersResult = mysqli_query($databaseConnection, $screeningAnswersQuery);
                if ($screeningAnswersResult) {
                    $row['jobScreeningAnswers'] = mysqli_fetch_all($screeningAnswersResult, MYSQLI_ASSOC);
                }
            }

            $values = $row;
            $to_encode = $values;
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'errorCode' => "in Error while retrieving Review information"
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while retrieving Review information"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getResumeData'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    $to_encode = array();
    if (isset($json)) {
        $email = $json['email'];
        $subject = $json['subject'];

        function decodeBase64Chunks($base64String)
        {
            $chunkSize = 8192; // Adjust this value based on your needs
            $totalChunks = ceil(strlen($base64String) / $chunkSize);
            $result = [];

            for ($i = 0; $i < $totalChunks; $i++) {
                $chunk = substr($base64String, $i * $chunkSize, $chunkSize);
                $result[] = base64_decode($chunk);
            }

            return implode('', $result);
        }
        $body = isset($json['body']) ? decodeBase64Chunks($json['body']) : null;
        $pdfData2 = isset($json['pdf']) ? base64_decode($json['pdf']) : null;
        sendEmailToUserReport($email, null, $subject, $body, $pdfData2);
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while updating information.",
        );
    }
    echo json_encode($to_encode);

} elseif (isset($_GET['listOfJobs'])) {
    $sql = "select * from job_notifications where is_deleted=false order by jobId desc";
    $result = mysqli_query($databaseConnection, $sql);
    //create an array
    $jobarray = array();
    if (mysqli_num_rows($result) >= 1) {
        while ($row = mysqli_fetch_assoc($result)) {
            $jobarray[] = $row;
        }
    }
    $to_encode = array(
        'data' => $jobarray
    );
    echo json_encode($to_encode);
    //close the db connection
} elseif (isset($_GET['insertJobs'])) {
    $data = @file_get_contents("php://input");
    $jsonArr = json_decode($data, true);
    $jobarray = array();
    if (isset($jsonArr)) {
        foreach ($jsonArr as $json) {
            $companyName = $json['company_name'];
            $title = $json['job_title'];
            /*$desc =  $json['job_description']; 
                $skills =  $json['skills_required'];*/
            $employment_type = $json['employment_type'];
            $eligibility = $json['eligibility'];
            $lastDate = $json['last_date'];
            $link = $json['link'];
            $createdBy = $json['created_by'];
            $uniqueId = $json['clientId'];
            $sql = "INSERT INTO `job_notifications`(`company_name`, `job_title`, `employment_type`, `eligibility`, `last_date`, `link`, `created_by`) VALUES ('$companyName','$title','$employment_type','$eligibility','$lastDate','$link',$createdBy)";
            $sqlQuery = mysqli_query($databaseConnection, $sql) or trigger_error("Query Failed! SQL: $sql - Error: " . mysqli_error($databaseConnection), E_USER_ERROR);
            ;
            if ($sqlQuery) {
                $id = mysqli_insert_id($databaseConnection);
                $jobarray[$uniqueId] = $id;
            } else {
                $jobarray[$uniqueId] = "failed";
            }
        }
    }
    echo json_encode($jobarray);
    //close the db connection

} elseif (isset($_GET['delJobs'])) {
    # code...
    $data = @file_get_contents("php://input");
    $jsonArr = json_decode($data, true);
    $jobarray = array();
    if (isset($jsonArr)) {
        foreach ($jsonArr as $json) {
            $id = $json['id'];
            $userId = $json['modified_by'];
            $sql = "UPDATE `job_notifications` set `is_deleted` = true, `modified_by`= $userId where `jobId`=$id";
            $sqlQuery = mysqli_query($databaseConnection, $sql) or trigger_error("Query Failed! SQL: $sql - Error: " . mysqli_error($databaseConnection), E_USER_ERROR);
            if ($sqlQuery) {
                $jobarray[$id] = true;
            } else {

                $jobarray[$id] = false;
            }
        }
    }
    echo json_encode($jobarray);
    //close the db connection

} elseif (isset($_GET['updateJobs'])) {
    # code...
    $data = @file_get_contents("php://input");
    $jsonArr = json_decode($data, true);
    $jobarray = array();
    if (isset($jsonArr)) {
        foreach ($jsonArr as $json) {
            $id = $json['id'];
            $userId = $json['modified_by'];

            $companyName = $json['company_name'];
            $title = $json['job_title'];
            /*$desc =  $json['job_description']; 
                $skills =  $json['skills_required'];*/
            $employment_type = $json['employment_type'];
            $eligibility = $json['eligibility'];
            $lastDate = $json['last_date'];
            $link = $json['link'];

            $sql = "UPDATE `job_notifications` set `modified_by`= $userId, `company_name`='$companyName', `job_title`='$title', `employment_type`='$employment_type', `eligibility`='$eligibility', `last_date`='$lastDate',`link`='$link' where `jobId`=$id";
            $sqlQuery = mysqli_query($databaseConnection, $sql) or trigger_error("Query Failed! SQL: $sql - Error: " . mysqli_error($databaseConnection), E_USER_ERROR);
            if ($sqlQuery) {
                $jobarray[$id] = true;
            } else {

                $jobarray[$id] = false;
            }
        }
    }
    echo json_encode($jobarray);
    //close the db connection

} elseif (isset($_GET['checkQAByQT'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $countQuestionQuery = "SELECT COUNT(q.id)-1 as QT from questions q inner join interview_questions_transection iqt on iqt.questionId = q.id inner join interview i on i.id = iqt.interviewId where iqt.interviewId = '" . $json['interviewId'] . "' and q.isActive = 'Y' and q.deleted_at is null and iqt.deleted_at is null order by iqt.sequence";

        $countResult = mysqli_query($databaseConnection, $countQuestionQuery);

        $attemptQuestionQuery = "SELECT COUNT(mergeId) as QA FROM `mergedVideos` m WHERE interviewId= '" . $json['interviewId'] . "' AND candidateId= '" . $json['candidateId'] . "' AND interviewSessionId= '" . $json['interviewSessionId'] . "'";
        $attemptResult = mysqli_query($databaseConnection, $attemptQuestionQuery);

        if ($countResult) {
            $QT = mysqli_fetch_assoc($countResult);
            $row['QT'] = $QT['QT'];
        }
        if ($attemptResult) {
            $QA = mysqli_fetch_assoc($attemptResult);
            $row['QA'] = $QA['QA'];
        }

        $interviewName = mysqli_query($databaseConnection, "SELECT name FROM `interview` WHERE id = '" . $json['interviewId'] . "'");
        if ($interviewName) {
            $interviewValue = mysqli_fetch_assoc($interviewName);
            $row['interviewName'] = $interviewValue['name'];
        }

        $to_encode = array(
            'status' => '1',
            'result' => $row,
        );
    } else {

        $to_encode = array(
            'status' => '0',
            'QAquery' => $attemptQuestionQuery,
            'QTquery' => $countQuestionQuery
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['checkQAByQTForStatic'])) {
    /* this api is added for checking new QA by Qt Rule  */

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $countQuestionQuery = "SELECT COUNT(q.id)-1 as QT from questions q inner join interview_questions_transection iqt on iqt.questionId = q.id inner join interview i on i.id = iqt.interviewId where iqt.interviewId = '" . $json['interviewId'] . "' and q.isActive = 'Y' and q.deleted_at is null and iqt.deleted_at is null order by iqt.sequence";

        $countResult = mysqli_query($databaseConnection, $countQuestionQuery);

        $attemptQuestionQuery = "SELECT COUNT(mergeId) as QA FROM `mergedVideos` m WHERE interviewId= '" . $json['interviewId'] . "' AND candidateId= '" . $json['candidateId'] . "' AND interviewSessionId= '" . $json['interviewSessionId'] . "'";
        $attemptResult = mysqli_query($databaseConnection, $attemptQuestionQuery);

        if ($countResult) {
            $QT = mysqli_fetch_assoc($countResult);
            $row['QT'] = $QT['QT'];
        }
        if ($attemptResult) {
            $QA = mysqli_fetch_assoc($attemptResult);
            $row['QA'] = $QA['QA'];
        }

        $interviewName = mysqli_query($databaseConnection, "SELECT name FROM `interview` WHERE id = '" . $json['interviewId'] . "'");
        if ($interviewName) {
            $interviewValue = mysqli_fetch_assoc($interviewName);
            $row['interviewName'] = $interviewValue['name'];
        }

        $to_encode = array(
            'status' => '1',
            'result' => $row,
        );
    } else {

        $to_encode = array(
            'status' => '0',
            'QAquery' => $attemptQuestionQuery,
            'QTquery' => $countQuestionQuery
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['getSuggestedNameList'])) {
    //for expert suggested name list by devanand merge by anuj 19-11-2021
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        if ($json['name'] != "") {
            $name = $json['name'];

            $data = "select name  from `panel` where name like '%" . addslashes($name) . "%' limit 0, 20";
            $query = mysqli_query($databaseConnection, $data);
            if (mysqli_num_rows($query) >= 1) {
                $values = mysqli_fetch_all($query, MYSQLI_ASSOC);
                $to_encode = $values;
            } else {
                $to_encode = array(
                    'status' => 0,
                    'result' => "no info",
                    'errorCode' => "no interview info found",
                    'query' => $data
                );
            }

        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "no info",
                'errorCode' => "No Key Press yet",
            );
        }

    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving interview information."
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['getSuggestedCollegeList'])) {
    //this method is added by arun on 30 dec 2022 to get suggested college at signup page
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        if ($json['name'] != "") {
            $name = $json['name'];

            $data = "select id,collegeName  from `colleges` where collegeName like '%" . addslashes($name) . "%' limit 0, 20";
            $query = mysqli_query($databaseConnection, $data);
            if (mysqli_num_rows($query) >= 1) {
                $values = mysqli_fetch_all($query, MYSQLI_ASSOC);
                $to_encode = $values;
            } else {
                $to_encode = array(
                    'status' => 0,
                    'result' => "no info",
                    'errorCode' => "no college found",
                    'query' => $data
                );
            }

        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "no info",
                'errorCode' => "No Key Press yet",
            );
        }

    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving interview information."
        );
    }
    echo json_encode($to_encode);
}
// node-api
else if (isset($_GET['getSuggestedLocationList'])) {
    //this method is added by arun on 30 dec 2022 to get suggested college at signup page
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        if ($json['name'] != "") {
            $name = $json['name'];

            $data = "select id,cityName  from `locations` where cityName like '%" . addslashes($name) . "%' limit 0, 20";
            $query = mysqli_query($databaseConnection, $data);
            if (mysqli_num_rows($query) >= 1) {
                $values = mysqli_fetch_all($query, MYSQLI_ASSOC);
                $to_encode = $values;
            } else {
                $to_encode = array(
                    'status' => 0,
                    'result' => "no info",
                    'errorCode' => "no Location found",
                    'query' => $data
                );
            }

        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "no info",
                'errorCode' => "No Key Press yet",
            );
        }

    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving Location information."
        );
    }
    echo json_encode($to_encode);
}
else if (isset($_GET['getWebinarDetails'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['candidateId'];

        $query = "select wd.id,wd.webinar_title from webinar_details wd inner join 
       webinar_registration_details wrd on wd.id=wrd.webinarId where wrd.candidateId='" . $candidateId . "' AND wrd.attend = 'Y'";
        $webinarAttended = mysqli_query($databaseConnection, $query);
        if (mysqli_num_rows($webinarAttended) > 0) {
            $row = mysqli_fetch_all($webinarAttended, MYSQLI_ASSOC);
            $to_encode = $row;
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "success",
                'errorCode' => "no data avaialble",
                'query' => $query
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while retrieving information",
            'query' => $query

        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['getGivenAssessmentDetails'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['userId'];
        $interviewId = $json['interviewId'];

        $value = array();

        if ($candidateId) {
            $row = getSubsciptionDetailsAndAssessment($databaseConnection, $candidateId);

            // $assessmentQuery="SELECT `freeTrialAssesmentAllowed` , `mockAssesmentAllowed` as '1', `communicationAssesmentAllowed` as '2', `behaviouralAssesmentAllowed` as '3', `problemsolvingAssesmentAllowed` as '4', `codingAssesmentAllowed` as '5' FROM `subscription` WHERE candidateId = '".$candidateId."'";
            // array_push($row,mysqli_fetch_assoc(mysqli_query($databaseConnection,$assessmentQuery)));
            $to_encode = $row;
        }

        array_push($value, $row);

        $getProductQuery = "SELECT `productId` FROM `interview` WHERE id = '" . $interviewId . "'";
        $getProductResult = mysqli_query($databaseConnection, $getProductQuery);
        $productValue = mysqli_fetch_assoc($getProductResult);

        $value['productId'] = $productValue['productId'];

        $getAssessmentQuery = "SELECT COUNT(fr.interviewSessionId) as Total ,(SELECT COUNT(fr.interviewSessionId) as Total FROM `feedback_request` fr CROSS JOIN `interview` i ON fr.interviewId = i.id WHERE fr.candidateId = '" . $candidateId . "'  AND fr.review_status in (0,1,2,-3)  AND fr.requestDate >= '" . $row['startDate'] . "' AND fr.requestDate <= '" . $row['endDate'] . "') as overAllAssessment FROM `feedback_request` fr CROSS JOIN `interview` i ON fr.interviewId = i.id WHERE fr.candidateId = '" . $candidateId . "'  AND fr.review_status in (0,1,2,-3) AND i.productId = '" . $productValue['productId'] . "' AND fr.requestDate >= '" . $row['startDate'] . "' AND fr.requestDate <= '" . $row['endDate'] . "'";

        $getAssessmentResult = mysqli_query($databaseConnection, $getAssessmentQuery);
        $assessmentValue = mysqli_fetch_assoc($getAssessmentResult);
        $value['taken'] = $assessmentValue['Total'];
        $value['overAllAssessment'] = $assessmentValue['overAllAssessment'];

        // $value['qry'] = $getAssessmentQuery;


        $to_encode = $value;

    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while retrieving information",
            'query' => $query

        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['getFeedbackAboutPlatform'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    $filterQuery = "";

    if ($json['userType'] == 'mentor') {
        $filterQuery .= " AND pd.assignMentorId = " . $json['userId'] . "";
    }
    if ($json['userType'] == 'college') {
        $filterQuery .= " AND pd.college = (SELECT college_id FROM `users` WHERE id = " . $json['userId'] . ")";
    }

    $query = "SELECT r.ratingsSubmitTime,i.name as interviewName,u.firstName as candidateName,u.mobileNumber,u.emailId,c.collegeName,pd.year as YOP,s.stream,r.interviewQuality as 'Complexity of Question',r.overallExperience,r.feedbackReason as Comments FROM ratings r INNER JOIN users u ON r.candidateId = u.id LEFT OUTER JOIN interview i ON i.id = r.interviewId LEFT OUTER JOIN professionaldetails pd ON pd.candidateId = u.id left outer join colleges c on c.id=pd.college inner join stream s on s.id=pd.specialization WHERE r.isSubmit='Y' and r.interviewSessionId is not null" . $filterQuery . " ORDER BY r.ratingsSubmitTime DESC";
    $resultData = mysqli_query($databaseConnection, $query);
    if ($resultData) {
        $resultValue = mysqli_fetch_all($resultData, MYSQLI_ASSOC);

        $to_encode = array(
            'status' => 1,
            'result' => $resultValue,
            'query' => $query

        );

    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error while retrieving information",
            'query' => $query

        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['insertActivityLog'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    $userId = $json['token'] != '0' ? getDecrypt($json['token'])->userId : $json['token'];
    $ipaddress = '';
    if (isset($_SERVER['REMOTE_ADDR']))
        $ipaddress = $_SERVER['REMOTE_ADDR'];
    else
        $ipaddress = 'UNKNOWN';

    if (isset($json)) {
        $query = "INSERT INTO `candidate_log`(`userId`, `ip`, `pageName`, `comments`, `action`, `logTime`) VALUES (" . $userId . ",'" . $ipaddress . "','" . $json['pageName'] . "','" . $json['comments'] . "','" . $json['action'] . "',now())";
        $resultData = mysqli_query($databaseConnection, $query);
        if ($resultData) {
            $to_encode = array(
                'status' => 1,
                'result' => $resultData
            );

        } else {
            $to_encode = array(
                'status' => -1,
                'result' => "error",
                'errorCode' => "out Error while inserting log",
                'query' => $query

            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'status' => -1,
        );
    }


    echo json_encode($to_encode);
} else if (isset($_GET['unResponsedDeselect'])) {

    // To revert unresponded mail for peer video by anuj 11-01-2022
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    if (isset($json)) {
        $query = "UPDATE questions q, mergedVideos mv SET q.peerResponseStatus = 'A' WHERE mv.questionId = q.id AND  mv.emailSentDate is not null and q.peerResponseStatus  not in ('NA', 'A') and q.mbr_id = '0' and q.peerResponseVideo is null AND DATEDIFF(now(),mv.emailSentDate) > 15;";

        $resultData = mysqli_query($databaseConnection, $query);
        if ($resultData) {
            $to_encode = array(
                'status' => 1,
                'result' => $resultData,

            );

        } else {
            $to_encode = array(
                'status' => -1,
                'result' => "error",
                'errorCode' => "Error while updating",
                'query' => $query

            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'status' => -1,
        );
    }


    echo json_encode($to_encode);
} else if (isset($_GET['getStudentScore'])) {
    // to calculate feedback data for candidate by Anuj 02-02-2022
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    $reviewData = array();
    $row = array();
    if (isset($json)) {

        $query = "SELECT interviewId,interviewSessionId,candidateId FROM mergedVideos WHERE candidateId = " . $json['candidateId'] . " GROUP BY interviewId ORDER BY mergeId DESC";
        $resultData = mysqli_query($databaseConnection, $query);
        if (mysqli_num_rows($resultData) > 0) {
            // $resultValue = mysqli_fetch_all($resultData,MYSQLI_ASSOC);
            $query_sector = "SELECT temp.sectorName,ifs.value as employabilityStatus,temp.companyName as companyName,temp.interviewName as interviewTaken,temp.favouriteSubject as subjectAssessed FROM (SELECT s.id as sectorId,s.name as sectorName,AVG(er.overallRating) as skillScore,GROUP_CONCAT(DISTINCT i.name SEPARATOR ', ') as interviewName,GROUP_CONCAT(DISTINCT SUBSTRING_INDEX(i.name,'_',1) SEPARATOR ', ') as companyName,GROUP_CONCAT(DISTINCT fs.favourite_subject SEPARATOR ', ') as favouriteSubject FROM expert_review er LEFT JOIN feedback_request fr ON er.feedback_request_id = fr.id LEFT OUTER JOIN interview i ON i.id = er.interviewId LEFT OUTER JOIN sector s ON s.id = i.sector_id LEFT OUTER JOIN questions q ON q.id = er.questionId LEFT OUTER JOIN favourite_subject fs ON fs.id = q.subjectId WHERE fr.review_status = 2 AND er.overallRating != 'videoIssue' AND er.overallRating IS NOT null AND i.productId in (1,6) AND er.candidateId = " . $json['candidateId'] . " GROUP BY s.id) as temp LEFT OUTER JOIN ier_for_sector ifs ON ifs.sector_id = temp.sectorId AND ifs.score = (CASE WHEN temp.skillScore <= 4 THEN round(temp.skillScore) WHEN temp.skillScore > 4 and temp.skillScore < 7 THEN 6 ELSE round(temp.skillScore) END);";
            $query_sector_result = mysqli_query($databaseConnection, $query_sector);
            $query_sector_data = mysqli_fetch_all($query_sector_result, MYSQLI_ASSOC);
            $reviewData['sectorWiseData'] = $query_sector_data;

            $apptitude_score_query = "select fv.favourite_subject as subjectName, ROUND(AVG(er.overallRating),1) as skillScore,GROUP_CONCAT(DISTINCT CASE  WHEN er.overallRating > 4   and (q.topic_id is not null or q.topic_id != '' or q.topic_id !=766)  THEN  t.name END SEPARATOR ', ') as whatsGood,GROUP_CONCAT(DISTINCT CASE  WHEN er.overallRating <= 4   and (q.topic_id is not null or q.topic_id != '' or q.topic_id !=766)  THEN  t.name  END SEPARATOR ', ') as whatNeedtobeImprove from expert_review er  inner join feedback_request fr on  fr.id = er.feedback_request_id inner join questions q on q.id = er.questionId inner join users u on u.id = er.candidateId inner join professionaldetails pd on pd.candidateId = u.id inner join favourite_subject fv on fv.id = q.subjectId inner join interview i on i.id = er.interviewId  LEFT OUTER JOIN topic t ON t.id = q.topic_id where fr.review_status =2 and er.review_type='question' and q.subjectId is not null and er.overAllRating !='videoIssue' and er.candidateId = " . $json['candidateId'] . "  group by q.subjectId order by fv.favourite_subject;";
            $apptitude_score_result = mysqli_query($databaseConnection, $apptitude_score_query);
            $reviewData['apptitudeScoreData'] = mysqli_fetch_all($apptitude_score_result, MYSQLI_ASSOC);

            $expert_company_query = "SELECT p.name,SUBSTRING_INDEX(p.companiesWorked,',',2) as companies,p.linkedinProfile as linkedinProfile FROM newFeedbackReport nfr LEFT OUTER JOIN expert_review er ON er.id = nfr.expertReviewId LEFT OUTER JOIN panel p ON p.id = er.feedbackGivenBy WHERE nfr.candidateId = " . $json['candidateId'] . " GROUP BY p.id;";
            $expert_company_result = mysqli_query($databaseConnection, $expert_company_query);
            $reviewData['expertDetails'] = mysqli_fetch_all($expert_company_result, MYSQLI_ASSOC);

            $recommend_qry = "SELECT ks.key_skill,oa.key_skill ,er.questionId,fs.favourite_subject as subjectName,t.name as topicName,oa.observation_name as observationName,oa.observation_type ,q.id from expert_review er INNER JOIN expert_review_observation_details erod ON erod.expertReviewId = er.id LEFT OUTER JOIN observation_area oa ON oa.id = erod.observationAreaId LEFT OUTER JOIN key_skill ks ON ks.id = oa.key_skill LEFT OUTER JOIN questions q ON q.id = er.questionId LEFT OUTER JOIN favourite_subject fs ON fs.id = q.subjectId LEFT OUTER JOIN topic t ON t.id = q.topic_id where er.feedback_request_id IN (SELECT id FROM `feedback_request` WHERE review_status = 2 AND candidateId = " . $json['candidateId'] . " ORDER BY `id` DESC) AND er.review_type = 'question' AND oa.observation_type IS NOT null";
            $recommend_qry_result = mysqli_query($databaseConnection, $recommend_qry);
            $recommend_qry_data = mysqli_fetch_all($recommend_qry_result, MYSQLI_ASSOC);
            $reviewData['recommendData'] = $recommend_qry_data;

            $videoWatch_qry = "SELECT temp.*,
            SEC_TO_TIME(SUM(TIME_TO_SEC(temp.prWatchDuration)+TIME_TO_SEC(temp.psWatchDuration)+TIME_TO_SEC(temp.gvWatchDuration))) as totalWatch,
            SEC_TO_TIME(SUM(TIME_TO_SEC(temp.personalizedVideo)+TIME_TO_SEC(temp.gvVideo)+TIME_TO_SEC(temp.prVideo))) as totalAvailable,
            (SUM(TIME_TO_SEC(temp.prWatchDuration)+TIME_TO_SEC(temp.psWatchDuration)+TIME_TO_SEC(temp.gvWatchDuration))) as totalWatchSec,
            (SUM(TIME_TO_SEC(temp.personalizedVideo)+TIME_TO_SEC(temp.gvVideo)+TIME_TO_SEC(temp.prVideo))) as totalAvailableSec
            FROM (SELECT vwd.*,m.mergeId as mergedId,oa.key_skill ,er.questionId,CASE WHEN er.vidLength IS NOT null THEN er.vidLength ELSE '00:00:00' END as personalizedVideo, CASE WHEN qt.vidLength IS NOT null AND qt.delegationType = 'guidanceVideo' THEN qt.vidLength ELSE '00:00:00' END as gvVideo,CASE WHEN qt.vidLength IS NOT null AND qt.delegationType = 'peerResponseVideo' THEN qt.vidLength ELSE '00:00:00' END as prVideo from expert_review er INNER JOIN expert_review_observation_details erod ON erod.expertReviewId = er.id LEFT OUTER JOIN observation_area oa ON oa.id = erod.observationAreaId INNER JOIN feedback_request fr ON fr.id = er.feedback_request_id INNER JOIN mergedVideos m ON m.interviewSessionId = fr.interviewSessionId AND m.candidateId = er.candidateId AND m.questionId = er.questionId AND m.interviewId = er.interviewId LEFT OUTER JOIN video_watched_details vwd ON vwd.mergeId = m.mergeId LEFT OUTER JOIN questions_transection qt ON qt.questionId = er.questionId where er.feedback_request_id IN (SELECT id FROM `feedback_request` WHERE review_status = 2 AND candidateId = " . $json['candidateId'] . " ORDER BY `id` DESC) AND er.review_type = 'question' AND oa.observation_type IS NOT null GROUP BY m.mergeId ) as temp GROUP BY temp.key_skill;";
            $videoWatch_qry_result = mysqli_query($databaseConnection, $videoWatch_qry);
            $videoWatch_qry_data = mysqli_fetch_all($videoWatch_qry_result, MYSQLI_ASSOC);
            $reviewData['videoWatchData'] = $videoWatch_qry_data;

            // $peerSkillwise_aptitude_qry = "SELECT GROUP_CONCAT(t.SkillScore) as SkillScore, GROUP_CONCAT(t.AssessmentSequence) as AssessmentSequence,t.key_skill_id,t.skillName AS skillName FROM (SELECT ROUND(AVG(nfr.SkillScore),1) as skillScore,fr.AssessmentSequence,nfr.key_skill_id,nfr.skillName from newFeedbackReport nfr LEFT OUTER JOIN feedback_request fr ON fr.id = nfr.feedback_request_id  group by nfr.key_skill_id,fr.AssessmentSequence order by fr.AssessmentSequence,nfr.key_skill_id) as t GROUP BY t.key_skill_id;";

            $peerSkillwise_aptitude_qry = "SELECT GROUP_CONCAT(temp1.skillScore) as SkillScore,temp1.key_skill_id, GROUP_CONCAT(round(time_to_sec(temp1.durationRange)/3600,4)) as AssessmentSequence,temp1.skillName AS skillName from (SELECT ROUND(AVG(temp.skillScore),1) as  SkillScore,temp.key_skill_id,temp.skillName AS skillName,temp.durationRange  from (
                SELECT nfr.skillScore,nfr.key_skill_id,nfr.skillName ,CASE WHEN nfr.cumulativeDuration <= '00:30:00' THEN '00:30:00'    WHEN  nfr.cumulativeDuration > '00:30:00' and nfr.cumulativeDuration <= '01:00:00' THEN '01:00:00'   WHEN  nfr.cumulativeDuration > '01:00:00' and nfr.cumulativeDuration <= '01:30:00' THEN '01:30:00'     WHEN  nfr.cumulativeDuration > '01:30:00' and nfr.cumulativeDuration <= '02:00:00' THEN '02:00:00'     WHEN  nfr.cumulativeDuration > '02:00:00' and nfr.cumulativeDuration <= '02:30:00' THEN '02:30:00'  WHEN  nfr.cumulativeDuration > '02:30:00' and nfr.cumulativeDuration <= '03:00:00' THEN '03:00:00'    WHEN  nfr.cumulativeDuration  > '03:00:00'  and nfr.cumulativeDuration <= '03:30:00'  THEN '03:30:00'   WHEN  nfr.cumulativeDuration > '03:30:00' and nfr.cumulativeDuration <= '04:00:00' THEN '04:00:00'     WHEN  nfr.cumulativeDuration > '04:00:00' and nfr.cumulativeDuration <= '04:30:00' THEN '04:30:00'     WHEN  nfr.cumulativeDuration > '04:30:00' and nfr.cumulativeDuration <= '05:00:00' THEN '05:00:00'     WHEN  nfr.cumulativeDuration > '05:00:00' and nfr.cumulativeDuration <= '05:30:00' THEN '05:30:00'    WHEN  nfr.cumulativeDuration > '00:30:00' and nfr.cumulativeDuration <= '06:00:00' THEN '06:00:00'     WHEN  nfr.cumulativeDuration > '06:00:00' and nfr.cumulativeDuration <= '06:30:00' THEN '06:30:00'    WHEN  nfr.cumulativeDuration > '06:30:00' and nfr.cumulativeDuration <= '07:00:00' THEN '07:00:00'   WHEN  nfr.cumulativeDuration > '07:00:00' and nfr.cumulativeDuration <= '07:30:00' THEN '07:30:00' WHEN  nfr.cumulativeDuration > '07:30:00' and nfr.cumulativeDuration <= '08:00:00' THEN '08:00:00' WHEN  nfr.cumulativeDuration > '08:00:00' and nfr.cumulativeDuration <= '08:30:00' THEN '08:30:00' WHEN  nfr.cumulativeDuration > '08:30:00' and nfr.cumulativeDuration <= '09:00:00' THEN '09:00:00' WHEN  nfr.cumulativeDuration > '09:00:00' and nfr.cumulativeDuration <= '09:30:00' THEN '09:30:00' WHEN  nfr.cumulativeDuration > '09:30:00' and nfr.cumulativeDuration <= '10:00:00' THEN '10:00:00' WHEN  nfr.cumulativeDuration > '10:00:00' and nfr.cumulativeDuration <= '10:30:00' THEN '10:30:00' WHEN  nfr.cumulativeDuration > '10:30:00' and nfr.cumulativeDuration <= '11:00:00' THEN '11:00:00' WHEN  nfr.cumulativeDuration > '11:00:00' and nfr.cumulativeDuration <= '11:30:00' THEN '11:30:00' WHEN  nfr.cumulativeDuration > '11:30:00' and nfr.cumulativeDuration <= '11:30:00' THEN '11:30:00' WHEN  nfr.cumulativeDuration > '11:30:00' and nfr.cumulativeDuration <= '12:00:00' THEN '12:00:00' WHEN  nfr.cumulativeDuration > '12:00:00'  and nfr.cumulativeDuration <= '12:30:00' THEN '12:30:00' WHEN  nfr.cumulativeDuration > '12:30:00' and nfr.cumulativeDuration <= '13:00:00' THEN '13:00:00' WHEN  nfr.cumulativeDuration > '13:00:00' and nfr.cumulativeDuration <= '13:30:00' THEN '13:30:00' ELSE 'More than 13.30' END as durationRange  from newFeedbackReport nfr inner join feedback_request fr on fr.id = nfr.feedback_request_id inner join users u  on u.id = nfr.candidateId  inner join professionaldetails pd on pd.candidateId = u.id     where fr.review_status = 2  and  nfr.key_skill_id in (1,2,3,6,8)  order by  nfr.key_skill_id , nfr.cumulativeDuration ) as temp  group by temp.key_skill_id,temp.durationRange order by temp.key_skill_id,temp.durationRange) as temp1 GROUP BY temp1.key_skill_id";

            $peerSkillwise_aptitude_data = mysqli_query($databaseConnection, $peerSkillwise_aptitude_qry);
            $peerSkillwise_aptitude_result = mysqli_fetch_all($peerSkillwise_aptitude_data, MYSQLI_ASSOC);
            // $reviewData['skillwiseApptitudeScorePeer'] = $peerSkillwise_aptitude_result;

            // $clgSkillwise_aptitude_qry = "SELECT GROUP_CONCAT(t.SkillScore) as SkillScore, GROUP_CONCAT(t.AssessmentSequence) as AssessmentSequence,t.key_skill_id,t.skillName AS skillName FROM (SELECT ROUND(AVG(nfr.SkillScore),1) as skillScore,fr.AssessmentSequence,nfr.key_skill_id,nfr.skillName from newFeedbackReport nfr LEFT OUTER JOIN feedback_request fr ON fr.id = nfr.feedback_request_id WHERE nfr.candidateId IN (SELECT professionaldetails.candidateId FROM professionaldetails WHERE professionaldetails.college = (SELECT college FROM professionaldetails WHERE candidateId = ".$json['candidateId'].")) group by nfr.key_skill_id,fr.AssessmentSequence order by fr.AssessmentSequence,nfr.key_skill_id) as t GROUP BY t.key_skill_id;";

            // $clgSkillwise_aptitude_qry = "SELECT GROUP_CONCAT(t.scoreAvg) as SkillScore, GROUP_CONCAT(t.skillSequence) as AssessmentSequence,t.key_skill_id,t.skillName AS skillName FROM (SELECT round(AVG(skillScore),1) as scoreAvg,skillName,key_skill_id,skillSequence FROM `newFeedbackReport` WHERE candidateId IN (SELECT professionaldetails.candidateId FROM professionaldetails WHERE professionaldetails.college = (SELECT college FROM professionaldetails WHERE candidateId = ".$json['candidateId'].")) GROUP BY key_skill_id,skillSequence ORDER BY key_skill_id,skillSequence) as t GROUP BY t.key_skill_id;";
            $clgSkillwise_aptitude_qry = "SELECT GROUP_CONCAT(temp1.skillScore) as SkillScore,temp1.key_skill_id, GROUP_CONCAT(round(time_to_sec(temp1.durationRange)/3600,4)) as AssessmentSequence,temp1.skillName AS skillName from (SELECT ROUND(AVG(temp.skillScore),1) as  SkillScore,temp.key_skill_id,temp.skillName AS skillName,temp.durationRange  from (
                SELECT nfr.skillScore,nfr.key_skill_id,nfr.skillName ,CASE WHEN nfr.cumulativeDuration <= '00:30:00' THEN '00:30:00'    WHEN  nfr.cumulativeDuration > '00:30:00' and nfr.cumulativeDuration <= '01:00:00' THEN '01:00:00'   WHEN  nfr.cumulativeDuration > '01:00:00' and nfr.cumulativeDuration <= '01:30:00' THEN '01:30:00'     WHEN  nfr.cumulativeDuration > '01:30:00' and nfr.cumulativeDuration <= '02:00:00' THEN '02:00:00'     WHEN  nfr.cumulativeDuration > '02:00:00' and nfr.cumulativeDuration <= '02:30:00' THEN '02:30:00'  WHEN  nfr.cumulativeDuration > '02:30:00' and nfr.cumulativeDuration <= '03:00:00' THEN '03:00:00'    WHEN  nfr.cumulativeDuration  > '03:00:00'  and nfr.cumulativeDuration <= '03:30:00'  THEN '03:30:00'   WHEN  nfr.cumulativeDuration > '03:30:00' and nfr.cumulativeDuration <= '04:00:00' THEN '04:00:00'     WHEN  nfr.cumulativeDuration > '04:00:00' and nfr.cumulativeDuration <= '04:30:00' THEN '04:30:00'     WHEN  nfr.cumulativeDuration > '04:30:00' and nfr.cumulativeDuration <= '05:00:00' THEN '05:00:00'     WHEN  nfr.cumulativeDuration > '05:00:00' and nfr.cumulativeDuration <= '05:30:00' THEN '05:30:00'    WHEN  nfr.cumulativeDuration > '00:30:00' and nfr.cumulativeDuration <= '06:00:00' THEN '06:00:00'     WHEN  nfr.cumulativeDuration > '06:00:00' and nfr.cumulativeDuration <= '06:30:00' THEN '06:30:00'    WHEN  nfr.cumulativeDuration > '06:30:00' and nfr.cumulativeDuration <= '07:00:00' THEN '07:00:00'   WHEN  nfr.cumulativeDuration > '07:00:00' and nfr.cumulativeDuration <= '07:30:00' THEN '07:30:00' WHEN  nfr.cumulativeDuration > '07:30:00' and nfr.cumulativeDuration <= '08:00:00' THEN '08:00:00' WHEN  nfr.cumulativeDuration > '08:00:00' and nfr.cumulativeDuration <= '08:30:00' THEN '08:30:00' WHEN  nfr.cumulativeDuration > '08:30:00' and nfr.cumulativeDuration <= '09:00:00' THEN '09:00:00' WHEN  nfr.cumulativeDuration > '09:00:00' and nfr.cumulativeDuration <= '09:30:00' THEN '09:30:00' WHEN  nfr.cumulativeDuration > '09:30:00' and nfr.cumulativeDuration <= '10:00:00' THEN '10:00:00' WHEN  nfr.cumulativeDuration > '10:00:00' and nfr.cumulativeDuration <= '10:30:00' THEN '10:30:00' WHEN  nfr.cumulativeDuration > '10:30:00' and nfr.cumulativeDuration <= '11:00:00' THEN '11:00:00' WHEN  nfr.cumulativeDuration > '11:00:00' and nfr.cumulativeDuration <= '11:30:00' THEN '11:30:00' WHEN  nfr.cumulativeDuration > '11:30:00' and nfr.cumulativeDuration <= '11:30:00' THEN '11:30:00' WHEN  nfr.cumulativeDuration > '11:30:00' and nfr.cumulativeDuration <= '12:00:00' THEN '12:00:00' WHEN  nfr.cumulativeDuration > '12:00:00'  and nfr.cumulativeDuration <= '12:30:00' THEN '12:30:00' WHEN  nfr.cumulativeDuration > '12:30:00' and nfr.cumulativeDuration <= '13:00:00' THEN '13:00:00' WHEN  nfr.cumulativeDuration > '13:00:00' and nfr.cumulativeDuration <= '13:30:00' THEN '13:30:00' ELSE 'More than 13.30' END as durationRange  from newFeedbackReport nfr inner join feedback_request fr on fr.id = nfr.feedback_request_id inner join users u  on u.id = nfr.candidateId  inner join professionaldetails pd on pd.candidateId = u.id     where fr.review_status = 2  and  nfr.key_skill_id in (1,2,3,6,8) AND pd.college = (SELECT college FROM professionaldetails WHERE candidateId = " . $json['candidateId'] . ")   order by  nfr.key_skill_id , nfr.cumulativeDuration ) as temp  group by temp.key_skill_id,temp.durationRange order by temp.key_skill_id,temp.durationRange) as temp1 GROUP BY temp1.key_skill_id";

            $clgSkillwise_aptitude_data = mysqli_query($databaseConnection, $clgSkillwise_aptitude_qry);
            $clgSkillwise_aptitude_result = mysqli_fetch_all($clgSkillwise_aptitude_data, MYSQLI_ASSOC);

            $peerPlatform_qry = "SELECT ROUND(AVG(SkillScore),1) as skillScore,key_skill_id,skillName, ROUND((SUM(TIME_TO_SEC(cumulativeDuration)+TIME_TO_SEC(contentConsumed))/count(SkillScore))/3600,2) as DurationAvg from newFeedbackReport group by key_skill_id order by key_skill_id,skillScore";

            $peerPlatform_data = mysqli_query($databaseConnection, $peerPlatform_qry);
            $peerPlatform_result = mysqli_fetch_all($peerPlatform_data, MYSQLI_ASSOC);

            $yourAvrg_qry = "SELECT ROUND(AVG(SkillScore),1) as skillScore,key_skill_id,skillName, ROUND((SUM(TIME_TO_SEC(cumulativeDuration)+TIME_TO_SEC(contentConsumed))/count(SkillScore))/3600,2) as DurationAvg from newFeedbackReport WHERE candidateId = " . $json['candidateId'] . " group by key_skill_id order by key_skill_id,skillScore";

            $skill_ier_query = mysqli_query($databaseConnection, "SELECT key_skill_id,`value`,score FROM `ier_for_skills` GROUP BY key_skill_id,`value` ORDER BY key_skill_id,score ASC");
            if (mysqli_num_rows($skill_ier_query) >= 1) {
                $ier_rows = mysqli_fetch_all($skill_ier_query, MYSQLI_ASSOC);
            } else {
                $ier_rows = '';
            }
            $reviewData['skill_ier'] = $ier_rows;

            $yourAvrg_data = mysqli_query($databaseConnection, $yourAvrg_qry);
            $yourAvrg_result = mysqli_fetch_all($yourAvrg_data, MYSQLI_ASSOC);
            // $reviewData['clgSkillwiseApptitudeScore'] = $clgSkillwise_aptitude_result;

            // $skillwise_aptitude_qry = "SELECT GROUP_CONCAT(t.SkillScore) as SkillScore, GROUP_CONCAT(t.AssessmentSequence) as AssessmentSequence,t.key_skill_id,t.skillName AS skillName FROM (SELECT ROUND(AVG(nfr.SkillScore),1) as skillScore,fr.AssessmentSequence,nfr.key_skill_id,nfr.skillName from newFeedbackReport nfr LEFT OUTER JOIN feedback_request fr ON fr.id = nfr.feedback_request_id WHERE nfr.candidateId IN (".$json['candidateId'].") group by nfr.key_skill_id,fr.AssessmentSequence order by fr.AssessmentSequence,nfr.key_skill_id) as t GROUP BY t.key_skill_id;";

            // $skillwise_aptitude_qry = "SELECT GROUP_CONCAT(t.scoreAvg) as SkillScore, GROUP_CONCAT(t.skillSequence) as AssessmentSequence,t.key_skill_id,t.skillName AS skillName FROM (SELECT round(AVG(skillScore),1) as scoreAvg,skillName,key_skill_id,skillSequence FROM `newFeedbackReport` WHERE key_skill_id IN (1,2,3,6,8) AND candidateId = ".$json['candidateId']." GROUP BY key_skill_id,skillSequence ORDER BY key_skill_id,skillSequence) as t GROUP BY t.key_skill_id;
            // ";
            $skillwise_aptitude_qry = "SELECT GROUP_CONCAT(temp1.skillScore) as SkillScore,temp1.key_skill_id, GROUP_CONCAT(round(time_to_sec(temp1.durationRange)/3600,4)) as AssessmentSequence,temp1.skillName AS skillName from (SELECT ROUND(AVG(temp.skillScore),1) as  SkillScore,temp.key_skill_id,temp.skillName AS skillName,temp.durationRange  from (
                SELECT nfr.skillScore,nfr.key_skill_id,nfr.skillName ,CASE WHEN nfr.cumulativeDuration <= '00:30:00' THEN '00:30:00'    WHEN  nfr.cumulativeDuration > '00:30:00' and nfr.cumulativeDuration <= '01:00:00' THEN '01:00:00'   WHEN  nfr.cumulativeDuration > '01:00:00' and nfr.cumulativeDuration <= '01:30:00' THEN '01:30:00'     WHEN  nfr.cumulativeDuration > '01:30:00' and nfr.cumulativeDuration <= '02:00:00' THEN '02:00:00'     WHEN  nfr.cumulativeDuration > '02:00:00' and nfr.cumulativeDuration <= '02:30:00' THEN '02:30:00'  WHEN  nfr.cumulativeDuration > '02:30:00' and nfr.cumulativeDuration <= '03:00:00' THEN '03:00:00'    WHEN  nfr.cumulativeDuration  > '03:00:00'  and nfr.cumulativeDuration <= '03:30:00'  THEN '03:30:00'   WHEN  nfr.cumulativeDuration > '03:30:00' and nfr.cumulativeDuration <= '04:00:00' THEN '04:00:00'     WHEN  nfr.cumulativeDuration > '04:00:00' and nfr.cumulativeDuration <= '04:30:00' THEN '04:30:00'     WHEN  nfr.cumulativeDuration > '04:30:00' and nfr.cumulativeDuration <= '05:00:00' THEN '05:00:00'     WHEN  nfr.cumulativeDuration > '05:00:00' and nfr.cumulativeDuration <= '05:30:00' THEN '05:30:00'    WHEN  nfr.cumulativeDuration > '00:30:00' and nfr.cumulativeDuration <= '06:00:00' THEN '06:00:00'     WHEN  nfr.cumulativeDuration > '06:00:00' and nfr.cumulativeDuration <= '06:30:00' THEN '06:30:00'    WHEN  nfr.cumulativeDuration > '06:30:00' and nfr.cumulativeDuration <= '07:00:00' THEN '07:00:00'   WHEN  nfr.cumulativeDuration > '07:00:00' and nfr.cumulativeDuration <= '07:30:00' THEN '07:30:00' WHEN  nfr.cumulativeDuration > '07:30:00' and nfr.cumulativeDuration <= '08:00:00' THEN '08:00:00' WHEN  nfr.cumulativeDuration > '08:00:00' and nfr.cumulativeDuration <= '08:30:00' THEN '08:30:00' WHEN  nfr.cumulativeDuration > '08:30:00' and nfr.cumulativeDuration <= '09:00:00' THEN '09:00:00' WHEN  nfr.cumulativeDuration > '09:00:00' and nfr.cumulativeDuration <= '09:30:00' THEN '09:30:00' WHEN  nfr.cumulativeDuration > '09:30:00' and nfr.cumulativeDuration <= '10:00:00' THEN '10:00:00' WHEN  nfr.cumulativeDuration > '10:00:00' and nfr.cumulativeDuration <= '10:30:00' THEN '10:30:00' WHEN  nfr.cumulativeDuration > '10:30:00' and nfr.cumulativeDuration <= '11:00:00' THEN '11:00:00' WHEN  nfr.cumulativeDuration > '11:00:00' and nfr.cumulativeDuration <= '11:30:00' THEN '11:30:00' WHEN  nfr.cumulativeDuration > '11:30:00' and nfr.cumulativeDuration <= '11:30:00' THEN '11:30:00' WHEN  nfr.cumulativeDuration > '11:30:00' and nfr.cumulativeDuration <= '12:00:00' THEN '12:00:00' WHEN  nfr.cumulativeDuration > '12:00:00'  and nfr.cumulativeDuration <= '12:30:00' THEN '12:30:00' WHEN  nfr.cumulativeDuration > '12:30:00' and nfr.cumulativeDuration <= '13:00:00' THEN '13:00:00' WHEN  nfr.cumulativeDuration > '13:00:00' and nfr.cumulativeDuration <= '13:30:00' THEN '13:30:00' ELSE 'More than 13.30' END as durationRange  from newFeedbackReport nfr inner join feedback_request fr on fr.id = nfr.feedback_request_id inner join users u  on u.id = nfr.candidateId  inner join professionaldetails pd on pd.candidateId = u.id     where fr.review_status = 2  and  nfr.key_skill_id in (1,2,3,6,8) AND pd.candidateId = " . $json['candidateId'] . "   order by  nfr.key_skill_id , nfr.cumulativeDuration ) as temp  group by temp.key_skill_id,temp.durationRange order by temp.key_skill_id,temp.durationRange) as temp1 GROUP BY temp1.key_skill_id";

            $skillwise_aptitude_data = mysqli_query($databaseConnection, $skillwise_aptitude_qry);
            $skillwise_aptitude_result = mysqli_fetch_all($skillwise_aptitude_data, MYSQLI_ASSOC);
            for ($i = 0; $i < count($skillwise_aptitude_result); $i++) {
                $skillwise_aptitude_result[$i]['graphId'] = explode(' ', $skillwise_aptitude_result[$i]['skillName'])[0] . "graph";
                for ($k = 0; $k < count($peerSkillwise_aptitude_result); $k++) {
                    if ($peerSkillwise_aptitude_result[$k]['key_skill_id'] == $skillwise_aptitude_result[$i]['key_skill_id']) {
                        $skillwise_aptitude_result[$i]['peerSkillScore'] = $peerSkillwise_aptitude_result[$k]['SkillScore'];
                        $skillwise_aptitude_result[$i]['peerAssessmentSequence'] = $peerSkillwise_aptitude_result[$k]['AssessmentSequence'];
                    }
                }
                for ($k = 0; $k < count($clgSkillwise_aptitude_result); $k++) {
                    if ($clgSkillwise_aptitude_result[$k]['key_skill_id'] == $skillwise_aptitude_result[$i]['key_skill_id']) {
                        $skillwise_aptitude_result[$i]['clgSkillScore'] = $clgSkillwise_aptitude_result[$k]['SkillScore'];
                        $skillwise_aptitude_result[$i]['clgAssessmentSequence'] = $clgSkillwise_aptitude_result[$k]['AssessmentSequence'];
                    }
                }
                for ($k = 0; $k < count($yourAvrg_result); $k++) {
                    if ($yourAvrg_result[$k]['key_skill_id'] == $skillwise_aptitude_result[$i]['key_skill_id']) {
                        $skillwise_aptitude_result[$i]['skillAvg'] = $yourAvrg_result[$k]['skillScore'];
                    }
                }
                for ($k = 0; $k < count($peerPlatform_result); $k++) {
                    if ($peerPlatform_result[$k]['key_skill_id'] == $skillwise_aptitude_result[$i]['key_skill_id']) {
                        $skillwise_aptitude_result[$i]['peerSkillAvg'] = $peerPlatform_result[$k]['skillScore'];
                    }
                }
            }
            $reviewData['skillwiseApptitudeScore'] = $skillwise_aptitude_result;

            $topVideoId = "SELECT mv.youtubeId,nfr.skillScore
            FROM newFeedbackReport nfr INNER JOIN feedback_request fr ON fr.id = nfr.feedback_request_id INNER JOIN mergedVideos mv ON nfr.candidateId = mv.candidateId AND mv.questionId = nfr.questionId AND mv.interviewId = nfr.interviewId AND mv.interviewSessionId = fr.interviewSessionId  WHERE nfr.skillName = 'Communication Skill' AND nfr.candidateId = " . $json['candidateId'] . " ORDER BY nfr.skillScore DESC LIMIT 1;";
            $topVideoId_result = mysqli_query($databaseConnection, $topVideoId);
            if (mysqli_num_rows($topVideoId_result) > 0) {
                $reviewData['topVideoId'] = mysqli_fetch_all($topVideoId_result, MYSQLI_ASSOC)[0]['youtubeId'];
            } else {
                $reviewData['topVideoId'] = 0;
            }

            $qry = "SELECT id FROM feedback_request WHERE candidateId = " . $json['candidateId'] . " AND review_status = 2";
            $qry_result = mysqli_query($databaseConnection, $qry);
            $num_rows = mysqli_num_rows($qry_result);
            if ($num_rows >= 1) {
                $completeData = array();
                $fbr_id = '0';
                // while($row_swd = mysqli_fetch_assoc($qry_result))
                {
                    // $fbr_id .= ",".$row_swd['id'];

                    $query_skill_wise = "select oa.observation_name,ROUND((SUM(ov.observation_values)/count(erod.observationAreaId)),1) as PlateformAvg from expert_review er inner join expert_review_observation_details erod on er.id = erod.expertReviewId inner join observation_area oa on oa.id = erod.observationAreaId inner join observation_values ov on ov.id = erod.observationValueId where oa.mandatory =1 and ov.observation_values !='Not Applicable' and er.review_type='question' and er.overAllRating !='videoIssue' and er.questionId in(select questionId from expert_review where feedback_request_id IN (SELECT id FROM feedback_request WHERE candidateId = " . $json['candidateId'] . " AND review_status = 2)) group by erod.observationAreaId order by oa.key_skill ASC;";
                    $query_skill_result = mysqli_query($databaseConnection, $query_skill_wise);
                    $query_skill_data = mysqli_fetch_all($query_skill_result, MYSQLI_ASSOC);
                    array_push($completeData, $query_skill_data);
                }
                $reviewData['skillWiseData'] = $completeData;
                // $reviewData['skillWiseDataqry']=$query_skill_wise;
            } else {
                $reviewData['skillWiseData'] = array(
                    'status' => -1,
                    'message' => 'no feedback found',
                );
            }

            $to_encode = array(
                'status' => 1,
                'result' => $reviewData,
                'query' => $query

            );

        } else {
            $to_encode = array(
                'status' => -1,
                'result' => "No interview found for candidate " . $json['candidateId'],
                'query' => $query

            );
        }

    } else {
        $to_encode = array(
            'result' => "error",
            'status' => -1,
        );
    }


    echo json_encode($to_encode);
} else if (isset($_GET['updatePriority'])) {

    // To revert unresponded mail for peer video by anuj 11-01-2022
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    if (isset($json)) {
        $query = "UPDATE `mergedVideos` SET `priority`='" . $json['priority'] . "' WHERE mergeId = " . $json['mergeId'] . "";

        $resultData = mysqli_query($databaseConnection, $query);
        if ($resultData) {
            $to_encode = array(
                'status' => 1,
                'result' => $resultData,

            );

        } else {
            $to_encode = array(
                'status' => -1,
                'result' => "error",
                'errorCode' => "Error while updating",
                'query' => $query
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'status' => -1,
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['activeRed5proUser'])) {
    $query = "SELECT COUNT(CASE WHEN ((`status` = 'test' AND TIMESTAMPDIFF(MINUTE,updatedAt,now()) < 3) OR (`status` = 'start' AND TIMESTAMPDIFF(MINUTE,updatedAt,now()) < 50)) THEN id ELSE null END) as totalActive,90 as totalAllowed FROM `active_redfive_user` WHERE `isActive` = 'Y';";
    $resultData = mysqli_query($databaseConnection, $query);
    if ($resultData) {
        $to_encode = array(
            'status' => 1,
            'result' => mysqli_fetch_all($resultData, MYSQLI_ASSOC)
        );

    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "Error while counting",
            'query' => $query

        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['markRed5proUserStatus'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    if (isset($json)) {
        $checkUser = "SELECT * FROM `active_redfive_user` WHERE candidateId = " . $json['candidateId'] . "";
        $checkUserData = mysqli_query($databaseConnection, $checkUser);
        if (mysqli_num_rows($checkUserData) > 0) {
            $updateUser = "UPDATE `active_redfive_user` SET `status` = '" . $json['status'] . "',`isActive` = 'Y',`updatedAt` = now() WHERE candidateId = '" . $json['candidateId'] . "'";
            $updateUserData = mysqli_query($databaseConnection, $updateUser);
            if ($updateUserData) {
                $to_encode = array(
                    'status' => 1,
                    'result' => "updated",
                );
            } else {
                $to_encode = array(
                    'status' => -1,
                    'result' => "error while Update",
                    'qry' => $updateUser
                );
            }
        } else {
            $insertUser = "INSERT INTO `active_redfive_user`(`candidateId`, `status`, `isActive`, `updatedAt`) VALUES (" . $json['candidateId'] . ",'" . $json['status'] . "','Y',now());";
            $insertUserData = mysqli_query($databaseConnection, $insertUser);
            if ($insertUserData) {
                $to_encode = array(
                    'status' => 1,
                    'result' => "record Insert",
                );
            } else {
                $to_encode = array(
                    'status' => -1,
                    'result' => "error while insertion",
                    'qry' => $insertUser
                );
            }

        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "Error while Decoding Data",
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['markRed5proUserInactive'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    if (isset($json)) {
        $updateUser = "UPDATE `active_redfive_user` SET `isActive` = 'N' WHERE candidateId = '" . $json['candidateId'] . "'";
        $updateUserData = mysqli_query($databaseConnection, $updateUser);
        if ($updateUserData) {
            $to_encode = array(
                'status' => 1,
                'result' => "updated",
            );
        } else {
            $to_encode = array(
                'status' => -1,
                'result' => "error while Update",
                'qry' => $updateUser
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "Error while Decoding Data",
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['getInterviewProducts'])) {
    $productQry = "SELECT `id`,`name` as `value` FROM `menu`;";
    $productResult = mysqli_query($databaseConnection, $productQry);
    if (mysqli_num_rows($productResult) > 0) {
        $productValue = mysqli_fetch_all($productResult, MYSQLI_ASSOC);
        $to_encode = array(
            'data' => $productValue,
            'status' => 1
        );
    } else {
        $to_encode = array(
            'data' => 'none',
            'status' => -1
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['getInterviewList'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if ($json) {

        if ($json['pId'] == '1') {
            $interviewQry = "SELECT c.id," . $json['pId'] . " as productId,st.sector as sectorId,c.name as `name` FROM `scps_transaction` st INNER JOIN aspiration_company c ON st.company = c.id WHERE st.company NOT IN (0)  GROUP BY st.company,st.sector ORDER BY c.name ASC ";
        } else if ($json['pId'] == '6') {
            $interviewQry = "SELECT s.id," . $json['pId'] . " as productId,st.sector as sectorId,s.name as `name` FROM `scps_transaction` st INNER JOIN sector s ON st.sector = s.id GROUP BY st.sector ORDER BY s.name ASC ";
        } else {
            $interviewQry = "select i.id," . $json['pId'] . " as productId,i.name,i.role,i.duration,i.interviewLevel,i.categoryType,i.targetAudience, m.id as menu_id, fs.favourite_subject as subject_name from `interview` i left outer join favourite_subject fs on i.subject_id = fs.id left outer join menu_subject_transection mst on fs.id = mst.subject_id left outer join menu m on mst.menu_id = m.id where i.deleted_at is null  and i.isActive='Y' and i.categoryType in (1,2,6,7,8) and m.id = '" . $json['pId'] . "' order by i.name ASC";
        }
        $interviewResult = mysqli_query($databaseConnection, $interviewQry);
        if (mysqli_num_rows($interviewResult) > 0) {
            $interviewValue = mysqli_fetch_all($interviewResult, MYSQLI_ASSOC);
            $to_encode = array(
                'data' => $interviewValue,
                'status' => 1
            );
        } else {
            $to_encode = array(
                'data' => 'none',
                'status' => -1
            );
        }
    } else {
        $to_encode = array(
            'data' => 'unable to decode JSON',
            'status' => -1
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['getPendingQuestionSubjectWise'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if ($json) {
        $filterQry = " ";
        $havingQry = " HAVING 1 ";
        $finalArray = array();
        if ($json['subject'] != '') {
            $filterQry .= " AND q.subjectId IN (" . implode(",", $json['subject']) . ") ";
        }
        if ($json['noOfPenQues'] != '') {
            $havingQry .= " AND pendingQuestion " . $json['noOfPenQues'] . "";
        }
        if ($json['predictedTime'] != '') {
            if ($json['predictedTime'] == 'expertNotAvailable') {
                $havingQry .= " AND expertIds IS NULL ";
            }
        }

        /* $questionQry = "SELECT COUNT(DISTINCT fsq.id) as pendingQuestion,fs.id as subjectId,CASE WHEN fs.favourite_subject IS NULL THEN 'Others' ELSE fs.favourite_subject END as subjectName,COUNT(DISTINCT CASE WHEN (p.isAssessmentApproved = 'Y' AND p.expertStatus = 1 AND p.deleted_at IS null AND p.lastActiveOnAssessment IS NOT NULL) THEN p.id END) as noOfActiveExpert,
        COUNT(DISTINCT CASE WHEN (p.isAssessmentApproved = 'Y' AND p.expertStatus = 1 AND p.deleted_at IS null AND p.lastActiveOnAssessment IS NOT NULL AND TIMESTAMPDIFF(DAY,lastActiveOnAssessment,now()) <= 7) THEN p.id END) as availableActiveExpert,
        COUNT(DISTINCT CASE WHEN (p.expertStatus IN (-1,0,1)) THEN p.id END) as onBoardedExpert,
        COUNT(DISTINCT CASE WHEN (p.expertStatus = 0) THEN p.id END) as unVerifiedExpert,
        GROUP_CONCAT(DISTINCT CASE WHEN (p.isAssessmentApproved = 'Y' AND p.expertStatus = 1 AND p.deleted_at IS null) THEN p.id END) as expertIds 
        FROM feedback_status_question fsq INNER JOIN questions q ON q.id = fsq.questionId LEFT JOIN favourite_subject fs ON fs.id = q.subjectId LEFT JOIN panel p ON FIND_IN_SET(q.subjectId,p.areaOfExpertiseId) WHERE fsq.review_status IN (0,1) ".$filterQry." GROUP BY q.subjectId ".$havingQry." ORDER BY fs.favourite_subject ASC"; */
        $questionQry = "select * from( select temp.pendingQuestion as pendingQuestion,temp.subjectId as subjectId,temp.subjectName as subjectName,temp.noOfActiveExpert as noOfWorkingExpert,temp.unVerifiedExpert as unVerifiedExperts,temp.onBoardedExpert as VerifiedExperts,temp.availableActiveExpert as weeklyActiveExperts,temp.expertIds from 
        (SELECT COUNT(DISTINCT fsq.id) as pendingQuestion, fs.id as subjectId,CASE WHEN fs.favourite_subject IS NULL THEN 'Others' ELSE fs.favourite_subject END as subjectName, COUNT(DISTINCT CASE WHEN (p.isAssessmentApproved = 'Y' AND p.expertStatus = 1 AND p.deleted_at IS null AND p.lastActiveOnAssessment IS NOT NULL) THEN p.id END) as noOfActiveExpert,COUNT(DISTINCT CASE WHEN (p.isAssessmentApproved = 'Y' AND p.expertStatus = 1 AND p.deleted_at IS null AND p.lastActiveOnAssessment IS NOT NULL AND TIMESTAMPDIFF(DAY,lastActiveOnAssessment,now()) <= 15 ) THEN p.id END) as availableActiveExpert,COUNT(DISTINCT CASE WHEN (p.expertStatus IN (-1,0,1)) THEN p.id END) as onBoardedExpert,COUNT(DISTINCT CASE WHEN (p.expertStatus = 0) THEN p.id END) as unVerifiedExpert,GROUP_CONCAT(DISTINCT CASE WHEN (p.isAssessmentApproved = 'Y' AND p.expertStatus = 1 AND p.deleted_at IS null) THEN p.id END) as expertIds FROM feedback_status_question fsq inner JOIN questions q ON q.id = fsq.questionId LEFT JOIN favourite_subject fs ON fs.id = q.subjectId LEFT JOIN panel p ON FIND_IN_SET(q.subjectId,p.areaOfExpertiseId) WHERE fsq.review_status IN (0,1) and q.deleted_at is null " . $filterQry . "GROUP BY q.subjectId HAVING 1 ORDER BY fs.favourite_subject ASC)as temp) as q1 left join (select * from (select temp2.id as subjectid,temp2.favourite_subject as subjectName,concat('Adv: ',temp2.Advques,' Avg: ',temp2.Avgques,' Bas:',temp2.basques) as questions from (select count(distinct q.id)as totalquestion,count(distinct case when (q.questionLevel='Advanced') then q.id end) as Advques,count(distinct case when (q.questionLevel='Average') then q.id end) as Avgques,count(distinct case when (q.questionLevel='Basic') then q.id end) as basques, fs.favourite_subject,fs.id from questions q inner join favourite_subject fs on fs.id=q.subjectId where q.deleted_at is null " . $filterQry . " group by fs.id ORDER by fs.favourite_subject) as temp2) as q2 left join 
        (select temp1.id,temp1.subname,concat('0-3:',temp1.Goodcand0to3,' ,3-6:',temp1.Goodcand3to6,' ,6+:',Goodcandgreater6) as goodcandidates from (Select temp.id,temp.SubjectName as subname,COUNT(Distinct CASE WHEN (temp.AptitudeScore >=7 and temp.experience between 0 and 3) THEN temp.candidateId ELSE NULL END) as Goodcand0to3,COUNT(Distinct CASE WHEN (temp.AptitudeScore >=7 and temp.experience between 3 and 6) THEN temp.candidateId ELSE NULL END) as Goodcand3to6,COUNT(Distinct CASE WHEN (temp.AptitudeScore >=7 and temp.experience>6) THEN temp.candidateId ELSE NULL END) as Goodcandgreater6  from (select er.candidateId , fv.favourite_subject as SubjectName, ROUND(AVG(er.overallRating),1) as AptitudeScore , fv.id,pd.workExperience as experience from expert_review er  inner join feedback_request fr on  fr.id = er.feedback_request_id inner join questions q on q.id = er.questionId inner join users u on u.id = er.candidateId inner join professionaldetails pd on pd.candidateId = u.id inner join favourite_subject fv on fv.id = q.subjectId inner join interview i on i.id = er.interviewId  LEFT OUTER JOIN topic t ON t.id = q.topic_id where  fr.review_status =2 and er.review_type='question' and q.subjectId is not null and er.overAllRating !='videoIssue'" . $filterQry . " group by er.candidateId,fv.favourite_subject order by er.candidateId DESC) as temp group by temp.SubjectName)as temp1) as q3 on q3.id=q2.subjectid) as q2 on q1.subjectId=q2.subjectId
        
        union 

        select 0 as pendingQuestion,temp2.id as subjectId,temp2.favourite_subject as subjectName,0 as noOfWorkingExpert,temp2.unVerifiedExpert as unVerifiedExpert,temp2.onBoardedExpert as VerifiedExperts,0 as weeklyActiveExperts,temp2.expertIds as expertIds, temp2.id as subjectid,temp2.favourite_subject as subjectName,concat('Adv: ',temp2.Advques,' Avg: ',temp2.Avgques,' Bas:',temp2.basques) as questions,temp2.id as id,temp2.favourite_subject as subname,0 as goodcandidates from 
        (select count(distinct q.id)as totalquestion,count(distinct case when (q.questionLevel='Advanced') then q.id end) as Advques,count(distinct case when (q.questionLevel='Average') then q.id end) as Avgques,count(distinct case when (q.questionLevel='Basic') then q.id end) as basques, fs.favourite_subject,fs.id,COUNT(DISTINCT CASE WHEN (p.expertStatus = 0) THEN p.id END) as unVerifiedExpert, COUNT(DISTINCT CASE WHEN (p.expertStatus IN (-1,0,1)) THEN p.id END) as onBoardedExpert,GROUP_CONCAT(DISTINCT CASE WHEN (p.isAssessmentApproved = 'Y' AND p.expertStatus = 1 AND p.deleted_at IS null) THEN p.id END) as expertIds from questions q inner join favourite_subject fs on fs.id=q.subjectId inner join scps_transaction scps on scps.subject=q.subjectId LEFT JOIN panel p ON FIND_IN_SET(q.subjectId,p.areaOfExpertiseId) where q.deleted_at is null and q.subjectId not in (select subjectId from questions where id in(select questionId from feedback_status_question)) " . $filterQry . " group by fs.id ORDER by fs.favourite_subject) as temp2;";

        $questionResult = mysqli_query($databaseConnection, $questionQry);
        if (mysqli_num_rows($questionResult) > 0) {
             // while($row = mysqli_fetch_array($questionResult)) {
            //     if ($row['expertIds'] != null) {
            //         $currentCompletionRateQry = "SELECT SUM(t.noOfQuestions),COUNT(t.noOfQuestions),(SUM(t.noOfQuestions)/COUNT(t.noOfQuestions)),ROUND(AVG(t.noOfQuestions)) as currentCompletionRate FROM (SELECT COUNT(DISTINCT id) as noOfQuestions,createdAt,feedbackGivenBy FROM `expert_review` WHERE feedbackGivenBy IN (".$row['expertIds'].") AND review_type = 'question' GROUP BY feedbackGivenBy,year(createdAt),month(createdAt),day(createdAt) ORDER BY `feedbackGivenBy` ASC) as t;";
            //         $currentCompletionRateResult = mysqli_query($databaseConnection,$currentCompletionRateQry);
            //         if (mysqli_num_rows($currentCompletionRateResult)>0) {
            //             $currentCompletionRateValue = mysqli_fetch_all($currentCompletionRateResult,MYSQLI_ASSOC);
            //             $row['currentCompletionRate'] = $currentCompletionRateValue[0]['currentCompletionRate'];
            //         }
            //         $avgFeedbackQry = "Select SEC_TO_TIME(round(sum(temp.avgfeedback)/50)) as avgfeedback,case when temp.avgPickup is not null then SEC_TO_TIME(round(sum(temp.avgPickup)/50)) else 0 end as avgPickup,temp.favourite_subject from (select TIMESTAMPDIFF(SECOND,t.requestdate,min(er.createdAt)) as avgfeedback,TIMESTAMPDIFF(SECOND,er.createdAt,max(fsq.createdAt)) as avgPickup,fv.favourite_subject from (select fr.id,fr.review_status,fr.requestDate from feedback_request fr where fr.review_status=2 order by id desc limit 50) as t inner join expert_review er on er.feedback_request_id=t.id inner join questions q on er.questionId=q.id inner join feedback_status_question fsq on fsq.questionId = q.id inner join favourite_subject fv on fv.id =q.subjectId where er.review_type='question' and q.subjectId = ".$row['subjectId']." and er.overAllRating !='videoIssue' group by fv.id,t.id) as temp group by temp.favourite_subject;";
            //         $avgFeedbackQryResult = mysqli_query($databaseConnection,$avgFeedbackQry);
            //         if (mysqli_num_rows($avgFeedbackQryResult)>0) {
            //             $avgFeedbackQryValue = mysqli_fetch_all($avgFeedbackQryResult,MYSQLI_ASSOC);
            //             $row['avgfeedback'] = $avgFeedbackQryValue[0]['avgfeedback'];
            //         }else{
            //             $row['avgfeedback'] = 0;
            //         }
            //         $avgPickupQry = "Select case when temp.avgPickup is not null then SEC_TO_TIME(round(sum(temp.avgPickup)/50)) else 0 end as avgPickup,temp.favourite_subject from (select TIMESTAMPDIFF(SECOND,er.createdAt,max(fsq.createdAt)) as avgPickup,fv.favourite_subject from (select fr.id,fr.review_status,fr.requestDate from feedback_request fr where fr.review_status=2 order by id desc limit 50) as t inner join expert_review er on er.feedback_request_id=t.id inner join feedback_status_question fsq on fsq.feedbackRequestId = er.feedback_request_id inner join questions q on er.questionId=q.id inner join favourite_subject fv on fv.id =q.subjectId where er.review_type='question' and q.subjectId = ".$row['subjectId']." and er.overAllRating !='videoIssue' group by fv.id,t.id) as temp group by temp.favourite_subject;";
            //         $avgPickupQryResult = mysqli_query($databaseConnection,$avgPickupQry);
            //         if (mysqli_num_rows($avgPickupQryResult)>0) {
            //             $avgPickupQryValue = mysqli_fetch_all($avgPickupQryResult,MYSQLI_ASSOC);
            //             $row['avgPickup'] = $avgPickupQryValue[0]['avgPickup'];
            //         }else{
            //             $row['avgPickup'] = 0;
            //         }
            //         $currentInputRateQry = "SELECT ROUND(AVG(t.total)) as currentInputRate FROM (SELECT COUNT(fsq.id) as total FROM feedback_status_question fsq INNER JOIN questions q ON fsq.questionId = q.id INNER JOIN feedback_request fr ON fr.id = fsq.feedbackRequestId INNER JOIN mergedVideos mv ON mv.interviewSessionId = fr.interviewSessionId AND fsq.questionId = mv.questionId WHERE q.subjectId = ".$row['subjectId']." GROUP BY q.subjectId,year(mv.created),month(mv.created),day(mv.created)) as t;";
            //         $currentInputRateResult = mysqli_query($databaseConnection,$currentInputRateQry);
            //         if (mysqli_num_rows($currentInputRateResult)>0) {
            //             $currentInputRateValue = mysqli_fetch_all($currentInputRateResult,MYSQLI_ASSOC);
            //             $row['currentInputRate'] = $currentInputRateValue[0]['currentInputRate'];
            //         }
            //         $effectiveRate = $row['currentCompletionRate'] - $row['currentInputRate'];
            //         if($effectiveRate == 0) {$effectiveRate = 1;}
            //          $row['expectedTime'] =  round(($row['pendingQuestion']/($effectiveRate)));
            //         if($json['predictedTime'] != '') {
            //             if ($json['predictedTime'] == '<0' && $row['expectedTime'] < 0) {
            //                 array_push($finalArray,$row);
            //             }
            //             elseif ($json['predictedTime'] == '=0' && $row['expectedTime'] == 0) {
            //                 array_push($finalArray,$row);
            //             }
            //             elseif ($json['predictedTime'] == '>0' && $row['expectedTime'] > 0) {
            //                 array_push($finalArray,$row);
            //             }
            //         }
            //         else {
            //             array_push($finalArray,$row);
            //         } 

            //     } else {
            //         $row['currentInputRate'] = 0;
            //         $row['currentCompletionRate'] = 0;
            //         $row['avgfeedback'] = 0;
            //         $row['avgPickup'] = 0;
            //         $row['expectedTime'] = 'Expert not Available';
            //         if($json['predictedTime'] != '') {
            //             if ($json['predictedTime'] == 'expertNotAvailable') {
            //                 array_push($finalArray,$row);
            //             }
            //         } 
            //         else {
            //             array_push($finalArray,$row);
            //         }
            //     }
            // }
            $questionValue = mysqli_fetch_all($questionResult, MYSQLI_ASSOC);
            $to_encode = array(
                'data' => $questionValue,
                'qry' => $questionQry,
                'status' => 1
            );
        } else {
            $to_encode = array(
                'data' => 'none',
                'qry' => $questionQry,
                'status' => -1
            );
        }
    } else {
        $to_encode = array(
            'data' => 'unable to decode JSON',
            'status' => -1
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['getexpertCalculationFilters'])) {

    $values = array();
    $questionValue = '';
    $questionQry = "SELECT id,favourite_subject FROM `favourite_subject` ORDER BY favourite_subject ASC";
    $questionResult = mysqli_query($databaseConnection, $questionQry);
    if (mysqli_num_rows($questionResult) > 0) {
        $questionValue = mysqli_fetch_all($questionResult, MYSQLI_ASSOC);
    }
    $values['favourite_subject'] = $questionValue;

    $data1 = "Select case when pr.interviewName is null then ac.name else pr.interviewName End as name,pr.id as preInterviewId from preInterview pr inner join aspiration_company ac on ac.id=pr.company_id where pr.productId!=6 and pr.interviewStatus in('Active') group by pr.id ORDER BY pr.id DESC";
    $query1 = mysqli_query($databaseConnection, $data1);
    $values1 = mysqli_fetch_all($query1, MYSQLI_ASSOC);
    $values['interview_name'] = $values1;


    $to_encode = array(
        'data' => $values,
        'status' => 1
    );
    echo json_encode($to_encode);
}
else if (isset($_GET['getCorporateLoginFilters'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $companyId = $json['companyId'];

        $values = array();

        // $filter1 = "SELECT id,collegeName FROM colleges ORDER BY collegeName ASC;";
        // $filter1Result = mysqli_query($databaseConnection,$filter1);

        // $filter2 = "SELECT pd.year FROM professionaldetails pd WHERE pd.year NOT IN (0) GROUP BY pd.year ORDER BY pd.year ASC;";
        // $filter2Result = mysqli_query($databaseConnection,$filter2);

        $filter3 = "SELECT id,stream FROM stream;";
        $filter3Result = mysqli_query($databaseConnection, $filter3);

        $filter4 = "SELECT fs.favourite_subject as subjectName,fs.id  FROM favourite_subject fs LEFT JOIN fav_prog_skill fps ON fps.fav_prog_skill LIKE CONCAT('%',fs.favourite_subject,'%') LEFT OUTER JOIN questions q ON q.subjectId = fs.id  WHERE fps.id IS null AND fs.id NOT IN (178) GROUP BY fs.favourite_subject ORDER BY fs.favourite_subject ASC;";
        $filter4Result = mysqli_query($databaseConnection, $filter4);

        // $filter5 = "SELECT fs.favourite_subject as subjectName,fs.id  FROM favourite_subject fs LEFT JOIN fav_prog_skill fps ON fps.fav_prog_skill LIKE CONCAT('%',fs.favourite_subject,'%') LEFT OUTER JOIN questions q ON q.subjectId = fs.id  WHERE fps.id IS null AND fs.id IN (178) GROUP BY fs.favourite_subject ORDER BY fs.favourite_subject ASC;";
        // $filter5Result = mysqli_query($databaseConnection,$filter5);


        $filter6 = "SELECT fs.favourite_subject as subjectName,fs.id  FROM favourite_subject fs LEFT JOIN fav_prog_skill fps ON fps.fav_prog_skill LIKE CONCAT('%',fs.favourite_subject,'%') LEFT OUTER JOIN questions q ON q.subjectId = fs.id  WHERE fps.id IS NOT null GROUP BY fs.favourite_subject ORDER BY fs.favourite_subject ASC;";
        $filter6Result = mysqli_query($databaseConnection, $filter6);

        // $filter7 = "SELECT DISTINCT empstatus from candidateEmp_status;";
        // $filter7Result = mysqli_query($databaseConnection,$filter7);

        $filter8 = "SELECT id,cityName FROM locations ORDER BY cityName ASC;";
        $filter8Result = mysqli_query($databaseConnection, $filter8);

        $filter10 = " select r.id,r.name from relavant_role r inner join scps_transaction scp on scp.position=r.id inner join preInterview cd on cd.company_id=scp.company where cd.userId='" . $json['companyId'] . "' group by r.id;";
        $filter10Result = mysqli_query($databaseConnection, $filter10);

        // $filter9 = "select ac.name,ac.id from aspiration_company ac inner join scps_transaction scps on scps.company=ac.id group by scps.company";
        if ($json['userType'] == 'corporate') {
            // $filter9 = "Select distinct(st.company) as company,case when pr.interviewName is null then ac.name else pr.interviewName End as name,st.preInterviewId as id from scps_transaction st inner join aspiration_company ac on ac.id=st.company inner join preInterview pr on pr.id=st.preInterviewId where st.company!=0 and pr.id IN (SELECT preinterviewId FROM preInterview_corporate WHERE userId='" . $json['companyId'] . "') ORDER BY pr.id DESC";
            $filter9 = "SELECT pr.id, COALESCE(pr.interviewName, ac.name) AS name FROM preInterview pr LEFT JOIN aspiration_company ac ON ac.id = pr.id WHERE pr.id != 0 AND (pr.interviewName IS NOT NULL OR ac.name IS NOT NULL)and pr.id IN (SELECT preinterviewId FROM preInterview_corporate WHERE userId='" . $json['companyId'] . "') ORDER BY pr.id DESC";
        } else {
            // $filter9 = "Select distinct(st.company) as company,case when pr.interviewName is null then ac.name else pr.interviewName End as name,st.preInterviewId as id from scps_transaction st inner join aspiration_company ac on ac.id=st.company inner join preInterview pr on pr.id=st.preInterviewId where st.company!=0 ORDER BY pr.id DESC";
            $filter9 = "SELECT pr.id, COALESCE(pr.interviewName, ac.name) AS name FROM preInterview pr LEFT JOIN aspiration_company ac ON ac.id = pr.id WHERE pr.id != 0 AND (pr.interviewName IS NOT NULL OR ac.name IS NOT NULL) ORDER BY pr.id DESC";

        }

        $filter9Result = mysqli_query($databaseConnection, $filter9);
        // if($json['userType']=='corporate'){

        //     $filter11 = "select r.id as roleId,ac.id as companyId,concat(ac.name,'(',r.name,')') as interview,scp.status as status from relavant_role r inner join scps_transaction scp on scp.position=r.id inner join preInterview cd on cd.company_id=scp.company inner join aspiration_company ac on ac.id=cd.company_id where cd.userId='" . $json['companyId'] . "' group by scp.position,scp.company";

        // }else{

        //     $filter11 = "select r.id as roleId,ac.id as companyId,concat(ac.name,'(',r.name,')') as interview,scp.status as status from relavant_role r inner join scps_transaction scp on scp.position=r.id inner join preInterview cd on cd.company_id=scp.company inner join aspiration_company ac on ac.id=cd.company_id group by scp.position,scp.company";
        // }

        if ($json['userType'] == 'corporate') {

            $filter11 = "select r.id as roleId,ac.id as companyId,r.name as interview,scp.status as status,ac.name as HiringCompany from relavant_role r inner join scps_transaction scp on scp.position=r.id inner join preInterview cd on cd.company_id=scp.company inner join aspiration_company ac on ac.id=cd.company_id where cd.userId='" . $json['companyId'] . "' group by scp.position,scp.company";

        } else {

            $filter11 = "select r.id as roleId,ac.id as companyId,r.name as interview,scp.status as status,ac.name as HiringCompany from relavant_role r inner join scps_transaction scp on scp.position=r.id inner join preInterview cd on cd.company_id=scp.company inner join aspiration_company ac on ac.id=cd.company_id group by scp.position,scp.company";
        }
        $filter11Result = mysqli_query($databaseConnection, $filter11);

        $syncPendingFilter = mysqli_query($databaseConnection, "select count(distinct(feedbackRequestId)) as syncPendingCount from feedback_status_question fsq inner join feedback_request fr on fr.id=fsq.feedbackRequestId where fsq.feedbackRequestId not in(select distinct(feedbackRequestId) from feedback_status_question where review_status in(0,1,9)) and fr.review_status in (0,1)");

        $filter12 = "select candidateStatus from candidateStatus where id not in (7,8,9,13)";
        $filter12Result = mysqli_query($databaseConnection, $filter12);

        $filter13 = "select * from candidateEmailTemplate where status in ('Shortlisted candidates','Profile Shared')";
        $filter13Result = mysqli_query($databaseConnection, $filter13);

        // $values['collegeList'] = mysqli_fetch_all($filter1Result,MYSQLI_ASSOC);
        // $values['YOP'] = mysqli_fetch_all($filter2Result,MYSQLI_ASSOC);
        // $values['stream'] = mysqli_fetch_all($filter3Result,MYSQLI_ASSOC);
        $values['cognitiveSubjects'] = mysqli_fetch_all($filter4Result, MYSQLI_ASSOC);
        //$values['behaviouralSubjects'] = mysqli_fetch_all($filter5Result,MYSQLI_ASSOC);
        $values['programmingSubjects'] = mysqli_fetch_all($filter6Result, MYSQLI_ASSOC);
        // $values['employabilitystatus'] = mysqli_fetch_all($filter7Result,MYSQLI_ASSOC);
        $values['locationList'] = mysqli_fetch_all($filter8Result, MYSQLI_ASSOC);
        $values['role'] = mysqli_fetch_all($filter10Result, MYSQLI_ASSOC);
        $values['interviewname'] = mysqli_fetch_all($filter9Result, MYSQLI_ASSOC);
        $values['jobName'] = mysqli_fetch_all($filter11Result, MYSQLI_ASSOC);
        $values['syncPending'] = mysqli_fetch_assoc($syncPendingFilter)['syncPendingCount'];
        $values['candidateStatus'] = mysqli_fetch_all($filter12Result, MYSQLI_ASSOC);
        $values['emailTemplate'] = mysqli_fetch_all($filter13Result, MYSQLI_ASSOC);

        $to_encode = array(
            'data' => $values,
            'status' => 1
        );

    } else {
        $to_encode = array(
            'data' => "err",
            'status' => 0
        );
    }
    echo json_encode($to_encode);
}
else if (isset($_GET['getSuggestedUserList'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        if ($json['name'] != "") {
            $name = $json['name'];

            // $companyId = $json['companyId'];

            // if($json['userType']=='corporate'){

            //     $data="SELECT pr.id, COALESCE(pr.interviewName, ac.name) AS name FROM preInterview pr LEFT JOIN aspiration_company ac ON ac.id = pr.id WHERE pr.interviewName like '%".addslashes($name)."%' and pr.id != 0 AND (pr.interviewName IS NOT NULL OR ac.name IS NOT NULL)and pr.id IN (SELECT preinterviewId FROM preInterview_corporate WHERE userId='" . $json['companyId'] . "') ORDER BY pr.id DESC";
            // }else{

            $data = "SELECT u.id, u.emailId  AS name FROM users u WHERE u.emailId like '%" . addslashes($name) . "%' ORDER BY u.id DESC";
            // }

            $query = mysqli_query($databaseConnection, $data);
            if (mysqli_num_rows($query) >= 1) {
                $values = mysqli_fetch_all($query, MYSQLI_ASSOC);
                $to_encode = $values;
            } else {
                $to_encode = array(
                    'status' => 0,
                    'result' => "no info",
                    'errorCode' => "no job found",
                    'query' => $data
                );
            }

        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "no info",
                'errorCode' => "No Key Press yet",
            );
        }

    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving interview information."
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['getSuggestedJobList'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        if ($json['name'] != "") {
            $name = $json['name'];


            $data = "SELECT pr.id , pr.interviewName  AS name FROM preInterview pr WHERE pr.interviewType='job' and pr.interviewName Is NOT NULL and pr.interviewName like '%" . addslashes($name) . "%' ORDER BY pr.id DESC";


            $query = mysqli_query($databaseConnection, $data);
            if (mysqli_num_rows($query) >= 1) {
                $values = mysqli_fetch_all($query, MYSQLI_ASSOC);
                $to_encode = $values;
            } else {
                $to_encode = array(
                    'status' => 0,
                    'result' => "no info",
                    'errorCode' => "no job found",
                    'query' => $data
                );
            }

        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "no info",
                'errorCode' => "No Key Press yet",
            );
        }

    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving interview information."
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['getscheduleInterviewFilters'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        // $preId=$json['preId'];

        $values = array();
        $filterQuery = '';
        $condition = '';
        $condition2 = '';

        if ($userType == 'corporate') {
            // $filterQuery .= " inner join preInterview pr on pr.company_id=st.company ";
            $condition = " and pr.id IN (SELECT preinterviewId FROM preInterview_corporate WHERE userId=" . $userId . ")";
            $condition2 = " and corporateId in (" . $userId . ")";

        }

        // $filter1 = "Select distinct(st.company) as company,case when pr.interviewName is null then ac.name else pr.interviewName End as interviewName,st.sector as sectorId,st.preInterviewId from scps_transaction st inner join aspiration_company ac on ac.id=st.company inner join preInterview pr on pr.id=st.preInterviewId ".$filterQuery." where st.company!=0 ".$condition." ORDER BY pr.id DESC";
        $filter1 = " Select p.preference, p.fieldname ,p.fieldValue,pr.jobCategory,pr.company_id as company,case when pr.interviewName is null then ac.name else pr.interviewName End as interviewName, pr.sectorId as sectorId,pr.id as preInterviewId ,  GROUP_CONCAT(DISTINCT CASE WHEN p.fieldValue LIKE CONCAT('%', s.id, '%') THEN s.skillName ELSE NULL END
    ) AS mskills from preInterview pr inner join aspiration_company ac on ac.id=pr.company_id left join profilePreferences p on p.preInterviewId = pr.id left join skills s on FIND_IN_SET(s.id,p.fieldValue)  where pr.company_id!=0 " . $condition . " GROUP BY pr.company_id, pr.interviewName, pr.sectorId, pr.id ORDER BY pr.id DESC";

        // removed filter AND (p.fieldName = 'skills' or p.fieldName is null) : For Corporate IntrviewName Population 2. p.fieldname, p.fieldValue, 




        $filter1Result = mysqli_query($databaseConnection, $filter1);



        $values['interviewList'] = mysqli_fetch_all($filter1Result, MYSQLI_ASSOC);

        $filter2 = "SELECT id,cityName FROM locations where id not in (512,518,513,516,514,515,517,519) ORDER BY cityName ASC;";
        $filter2Result = mysqli_query($databaseConnection, $filter2);

        $values['locationList'] = mysqli_fetch_all($filter2Result, MYSQLI_ASSOC);

        $filter3 = "SELECT id,name from language;";
        $filter3Result = mysqli_query($databaseConnection, $filter3);

        $values['language'] = mysqli_fetch_all($filter3Result, MYSQLI_ASSOC);

        $filter4 = "SELECT cityName as label,id as value FROM locations ORDER BY cityName ASC;";
        $filter4Result = mysqli_query($databaseConnection, $filter4);

        $values['locations'] = mysqli_fetch_all($filter4Result, MYSQLI_ASSOC);

        $filter5 = "SELECT * FROM recruiterList where activeStatus='Y' " . $condition2 . " ORDER BY name ASC;";

        $filter5Result = mysqli_query($databaseConnection, $filter5);

        $values['recruiterList'] = mysqli_fetch_all($filter5Result, MYSQLI_ASSOC);

        $filter6 = "SELECT * from subRoles;";
        $filter6Result = mysqli_query($databaseConnection, $filter6);

        $values['subroles'] = mysqli_fetch_all($filter6Result, MYSQLI_ASSOC);


        $filter7 = "SELECT favourite_subject from favourite_subject where active='Y';";
        $filter7Result = mysqli_query($databaseConnection, $filter7);

        $values['skills'] = mysqli_fetch_all($filter7Result, MYSQLI_ASSOC);

        $filter12 = "select candidateStatus from candidateStatus where id not in (8,13)";
        $filter12Result = mysqli_query($databaseConnection, $filter12);

        $values['candidateStatus'] = mysqli_fetch_all($filter12Result, MYSQLI_ASSOC);

        $filter13 = "select * from profilePreferences where fieldName='skills' ; ";
        $filter13Result = mysqli_query($databaseConnection, $filter13);

        $values['profilePreferenceSkills'] = mysqli_fetch_all($filter13Result, MYSQLI_ASSOC);


        $to_encode = array(
            'data' => $values,
            'status' => 1
        );

    } else {
        $to_encode = array(
            'data' => "err",
            'status' => 0
        );
    }
    echo json_encode($to_encode);

} else if (isset($_GET['deleteScpsInterviewStructure'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];

        if ($json['preInterviewId'] != NULL || $json['preInterviewId'] != '') {
            //  $d1="delete from interviewstructure where preInterviewId= '".implode(',',$json['preInterviewId'])."' ;";
            //  $d1Result = mysqli_query($databaseConnection,$d1);

            //  $d2=" delete from scps_transaction  where preInterviewId= '".implode(',',$json['preInterviewId'])."';";
            //  $d2Result = mysqli_query($databaseConnection,$d2);

            $d3 = "UPDATE preInterview SET pendingInterviews = 'Y'  where preInterviewId= '" . implode(',', $json['preInterviewId']) . "' ;";
            $d3Result = mysqli_query($databaseConnection, $d3);
        }

        $to_encode = array(
            'status' => 1,
            'result' => "Success",
            'data' => 'Deleted Successfull'
        );

    } else {
        $to_encode = array(
            'data' => "err",
            'result' => "Failure",
            'status' => -1
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['getinterviewCreationFilters'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $values = array();

        if ($userType == 'corporate') {

            $filter1 = "select ac.* from preInterview pr right join aspiration_company ac on ac.id=pr.company_id right join users u on u.firstName=ac.name where u.id='$userId' group by ac.id;";
            $filter1Result = mysqli_query($databaseConnection, $filter1);
            $values['companyNames'] = mysqli_fetch_all($filter1Result, MYSQLI_ASSOC);
        } else {

            $filter1 = "SELECT * FROM aspiration_company order by id desc";
            $filter1Result = mysqli_query($databaseConnection, $filter1);
            $values['companyNames'] = mysqli_fetch_all($filter1Result, MYSQLI_ASSOC);
        }


        $companyUrlFilter = "select company_id , company_url  from preInterview where company_id is not null and company_url is not null order  by id desc;";
        $companyUrlFilterResult = mysqli_query($databaseConnection, $companyUrlFilter);
        $values['companyUrls'] = mysqli_fetch_all($companyUrlFilterResult, MYSQLI_ASSOC);


        $filter2 = "SELECT * FROM relavant_role WHERE active = 'Y' ORDER BY id DESC";
        $filter2Result = mysqli_query($databaseConnection, $filter2);
        $values['roleNames'] = mysqli_fetch_all($filter2Result, MYSQLI_ASSOC);


        $filter3 = "SELECT
        fs.id,
        fs.favourite_subject as subjectName,
        role.id as roleId
        from favourite_subject fs
        inner join questions q on q.subjectId=fs.id
        LEFT JOIN role_subject map ON map.subjectId = fs.id
        LEFT JOIN relavant_role role ON role.id = map.roleId
        where q.deleted_at is null and fs.id!=178  AND fs.active = 'Y'
        group by fs.id having count(distinct case when q.isFollowUp in ('Y','N')then q.id end)>=5 order by fs.id Desc";

        $filter3Result = mysqli_query($databaseConnection, $filter3);

        $values['subjects'] = mysqli_fetch_all($filter3Result, MYSQLI_ASSOC);


        $filter5 = "select * from interviewSection where id in (3,4,5);";
        $filter5Result = mysqli_query($databaseConnection, $filter5);

        $values['sections'] = mysqli_fetch_all($filter5Result, MYSQLI_ASSOC);

        if ($userType == 'corporate') {

            $filter5 = "select pr.* from preInterview pr right join aspiration_company ac on ac.id=pr.company_id right join users u on u.firstName=ac.name where u.id='$userId' order by pr.id desc;";
            $filter5Result = mysqli_query($databaseConnection, $filter5);

            $values['interviewList'] = mysqli_fetch_all($filter5Result, MYSQLI_ASSOC);


        } else {
            $filter5 = "SELECT * FROM preInterview where interviewType = 'job' and interviewName is not null  ORDER BY id Desc ";
            $filter5Result = mysqli_query($databaseConnection, $filter5);

            $values['interviewList'] = mysqli_fetch_all($filter5Result, MYSQLI_ASSOC);
        }



        // $filter6 = "select * from locations order by id Asc";

        $filter6 = "SELECT * FROM locations ORDER BY 
            CASE 
            WHEN cityName LIKE '%Any%' THEN 0
            WHEN cityName LIKE '%Remote%' THEN 1
            ELSE 2
            END,
            cityName ASC";
        $filter6Result = mysqli_query($databaseConnection, $filter6);

        $values['locations'] = mysqli_fetch_all($filter6Result, MYSQLI_ASSOC);

        $filter7 = "select * from profilePreferences order by id desc";
        $filter7Result = mysqli_query($databaseConnection, $filter7);

        $values['profilepreferences'] = mysqli_fetch_all($filter7Result, MYSQLI_ASSOC);

        $filter8 = "select *, favourite_subject.favourite_subject as name from favourite_subject where active='Y' ";
        // $filter8 = "select id, skillName from skills;";

        $filter8Result = mysqli_query($databaseConnection, $filter8);

        $values['skills'] = mysqli_fetch_all($filter8Result, MYSQLI_ASSOC);



        $competencySubject = "SELECT DISTINCT skill.id, role.id as roleId, skill.favourite_subject AS name, CASE WHEN role.id is null then 'Other' ELSE role.name END as role
            FROM favourite_subject skill
            LEFT JOIN role_subject map ON map.subjectId = skill.id
            LEFT JOIN relavant_role role ON role.id = map.roleId
            WHERE skill.subjectType = 'competency' AND skill.active = 'Y'
            order by skill.id";

        $competencySubjectResult = mysqli_query($databaseConnection, $competencySubject);
        $values['competencySubject'] = mysqli_fetch_all($competencySubjectResult, MYSQLI_ASSOC);

        $filter9 = "select interviewName as name,id from preInterview where interviewType='Practice' and interviewExpireDate > curDate() order by id desc";
        $filter9Result = mysqli_query($databaseConnection, $filter9);
        $values['practiceList'] = mysqli_fetch_all($filter9Result, MYSQLI_ASSOC);

        $to_encode = array(
            'data' => $values,
            'status' => 1
        );

    } else {
        $to_encode = array(
            'data' => "err",
            'status' => 0
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['getPracticeCreationFilters'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $values = array();

        if ($userType == 'corporate') {

            $filter1 = "SELECT col.id, col.collegeName as name
            FROM preInterview pr
            right join colleges col on col.id=pr.college_id
            right join preInterview_corporate cor on cor.preInterviewId=pr.id
            WHERE cor.userId='$userId' group by col.id;";
            $filter1Result = mysqli_query($databaseConnection, $filter1);
            $values['collegeNames'] = mysqli_fetch_all($filter1Result, MYSQLI_ASSOC);
        } else {

            $filter1 = "SELECT id, collegeName as name FROM colleges order by id desc";
            $filter1Result = mysqli_query($databaseConnection, $filter1);
            $values['collegeNames'] = mysqli_fetch_all($filter1Result, MYSQLI_ASSOC);
        }


        // $companyUrlFilter = "select company_id , company_url  from preInterview where company_id is not null and company_url is not null order  by id desc;";
        // $companyUrlFilterResult = mysqli_query($databaseConnection, $companyUrlFilter);
        // $values['companyUrls'] = mysqli_fetch_all($companyUrlFilterResult, MYSQLI_ASSOC);


        $filter2 = "SELECT * FROM relavant_role WHERE active = 'Y' ORDER BY id DESC";
        $filter2Result = mysqli_query($databaseConnection, $filter2);
        $values['roleNames'] = mysqli_fetch_all($filter2Result, MYSQLI_ASSOC);


        $filter3 = "SELECT
        fs.id,
        fs.favourite_subject as subjectName,
        role.id as roleId
        from favourite_subject fs
        inner join questions q on q.subjectId=fs.id
        LEFT JOIN role_subject map ON map.subjectId = fs.id
        LEFT JOIN relavant_role role ON role.id = map.roleId
        where q.deleted_at is null and fs.id!=178  AND fs.active = 'Y'
        group by fs.id,role.id having count(distinct case when q.isFollowUp in ('Y','N')then q.id end)>=5 order by fs.id Desc";

        $filter3Result = mysqli_query($databaseConnection, $filter3);

        $values['subjects'] = mysqli_fetch_all($filter3Result, MYSQLI_ASSOC);


        $filter5 = "select * from interviewSection where id in (3,4,5);";
        $filter5Result = mysqli_query($databaseConnection, $filter5);

        $values['sections'] = mysqli_fetch_all($filter5Result, MYSQLI_ASSOC);



        // if ($userType == 'corporate') {

        //     $filter5 = "select pr.* from preInterview pr right join aspiration_company ac on ac.id=pr.company_id right join users u on u.firstName=ac.name where u.id='$userId' order by pr.id desc;";
        //     $filter5Result = mysqli_query($databaseConnection, $filter5);

        //     $values['interviewList'] = mysqli_fetch_all($filter5Result, MYSQLI_ASSOC);


        // } else {
        //     $filter5 = "SELECT * FROM preInterview where interviewType!='assessment' and interviewName is not null  ORDER BY id Desc ";
        //     $filter5Result = mysqli_query($databaseConnection, $filter5);

        //     $values['interviewList'] = mysqli_fetch_all($filter5Result, MYSQLI_ASSOC);
        // }


        $filter9 = "select interviewName as name,id from preInterview where interviewType='Practice' and interviewExpireDate > curDate() order by id desc";
        $filter9Result = mysqli_query($databaseConnection, $filter9);
        $values['practiceList'] = mysqli_fetch_all($filter9Result, MYSQLI_ASSOC);



        // $filter6 = "select * from locations order by id Asc";

        $filter6 = "SELECT * FROM locations ORDER BY 
            CASE 
            WHEN cityName LIKE '%Any%' THEN 0
            WHEN cityName LIKE '%Remote%' THEN 1
            ELSE 2
            END,
            cityName ASC";
        $filter6Result = mysqli_query($databaseConnection, $filter6);

        $values['locations'] = mysqli_fetch_all($filter6Result, MYSQLI_ASSOC);

        $filter7 = "select * from profilePreferences order by id desc";
        $filter7Result = mysqli_query($databaseConnection, $filter7);

        $values['profilepreferences'] = mysqli_fetch_all($filter7Result, MYSQLI_ASSOC);

        $filter8 = "select *, favourite_subject.favourite_subject as name from favourite_subject where active='Y' ";
        // $filter8 = "select id, skillName from skills;";

        $filter8Result = mysqli_query($databaseConnection, $filter8);

        $values['skills'] = mysqli_fetch_all($filter8Result, MYSQLI_ASSOC);



        $competencySubject = "SELECT DISTINCT skill.id, role.id as roleId, skill.favourite_subject AS name, CASE WHEN role.id is null then 'Other' ELSE role.name END as role
            FROM favourite_subject skill
            LEFT JOIN role_subject map ON map.subjectId = skill.id
            LEFT JOIN relavant_role role ON role.id = map.roleId
            WHERE skill.subjectType = 'competency' AND skill.active = 'Y'
            order by skill.id";

        $competencySubjectResult = mysqli_query($databaseConnection, $competencySubject);
        $values['competencySubject'] = mysqli_fetch_all($competencySubjectResult, MYSQLI_ASSOC);



        $to_encode = array(
            'data' => $values,
            'status' => 1
        );

    } else {
        $to_encode = array(
            'data' => "err",
            'status' => 0
        );
    }
    echo json_encode($to_encode);
}
else if (isset($_GET['getPracticeDetails'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    if (isset($json['preInterviewId']) && !empty($json['preInterviewId'])) {
        $ids = is_array($json['preInterviewId']) ? $json['preInterviewId'] : [$json['preInterviewId']];
        $practiceId = implode(',', array_map('intval', $ids)); 
        $values = array();

        // 🔹 1. Basic practice form data
        $query1 = "SELECT
        p.id,
        p.interviewName AS practiceName,
        p.duration,
        p.college_id,
        c.collegeName AS collegeName,   -- add this
        p.roleId,
        p.subjectId,
        fs.favourite_subject AS subjectName,
        p.practiceType AS practiceType,
        p.description,
        p.logoName,
        p.logoText,
        p.YOE
        FROM preInterview p
        LEFT JOIN colleges c ON c.id = p.college_id
        LEFT JOIN favourite_subject fs ON fs.id = p.subjectId
        WHERE p.id IN ($practiceId) AND p.interviewType='Practice';";

        $result1 = mysqli_query($databaseConnection, $query1);
        if (!$result1) {
            die(json_encode(["data" => "Query1 failed: " . mysqli_error($databaseConnection), "status" => 0]));
        }
        $practice = mysqli_fetch_assoc($result1);

        if ($practice) {
            $practice['logo'] = [
                "name" => $practice['logoName'],
                "text" => $practice['logoText']
            ];
            unset($practice['logoName'], $practice['logoText']); // remove raw fields
        }

        if (!isset($practice['YOE'])) {
            $practice['YOE'] = null;
        }
        $values['practiceForm'] = $practice;

        // 🔹 2. Profile Preferences
        $query2 = "SELECT * FROM profilePreferences WHERE preInterviewId IN ($practiceId)";
        $result2 = mysqli_query($databaseConnection, $query2);
        if (!$result2) {
            die(json_encode(["data" => "Query2 failed: " . mysqli_error($databaseConnection), "status" => 0]));
        }
        $values['preference'] = mysqli_fetch_all($result2, MYSQLI_ASSOC);

        // 🔹 3. Competencies with available + selected topics
        $query3 = "
        SELECT 
            s.subject AS subjectId,
            fs.favourite_subject AS subjectName,
            s.topics AS selectedTopicIds,
            GROUP_CONCAT(DISTINCT t.id) AS allTopicIds,
            GROUP_CONCAT(DISTINCT t.name) AS allTopicNames,
            p.interviewLevel AS difficulty
        FROM scps_transaction s
        JOIN preInterview p 
            ON p.id = s.preInterviewId
        LEFT JOIN favourite_subject fs 
            ON fs.id = s.subject
        LEFT JOIN questions q 
            ON q.subjectId = s.subject
        LEFT JOIN topic t 
            ON FIND_IN_SET(t.id, q.topic_Id)
        WHERE s.preInterviewId = '$practiceId'
        GROUP BY s.subject;
        ";

        $result3 = mysqli_query($databaseConnection, $query3);
        if (!$result3) {
            die(json_encode(["data" => "Query3 failed: " . mysqli_error($databaseConnection), "status" => 0]));
        }

        $competencies = mysqli_fetch_all($result3, MYSQLI_ASSOC);

        // 🔹 Convert comma-separated lists into arrays
        foreach ($competencies as &$c) {
            $c['topicId'] = !empty($c['allTopicIds']) ? explode(',', $c['allTopicIds']) : [];
            $c['topicName'] = !empty($c['allTopicNames']) ? explode(',', $c['allTopicNames']) : [];
            $c['selectedTopicIds'] = !empty($c['selectedTopicIds']) ? explode(',', $c['selectedTopicIds']) : [];
            unset($c['allTopicIds'], $c['allTopicNames']);
        }
        $values['competencies'] = $competencies;

        // 🔹 4. Languages
        $query4 = "SELECT * FROM language ORDER BY id ASC";
        $result4 = mysqli_query($databaseConnection, $query4);
        if (!$result4) {
            die(json_encode(["data" => "Query4 failed: " . mysqli_error($databaseConnection), "status" => 0]));
        }
        $values['language'] = mysqli_fetch_all($result4, MYSQLI_ASSOC);

        // 🔹 5. Skills
        $query5 = "SELECT * FROM skills ORDER BY id ASC";
        $result5 = mysqli_query($databaseConnection, $query5);
        if (!$result5) {
            die(json_encode(["data" => "Query5 failed: " . mysqli_error($databaseConnection), "status" => 0]));
        }
        $values['skills'] = mysqli_fetch_all($result5, MYSQLI_ASSOC);

        $to_encode = array(
            "data" => $values,
            "status" => 1
        );

    } else {
        $to_encode = array(
            "data" => "err",
            "status" => 0
        );
    }

    echo json_encode($to_encode);
}
else if (isset($_GET['getAssociatedCorporate'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $values = array();

        $filter1 = "select u.id,u.firstName from users u where u.userType='corporate' order by u.id desc";

        $filter1Result = mysqli_query($databaseConnection, $filter1);

        $values['corporateList'] = mysqli_fetch_all($filter1Result, MYSQLI_ASSOC);

        $filter2 = "select userId as id from preInterview_corporate where preInterviewId='" . implode(',', $json['preInterviewId']) . "'";

        $filter2Result = mysqli_query($databaseConnection, $filter2);

        $values['associatedCorporate'] = mysqli_fetch_all($filter2Result, MYSQLI_ASSOC);


        $to_encode = array(
            'data' => $values,
            'status' => 1
        );

    } else {
        $to_encode = array(
            'data' => "err",
            'status' => 0
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['getInterviewTopics'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $values = array();

        $filter1 = "select tt.id as topicId,tt.name as topicName,q.subjectId from questions q inner join topic tt on tt.id=q.topic_Id where q.subjectId in (" . $json['subjectId'] . ") group by tt.id order by q.subjectId";

        $filter1Result = mysqli_query($databaseConnection, $filter1);
        $values['topicList'] = mysqli_fetch_all($filter1Result, MYSQLI_ASSOC);


        $to_encode = array(
            'data' => $values,
            'status' => 1
        );

    } else {
        $to_encode = array(
            'data' => "err",
            'status' => 0
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['getInterviewTopicsPractice'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $values = array();

        // Ensure subjectId is an array and sanitize it
        if (isset($json['subjectId']) && is_array($json['subjectId'])) {
            $subjectIds = array_map('intval', $json['subjectId']); // Convert values to integers for safety
            $subjectIdList = implode(',', $subjectIds); // Create comma-separated list
        } else {
            $subjectIdList = ''; // Handle empty or invalid subjectId
        }

        if (!empty($subjectIdList)) {
            $filter1 = "SELECT 
                            tt.id AS topicId,
                            tt.name AS topicName,
                            q.subjectId 
                        FROM questions q 
                        INNER JOIN topic tt ON tt.id = q.topic_Id 
                        WHERE q.subjectId IN ($subjectIdList) 
                        GROUP BY tt.id 
                        ORDER BY q.subjectId";

            $filter1Result = mysqli_query($databaseConnection, $filter1);
            $values['topicList'] = mysqli_fetch_all($filter1Result, MYSQLI_ASSOC);

            $to_encode = array(
                'data' => $values,
                'status' => 1
            );
        } else {
            $to_encode = array(
                'data' => "Invalid or empty subjectId",
                'status' => 0
            );
        }
    } else {
        $to_encode = array(
            'data' => "Error decoding JSON",
            'status' => 0
        );
    }

    echo json_encode($to_encode);
} else if (isset($_GET['getAttempdetails'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $values = array();

        $filter1 = "select count(distinct(fr.id)) as attempted from feedback_request fr inner join interview i on i.id=fr.interviewId where i.preInterviewId='" . implode(',', $json['preInterviewId']) . "';";

        $filter1Result = mysqli_query($databaseConnection, $filter1);

        $values['attemptedDetails'] = mysqli_fetch_assoc($filter1Result)['attempted'];


        $filter2 = "select * from preInterview where id='" . implode(',', $json['preInterviewId']) . "';";

        $filter2Result = mysqli_query($databaseConnection, $filter2);

        $values['jobForm'] = mysqli_fetch_all($filter2Result, MYSQLI_ASSOC);

        $filter3 = "select * from profilePreferences where preInterviewId='" . implode(',', $json['preInterviewId']) . "';";

        $filter3Result = mysqli_query($databaseConnection, $filter3);

        $values['preference'] = mysqli_fetch_all($filter3Result, MYSQLI_ASSOC);

        $filter4 = "select * from language order by id Asc";

        $filter4Result = mysqli_query($databaseConnection, $filter4);

        $values['language'] = mysqli_fetch_all($filter4Result, MYSQLI_ASSOC);


        $filter5 = "select * from skills order by id Asc";

        $filter5Result = mysqli_query($databaseConnection, $filter5);

        $values['skills'] = mysqli_fetch_all($filter5Result, MYSQLI_ASSOC);


        // $filter6 = "select * from locations order by id Asc";
        $filter6 = "SELECT * FROM locations ORDER BY 
        CASE 
        WHEN cityName LIKE '%Any%' THEN 0
        WHEN cityName LIKE '%Remote%' THEN 1
        ELSE 2
        END,
        cityName ASC";

        $filter6Result = mysqli_query($databaseConnection, $filter6);

        $values['locations'] = mysqli_fetch_all($filter6Result, MYSQLI_ASSOC);


        $to_encode = array(
            'data' => $values,
            'status' => 1
        );

    } else {
        $to_encode = array(
            'data' => "err",
            'status' => 0
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['editInterviewDetails'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $values = array();


        $filter2 = "SELECT section, GROUP_CONCAT(distinct(subject)) AS subjects,clusterLevel,position,GROUP_CONCAT(distinct(topics)) AS topics,weightage FROM (SELECT scps.subject,isc.sectionId,CASE WHEN scps.dropdown = 1 AND scps.subjectType = 'technical' THEN '3' WHEN scps.dropdown = 2 AND scps.subjectType = 'technical' THEN '4' WHEN scps.dropdown = 1 AND scps.subjectType = 'coding' THEN '5' END AS section,case when isc.clusterLevel='Basic,Average,Advanced' then 'Basic' when isc.clusterLevel in('Average,Basic,Advanced','Average,Advanced,Basic') then 'Average' when isc.clusterLevel='Advanced,Average,Basic' then 'Advanced' end as clusterLevel,scps.position,scps.topics,scps.weightage
      FROM scps_transaction scps inner join interviewStructure isc ON isc.preInterviewId = scps.preInterviewId WHERE scps.preInterviewId = '" . implode(',', $json['preInterviewId']) . "') AS subquery
    GROUP BY section";

        $filter2Result = mysqli_query($databaseConnection, $filter2);

        $values['interviewStructure'] = mysqli_fetch_all($filter2Result, MYSQLI_ASSOC);

        $filter3 = "select sectionId as section, 178 as subjects, case when clusterLevel='Basic,Average,Advanced' then 'Basic' when clusterLevel in('Average,Basic,Advanced','Average,Advanced,Basic') then 'Average' when clusterLevel='Advanced,Average,Basic' then 'Advanced' end as clusterLevel, 6 as weightage from interviewStructure where preInterviewId= '" . implode(',', $json['preInterviewId']) . "' and sectionId=1";

        $filter3Result = mysqli_query($databaseConnection, $filter3);

        $values['interviewBehavioral'] = mysqli_fetch_all($filter3Result, MYSQLI_ASSOC);

        $filter4 = "select * from scps_transaction where preInterviewId= '" . implode(',', $json['preInterviewId']) . "' ;";

        $filter4Result = mysqli_query($databaseConnection, $filter4);

        $values['scps_transaction'] = mysqli_fetch_all($filter4Result, MYSQLI_ASSOC);


        $filter5 = "select count(distinct(fr.id)) as attempted from feedback_request fr inner join interview i on i.id=fr.interviewId where i.preInterviewId='" . implode(',', $json['preInterviewId']) . "';";
        $filter5Result = mysqli_query($databaseConnection, $filter5);
        $values['newAttemptdetails'] = mysqli_fetch_assoc($filter5Result)['attempted'];


        $filter6 = "select * from promotion where preInterviewId = '" . implode(',', $json['preInterviewId']) . "' ;";
        // echo  $filter6 ; 
        $filter6Result = mysqli_query($databaseConnection, $filter6);
        $values['promoteValue'] = mysqli_fetch_all($filter6Result, MYSQLI_ASSOC);

        $to_encode = array(
            'data' => $values,
            'status' => 1
        );

    } else {
        $to_encode = array(
            'data' => "err",
            'status' => 0
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['editInterviewDetails_v2'])) {
    // For Job Creation V2 with limited fields

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $preInterviewId = '';
        if (isset($json['preInterviewId'])) {
            if (is_array($json['preInterviewId'])) {
                $preInterviewId = implode(',', array_map('intval', $json['preInterviewId']));
            } else {
                $preInterviewId = (string) intval($json['preInterviewId']);
            }
        }
        $values = array();

        if ($preInterviewId === '') {
            $to_encode = array(
                'data' => "Invalid preInterviewId",
                'status' => 0
            );
            echo json_encode($to_encode);
            exit();
        }

        $jobFormQuery = "SELECT * FROM preInterview WHERE id = '" . $preInterviewId . "' LIMIT 1";
        $jobFormResult = mysqli_query($databaseConnection, $jobFormQuery);
        $jobForm = mysqli_fetch_assoc($jobFormResult);

        if (!$jobForm) {
            $to_encode = array(
                'data' => "Interview not found",
                'status' => 0
            );
            echo json_encode($to_encode);
            exit();
        }

        $attemptQuery = "SELECT count(distinct(fr.id)) as attempted FROM feedback_request fr inner join interview i on i.id=fr.interviewId where i.preInterviewId='" . $preInterviewId . "'";
        $attemptResult = mysqli_query($databaseConnection, $attemptQuery);
        $attemptDetails = 0;
        if ($attemptResult) {
            $attemptDetails = (int) mysqli_fetch_assoc($attemptResult)['attempted'];
        }

        $preferencesQuery = "SELECT fieldName, fieldValue, preference FROM profilePreferences WHERE preInterviewId = '" . $preInterviewId . "'";
        $preferencesResult = mysqli_query($databaseConnection, $preferencesQuery);
        $workExperience = '';
        $workExperiencePreference = '';
        if ($preferencesResult) {
            while ($pref = mysqli_fetch_assoc($preferencesResult)) {
                if ($pref['fieldName'] == 'workExperience') {
                    $workExperience = $pref['fieldValue'];
                    $workExperiencePreference = $pref['preference'];
                    break;
                }
            }
        }

        $sections = array();
        $structureQuery = "SELECT
            CASE
                WHEN scps.dropdown = 1 AND scps.subjectType = 'technical' THEN '3'
                WHEN scps.dropdown = 2 AND scps.subjectType = 'technical' THEN '4'
                WHEN scps.dropdown = 1 AND scps.subjectType = 'coding' THEN '5'
                ELSE ''
            END AS section,
            scps.subject,
            scps.weightage,
            scps.topics,
            CASE
                WHEN isc.clusterLevel='Basic,Average,Advanced' THEN 'Basic'
                WHEN isc.clusterLevel in ('Average,Basic,Advanced','Average,Advanced,Basic') THEN 'Average'
                WHEN isc.clusterLevel='Advanced,Average,Basic' THEN 'Advanced'
                ELSE 'Basic'
            END AS clusterLevel
            FROM scps_transaction scps
            LEFT JOIN interviewStructure isc ON isc.preInterviewId = scps.preInterviewId AND (
                (scps.dropdown = 1 AND scps.subjectType = 'technical' AND isc.sectionId = 3) OR
                (scps.dropdown = 2 AND scps.subjectType = 'technical' AND isc.sectionId = 4) OR
                (scps.dropdown = 1 AND scps.subjectType = 'coding' AND isc.sectionId = 5)
            )
            WHERE scps.preInterviewId = '" . $preInterviewId . "' AND scps.subjectType in ('technical','coding')
            ORDER BY section ASC, scps.id ASC";
        $structureResult = mysqli_query($databaseConnection, $structureQuery);
        if ($structureResult) {
            while ($row = mysqli_fetch_assoc($structureResult)) {
                $sectionKey = $row['section'];
                if ($sectionKey == '') {
                    continue;
                }
                if (!isset($sections[$sectionKey])) {
                    $topics = array();
                    if (!empty($row['topics'])) {
                        $topics = array_values(array_filter(array_map('trim', explode(',', $row['topics']))));
                    }

                    $sections[$sectionKey] = array(
                        'section' => $sectionKey,
                        'subject' => (string) $row['subject'],
                        'level' => array($row['clusterLevel']),
                        'aSubject' => array('1'),
                        'cutOff' => ($row['weightage'] !== null && $row['weightage'] !== '') ? (string) $row['weightage'] : '0',
                        'topics' => $topics,
                        'speakingSkill' => false
                    );
                }
            }
        }
        ksort($sections);

        $behavioralQuery = "SELECT count(*) as behavioralCount FROM interviewStructure WHERE preInterviewId = '" . $preInterviewId . "' AND sectionId = 1";
        $behavioralResult = mysqli_query($databaseConnection, $behavioralQuery);
        $includeBehavioral = false;
        if ($behavioralResult) {
            $includeBehavioral = ((int) mysqli_fetch_assoc($behavioralResult)['behavioralCount']) > 0;
        }

        $jobScreeningQuestions = array();
        $screeningQuestionsQuery = "SELECT id, preInterviewId, questionText, questionType, optionsJson, sortOrder, isActive, createdAt FROM jobScreeningQuestions WHERE preInterviewId = '" . $preInterviewId . "' AND (isActive IS NULL OR isActive = 'Y') ORDER BY sortOrder ASC, id ASC";
        $screeningQuestionsResult = mysqli_query($databaseConnection, $screeningQuestionsQuery);
        if ($screeningQuestionsResult) {
            $jobScreeningQuestions = mysqli_fetch_all($screeningQuestionsResult, MYSQLI_ASSOC);
        }

        $validationState = 0;
        if (count($sections) > 0) {
            $validationState = 1;
        }
        $advancedValidationQuery = "SELECT count(*) as advancedCount FROM interviewStructure WHERE preInterviewId = '" . $preInterviewId . "' AND sectionId = 8";
        $advancedValidationResult = mysqli_query($databaseConnection, $advancedValidationQuery);
        if ($advancedValidationResult) {
            $advancedCount = (int) mysqli_fetch_assoc($advancedValidationResult)['advancedCount'];
            if ($advancedCount > 0) {
                $validationState = 3;
            }
        }

        $subjectIdList = array();
        if (!empty($jobForm['subjectId'])) {
            $subjectIdList = array_values(array_filter(array_map('trim', explode(',', $jobForm['subjectId']))));
        }

        $companyIdList = array();
        if (!empty($jobForm['company_id'])) {
            $companyIdList = array_values(array_filter(array_map('trim', explode(',', $jobForm['company_id']))));
        }

        $expMin = '';
        $expMax = '';
        if (!empty($workExperience) && strpos($workExperience, '-') !== false) {
            $expParts = explode('-', $workExperience);
            if (count($expParts) == 2) {
                $expMin = trim($expParts[0]);
                $expMax = trim($expParts[1]);
            }
        }

        $values['jobName'] = isset($jobForm['interviewName']) ? $jobForm['interviewName'] : '';
        $values['serviceType'] = isset($jobForm['serviceType']) ? $jobForm['serviceType'] : '';
        $values['recruiterEmail'] = isset($jobForm['RecruiterEmail']) ? $jobForm['RecruiterEmail'] : '';
        $values['companyUrl'] = isset($jobForm['company_url']) ? $jobForm['company_url'] : '';
        $values['roleId'] = isset($jobForm['roleId']) ? $jobForm['roleId'] : '';
        $values['subjectId'] = isset($jobForm['subjectId']) ? $jobForm['subjectId'] : '';
        $values['subjectIdList'] = $subjectIdList;
        $values['companyIdList'] = $companyIdList;
        $values['jobStartDate'] = isset($jobForm['interviewStartDate']) ? $jobForm['interviewStartDate'] : '';
        $values['jobExpireDate'] = isset($jobForm['interviewExpireDate']) ? $jobForm['interviewExpireDate'] : '';
        $values['jobDescription'] = isset($jobForm['JDsection']) ? $jobForm['JDsection'] : '';
        $values['showJDsection'] = isset($jobForm['showJDsection']) ? $jobForm['showJDsection'] : 'Y';
        $values['additionalJobDetails'] = isset($jobForm['additionalJobDetails']) ? $jobForm['additionalJobDetails'] : 'Y';
        $values['JDupload'] = isset($jobForm['JDupload']) ? $jobForm['JDupload'] : '';
        $values['screeningQuestions'] = isset($jobForm['screeningQuestions']) && $jobForm['screeningQuestions'] == 'Y' ? 'Y' : 'N';
        $values['jobScreeningQuestions'] = $jobScreeningQuestions;
        $values['pendingInterviews'] = isset($jobForm['pendingInterviews']) ? $jobForm['pendingInterviews'] : 'Y';
        $values['workExperience'] = $workExperience;
        $values['workExperiencePreference'] = $workExperiencePreference;
        $values['expMin'] = $expMin;
        $values['expMax'] = $expMax;
        $values['validationState'] = $validationState;
        $values['includeBehavioral'] = $includeBehavioral;
        $values['attemptDetails'] = $attemptDetails;
        $values['interviewSections'] = array_values($sections);

        $to_encode = array(
            'data' => $values,
            'status' => 1
        );

    } else {
        $to_encode = array(
            'data' => "err",
            'status' => 0
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['editAssignPractice'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $values = array();

        $filter1 = "select * from candidateInterviewMapping where id = '" . $json['cimId'] . "';";
        $filter1Result = mysqli_query($databaseConnection, $filter1);
        $values['assignValues'] = mysqli_fetch_all($filter1Result, MYSQLI_ASSOC);

        $to_encode = array(
            'data' => $values,
            'status' => 1
        );

    } else {
        $to_encode = array(
            'data' => "err",
            'status' => 0
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['deletePreInterview'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        // $values = array();

        if ($userId && $userType != 'student') {
            $delete = "DELETE FROM promotion WHERE preInterviewId = '" . implode("','", $json['preInterviewId']) . "';";
            $deleteResult = mysqli_query($databaseConnection, $delete);

            if ($deleteResult) {
                // echo "Promotion Deletion successful";
            } else {
                echo "Error: " . mysqli_error($databaseConnection);
            }

            $delete2 = "DELETE FROM interviewStructure WHERE preInterviewId = '" . implode("','", $json['preInterviewId']) . "';";
            $delete2Result = mysqli_query($databaseConnection, $delete2);

            if ($delete2Result) {
                // echo "interviewStructure Deletion successful";
            } else {
                echo "Error: " . mysqli_error($databaseConnection);
            }

            $delete3 = "DELETE FROM scps_transaction WHERE preInterviewId = '" . implode("','", $json['preInterviewId']) . "';";
            $delete3Result = mysqli_query($databaseConnection, $delete3);

            if ($delete3Result) {
                // echo "scps Deletion successful";
            } else {
                echo "Error: " . mysqli_error($databaseConnection);
            }

            $delete4 = "DELETE FROM preInterview WHERE id = '" . implode("','", $json['preInterviewId']) . "';";
            $delete4Result = mysqli_query($databaseConnection, $delete4);

            if ($delete4Result) {
                // echo "preInterview Deletion successful";
            } else {
                echo "Error: " . mysqli_error($databaseConnection);
            }

            $to_encode = array(
                // 'data'=> $values,
                'status' => 1
            );

        } else {
            $to_encode = array(
                'data' => "err",
                'status' => 0
            );
        }
    } else {
        $to_encode = array(
            'data' => "err",
            'status' => 0
        );
    }
    echo json_encode($to_encode);
}
else if (isset($_GET['getPracticeAssociated'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $values = array();

        $filter1 = "select u.id,u.firstName,emailId from users u where u.userType='college' order by u.id desc";

        $filter1Result = mysqli_query($databaseConnection, $filter1);

        $values['corporateList'] = mysqli_fetch_all($filter1Result, MYSQLI_ASSOC);

        $filter2 = "select userId as id from preInterview_corporate where preInterviewId='" . $json['preInterviewId'] . "'";

        $filter2Result = mysqli_query($databaseConnection, $filter2);

        $values['associatedCorporate'] = mysqli_fetch_all($filter2Result, MYSQLI_ASSOC);


        $to_encode = array(
            'data' => $values,
            'status' => 1
        );

    } else {
        $to_encode = array(
            'data' => "err",
            'status' => 0
        );
    }
    echo json_encode($to_encode);
}
else if (isset($_GET['getPracticeAssociated2'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $values = array();

        $filter1 = "select u.id,u.firstName,emailId from users u where u.userType='corporate' order by u.id desc";

        $filter1Result = mysqli_query($databaseConnection, $filter1);

        $values['corporateList'] = mysqli_fetch_all($filter1Result, MYSQLI_ASSOC);

        $filter2 = "select userId as id from preInterview_corporate where preInterviewId='" . $json['preInterviewId'] . "'";

        $filter2Result = mysqli_query($databaseConnection, $filter2);

        $values['associatedCorporate'] = mysqli_fetch_all($filter2Result, MYSQLI_ASSOC);


        $to_encode = array(
            'data' => $values,
            'status' => 1
        );

    } else {
        $to_encode = array(
            'data' => "err",
            'status' => 0
        );
    }
    echo json_encode($to_encode);
}
else if (isset($_GET['associatingCorporateId'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $preInterviewId = $json['preInterviewId'];
        $corporateIds = array();
        $insert = 0;
        if ($json['corporateUserId'] != '') {
            $corporateIds = preg_split("/\,/", implode(",", $json['corporateUserId']));
        }

        $checkingQry = mysqli_query($databaseConnection, "select * from preInterview_corporate where preInterviewId='" . $preInterviewId . "'");

        if (mysqli_num_rows($checkingQry) > 0) {

            $deleteQry = mysqli_query($databaseConnection, "delete from preInterview_corporate where preInterviewId='" . $preInterviewId . "'");

        }


        for ($i = 0; $i < sizeOf($corporateIds); $i++) {

            $insertCorporate = mysqli_query($databaseConnection, "INSERT INTO preInterview_corporate(preInterviewId,userId,userType) VALUES ('" . $preInterviewId . "','" . $corporateIds[$i] . "','corporate')");

            if ($insertCorporate) {

                $insert += 1;
            }

        }
        if (sizeof($corporateIds) == $insert) {
            $to_encode = array(
                'data' => "Success",
                'status' => 1
            );
        } else {
            $to_encode = array(
                'data' => "error",
                'status' => -1
            );
        }



    } else {
        $to_encode = array(
            'data' => "err",
            'status' => 0
        );
    }
    echo json_encode($to_encode);
}
else if (isset($_GET['associatingCollegeId'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $preInterviewId = $json['preInterviewId'];
        $collegeIds = array();
        $insert = 0;
        if ($json['collegeUserId'] != '') {
            $collegeIds = preg_split("/\,/", implode(",", $json['collegeUserId']));
        }

        $checkingQry = mysqli_query($databaseConnection, "select * from preInterview_corporate where preInterviewId='" . $preInterviewId . "'");

        if (mysqli_num_rows($checkingQry) > 0) {

            $deleteQry = mysqli_query($databaseConnection, "delete from preInterview_corporate where preInterviewId='" . $preInterviewId . "'");

        }


        for ($i = 0; $i < sizeOf($collegeIds); $i++) {

            $insertCorporate = mysqli_query($databaseConnection, "INSERT INTO preInterview_corporate(preInterviewId,userId,userType) VALUES ('" . $preInterviewId . "','" . $collegeIds[$i] . "','college')");

            if ($insertCorporate) {

                $insert += 1;
            }

        }
        if (sizeof($collegeIds) == $insert) {
            $to_encode = array(
                'data' => "Success",
                'status' => 1
            );
        } else {
            $to_encode = array(
                'data' => "error",
                'status' => -1
            );
        }



    } else {
        $to_encode = array(
            'data' => "err",
            'status' => 0
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['getEventReportFilters'])) {

    $values = array();
    $filter1 = "SELECT id,collegeName FROM colleges ORDER BY collegeName ASC;";
    $filter1Result = mysqli_query($databaseConnection, $filter1);

    $filter2 = "SELECT pd.year FROM professionaldetails pd WHERE pd.year NOT IN (0) GROUP BY pd.year ORDER BY pd.year ASC;";
    $filter2Result = mysqli_query($databaseConnection, $filter2);

    $filter3 = "SELECT id,stream FROM stream;;";
    $filter3Result = mysqli_query($databaseConnection, $filter3);

    $filter4 = "SELECT id,name FROM aspiration_company order by id desc;";
    $filter4Result = mysqli_query($databaseConnection, $filter4);

    // $filter5 = "select distinct serviceType from preInterview where serviceType !='IAS' order by serviceType desc;";
    $filter5 = "select distinct serviceType from preInterview  order by serviceType desc;";
    $filter5Result = mysqli_query($databaseConnection, $filter5);

    $values['collegeList'] = mysqli_fetch_all($filter1Result, MYSQLI_ASSOC);
    $values['YOP'] = mysqli_fetch_all($filter2Result, MYSQLI_ASSOC);
    $values['stream'] = mysqli_fetch_all($filter3Result, MYSQLI_ASSOC);
    $values['hiringcompany'] = mysqli_fetch_all($filter4Result, MYSQLI_ASSOC);
    $values['servicetype'] = mysqli_fetch_all($filter5Result, MYSQLI_ASSOC);

    $to_encode = array(
        'data' => $values,
        'status' => 1
    );
    echo json_encode($to_encode);
} else if (isset($_GET['configureJobForm'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {

        $profilePreference = $json['profilePreference'];


        for ($i = 0; $i < sizeof($profilePreference); $i++) {
            $checkingQuery = mysqli_query($databaseConnection, "select * from profilePreferences where preInterviewId=" . implode(',', $json['preInterviewId']) . " and fieldName='" . $profilePreference[$i]['fieldName'] . "'");

            if (mysqli_num_rows($checkingQuery) > 0) {
                $id = mysqli_fetch_assoc($checkingQuery)['id'];
                $updateQuery = mysqli_query($databaseConnection, "update profilePreferences set fieldValue='" . $profilePreference[$i]['fieldValue'] . "', preference='" . $profilePreference[$i]['preference'] . "' where id=" . $id . " and preInterviewId=" . implode(',', $json['preInterviewId']));
            } else {
                $insertQuery = mysqli_query($databaseConnection, "insert into profilePreferences(preInterviewId, fieldName, fieldValue, preference) values (" . implode(',', $json['preInterviewId']) . ",'" . $profilePreference[$i]['fieldName'] . "','" . $profilePreference[$i]['fieldValue'] . "','" . $profilePreference[$i]['preference'] . "')");
            }
        }

        // $updatePreInterview="UPDATE preInterview SET jobType='".$json['jobType']."',currentCompany='".$json['currentCompany']."',currentProcess='".$json['currentProcess']."',processType='".$json['processType']."',clientType='".$json['clientType']."',workExperience='".$json['workExperience']."',currentSalary='".$json['currentSalary']."',expectedSalary='".$json['expectedSalary']."',noticePeriod='".$json['noticePeriod']."',processPreference='".$json['processPreference']."',shift='".$json['shift']."',workLocationPreference='".$json['workLocationPreference']."',timeToCall='".$json['timeToCall']."',declaration='".$json['declaration']."',preferedJobType='".$json['preferedJobType']."',joiningTimeline='".$json['joiningTimeline']."',Language='".$json['language']."',currentLocation='".$json['currentLocation']."',preferredWorkLocation='".$json['preferredWorkLocation']."',skills='".$json['skills']."',certifications='".$json['certifications']."',avgTenure='".$json['avgTenure']."' where id=".implode(',', $json['preInterviewId']);
        // if (mysqli_query($databaseConnection, $updatePreInterview)) {
        //     $to_encode = array(
        //         'data'=> 'Success',
        //         'status'=> 1
        //     );
        // }else{
        //     $to_encode = array(
        //         'data'=> 'error',
        //         'status'=> 0
        //     );
        // }



    } else {
        $to_encode = array(
            'data' => "err",
            'status' => 0
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['getWorkReportFilters'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $values = array();
        $filterQuery = '';
        $condition = '';
        $condition2 = '';

        if ($userType == 'corporate') {

            $condition = " and pr.id IN (SELECT preinterviewId FROM preInterview_corporate WHERE userId=" . $userId . ")";
            $condition2 = " and corporateId in (" . $userId . ")";
        }

        $filter1 = "select * from recruiterList where activeStatus='Y' " . $condition2 . " order by name ASC ";

        $filter1Result = mysqli_query($databaseConnection, $filter1);


        $values['recruiters'] = mysqli_fetch_all($filter1Result, MYSQLI_ASSOC);

        $filter2 = "select pr.id, case when pr.interviewName is null then (select name from aspiration_company where id=pr.company_id) else pr.interviewName end as interviewName from preInterview pr inner join interviewSchedule isc on isc.preInterviewId=pr.id where 1 " . $condition . " group by pr.id ORDER BY pr.id DESC";

        $filter2Result = mysqli_query($databaseConnection, $filter2);

        $values['interviews'] = mysqli_fetch_all($filter2Result, MYSQLI_ASSOC);





        //Akash 
        $filter3 = "select pr.company_id as id,a.name as companyName  from preInterview pr join aspiration_company a on a.id=pr.company_id where 1 " . $condition . "  group by id order by id desc;";
        $filter3Result = mysqli_query($databaseConnection, $filter3);
        $values['hiringCompanyName'] = mysqli_fetch_all($filter3Result, MYSQLI_ASSOC);

        $filter4 = "select  pr.id,pr.company_id,pr.interviewName as interviewName from preInterview pr join aspiration_company a on a.id=pr.company_id where 1 " . $condition . "  order by pr.id desc;";
        $filter4Result = mysqli_query($databaseConnection, $filter4);
        $values['jobName'] = mysqli_fetch_all($filter4Result, MYSQLI_ASSOC);

        $filter5 = "select distinct serviceType from preInterview order by serviceType desc;";
        $filter5Result = mysqli_query($databaseConnection, $filter5);
        $values['servicetype'] = mysqli_fetch_all($filter5Result, MYSQLI_ASSOC);


        $to_encode = array(
            'data' => $values,
            'status' => 1
        );

    } else {
        $to_encode = array(
            'data' => "err",
            'status' => 0
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['getrecruiterPerformanceFilters'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $values = array();
        $filterQuery = '';
        $condition = '';
        $condition2 = '';

        if ($userType == 'corporate') {

            $condition = " and pr.userId in (" . $userId . ")";
            $condition2 = " and corporateId in (" . $userId . ")";
        }

        $filter1 = "select * from recruiterList where activeStatus='Y' " . $condition2 . " order by name ASC ";

        $filter1Result = mysqli_query($databaseConnection, $filter1);


        $values['recruiters'] = mysqli_fetch_all($filter1Result, MYSQLI_ASSOC);

        $filter2 = "select pr.id, case when pr.interviewName is null then (select name from aspiration_company where id=pr.company_id) else pr.interviewName end as interviewName from preInterview pr inner join interviewSchedule isc on isc.preInterviewId=pr.id where 1 " . $condition . " group by pr.id ORDER BY pr.id DESC";

        $filter2Result = mysqli_query($databaseConnection, $filter2);

        $values['interviews'] = mysqli_fetch_all($filter2Result, MYSQLI_ASSOC);


        $to_encode = array(
            'data' => $values,
            'status' => 1
        );

    } else {
        $to_encode = array(
            'data' => "err",
            'status' => 0
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['getProfileSummaryFilters'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $values = array();
        $filterQuery = '';
        $condition = '';


        if ($userType == 'corporate') {

            $filterQuery = " and pr.userId in (" . $userId . ")";

        }

        $filter1 = "select r.id as roleId,r.name as role from scps_transaction scps left join relavant_role r on r.id=scps.position left join preInterview pr on pr.id=scps.preInterviewId where 1 " . $filterQuery . " group by scps.position";

        $filter1Result = mysqli_query($databaseConnection, $filter1);
        $values['roleList'] = mysqli_fetch_all($filter1Result, MYSQLI_ASSOC);


        $filter2 = "select * from locations order by cityName ASC";

        $filter2Result = mysqli_query($databaseConnection, $filter2);
        $values['location'] = mysqli_fetch_all($filter2Result, MYSQLI_ASSOC);

        // $filter3 = "select fs.id,fs.favourite_subject as subjectName from favourite_subject fs inner join scps_transaction scps on scps.subject=fs.id group by fs.id order by fs.favourite_subject ASC;";

        $filter3 = "SELECT MIN(id) as id, skillName as subjectName 
        FROM skills 
        GROUP BY skillName 
        ORDER BY skillName ASC;
        ";

        $filter3Result = mysqli_query($databaseConnection, $filter3);
        $values['subjectList'] = mysqli_fetch_all($filter3Result, MYSQLI_ASSOC);


        $to_encode = array(
            'data' => $values,
            'status' => 1
        );

    } else {
        $to_encode = array(
            'data' => "err",
            'status' => 0
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['fetchingJobDetails'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {


        $values = array();
        $filter1 = "SELECT * FROM interviewSchedule where emailId='" . $json['emailId'] . "' order by id desc limit 1";
        $filter1Result = mysqli_query($databaseConnection, $filter1);

        //Akash
        $emailId = $json['emailId'];
        $fetchingdata = "SELECT u.firstName from users u  where emailId= " . $emailId . ";";
        $fetchingdataResult = mysqli_query($databaseConnection, $fetchingdata);
        $values['name'] = $fetchingdataResult;



        $filter2 = "SELECT l.id as value,l.cityName as label from interviewSchedule isd inner join locations l on FIND_IN_SET(l.id,isd.preferredWorkLocation) where isd.emailId='" . $json['emailId'] . "' order by isd.id desc limit 1";
        $filter2Result = mysqli_query($databaseConnection, $filter2);
        if (mysqli_num_rows($filter1Result) > 0) {
            $values['details'] = mysqli_fetch_all($filter1Result, MYSQLI_ASSOC);
            $values['preferredLocation'] = mysqli_fetch_all($filter2Result, MYSQLI_ASSOC);


            $to_encode = array(
                'data' => $values,
                'status' => 1
            );
        } else {
            $to_encode = array(
                'data' => "err",
                'status' => 0
            );
        }

    } else {
        $to_encode = array(
            'data' => "err",
            'status' => 0
        );
    }
    echo json_encode($to_encode);
}
// node-api
else if (isset($_GET['getConnecttomentorFilters'])) {

    $values = array();

    $filter1 = "SELECT id,stream FROM stream;";
    $filter1Result = mysqli_query($databaseConnection, $filter1);
    $filter2 = "SELECT pd.year FROM professionaldetails pd WHERE pd.year NOT IN (0) GROUP BY pd.year ORDER BY pd.year ASC;";
    $filter2Result = mysqli_query($databaseConnection, $filter2);


    $filter3 = "select * from areasofinterest WHERE id not in (2,5,6,8,12,13) order by id ASC";
    $filter3Result = mysqli_query($databaseConnection, $filter3);

    $filter4 = "Select id,statusValue as `value` from salesLeadActionStatus where id in(1,2,3,5)";
    $filter4Result = mysqli_query($databaseConnection, $filter4);
    $filter5 = "SELECT id,collegeName FROM colleges ORDER BY collegeName ASC;";
    $filter5Result = mysqli_query($databaseConnection, $filter5);
    $filter6 = "SELECT * FROM sector";
    $filter6Result = mysqli_query($databaseConnection, $filter6);

    $filter7 = "SELECT id,concat(firstName,' (',usertype,')') as name FROM users where usertype in('tpmentor','mentor') and id in(select assignMentorId from professionaldetails where assignMentorId is not null group by assignMentorId)";
    $filter7Result = mysqli_query($databaseConnection, $filter7);

    $filter8 = "SELECT id,concat(firstName,' (',usertype,')') as name FROM users where usertype in('tpmentor','mentor') and id not in(select assignMentorId from professionaldetails where assignMentorId is not null group by assignMentorId)";
    $filter8Result = mysqli_query($databaseConnection, $filter8);

    $filter10 = "SELECT * FROM favourite_subject";
    $filter10Result = mysqli_query($databaseConnection, $filter10);

    // $filter11 = "SELECT * FROM aspiration_company";
    // if($json['userType']=='corporate'){

    //     $filter11 = "select r.id as roleId,ac.id as id,r.name as name,scp.status as status from relavant_role r inner join scps_transaction scp on scp.position=r.id inner join preInterview cd on cd.company_id=scp.company inner join aspiration_company ac on ac.id=cd.company_id where cd.userId='" . $json['companyId'] . "' group by scp.position,scp.company";

    // }else{

    $filter11 = "SELECT pr.id, COALESCE(pr.interviewName, ac.name) AS name FROM preInterview pr LEFT JOIN aspiration_company ac ON ac.id = pr.id WHERE pr.interviewType = 'Practice' AND (pr.interviewName IS NOT NULL OR ac.name IS NOT NULL) ORDER BY pr.id DESC";
    // }
    $filter11Result = mysqli_query($databaseConnection, $filter11);

    $filter12 = "select l.id as value,l.cityName as label from locations l inner join professionaldetails pd on pd.currentLocation=l.id where l.id not in(512,513,514,515,516,517,518,519) group by l.id order by l.cityName ASC";
    $filter12Result = mysqli_query($databaseConnection, $filter12);

    $filter13 = "select * from relavant_role order by id desc";
    $filter13Result = mysqli_query($databaseConnection, $filter13);

    // if($json['userType']=='tpmentor')
    // {
    //     $leadQuery = mysqli_query($databaseConnection, "Select id,statusValue as `value` from salesLeadActionStatus where id in(1,2,3,4,6,19,20)");
    // $values['leadFilter'] = mysqli_fetch_all($leadQuery, MYSQLI_ASSOC);
    // }
    // if($json['userType']!='tpmentor')
    // {
    // $leadQuery = mysqli_query($databaseConnection, "Select id,statusValue as `value` from salesLeadActionStatus where usedFor = 'L' and id in(1,2,3,5)");
    // $values['leadFilter'] = mysqli_fetch_all($leadQuery, MYSQLI_ASSOC);
    // }

    // Service Type filter options
    $serviceTypeOptions = [
        ['value' => 'Job', 'label' => 'Job'],
        ['value' => 'Practice', 'label' => 'Practice'],
        ['value' => 'Unknown', 'label' => 'Unknown']
    ];

    $values['stream'] = mysqli_fetch_all($filter1Result, MYSQLI_ASSOC);
    $values['yop'] = mysqli_fetch_all($filter2Result, MYSQLI_ASSOC);
    $values['connecttomentor'] = mysqli_fetch_all($filter3Result, MYSQLI_ASSOC);
    $values['leadstatusfilter'] = mysqli_fetch_all($filter4Result, MYSQLI_ASSOC);
    $values['college'] = mysqli_fetch_all($filter5Result, MYSQLI_ASSOC);
    $values['sector'] = mysqli_fetch_all($filter6Result, MYSQLI_ASSOC);
    $values['assignmentors'] = mysqli_fetch_all($filter7Result, MYSQLI_ASSOC);
    $values['notassignmentors'] = mysqli_fetch_all($filter8Result, MYSQLI_ASSOC);
    $values['subject'] = mysqli_fetch_all($filter10Result, MYSQLI_ASSOC);
    $values['interview_name'] = mysqli_fetch_all($filter11Result, MYSQLI_ASSOC);
    $values['location'] = mysqli_fetch_all($filter12Result, MYSQLI_ASSOC);
    $values['role'] = mysqli_fetch_all($filter13Result, MYSQLI_ASSOC);
    $values['serviceType'] = $serviceTypeOptions;



    $to_encode = array(
        'data' => $values,
        'status' => 1
    );

    echo json_encode($to_encode);
}
else if (isset($_GET['updateCompanyInterest'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if ($json) {
        $userType = $json['userType'];
        $userId = $json['userId'];
        $companyId = $json['companyId'];
        $isInterested = $json['isInterested'];
        $candidateId = $json['candidateId'];
        $feedbackRequestId = $json['feedbackRequestId'];
        $queryToCheck = "SELECT * FROM `company_candidate_interest` WHERE `companyId` in (SELECT `company_id` FROM `preInterview` WHERE `userId` = " . $userId . " and company_id=" . $companyId . ") AND `candidateId` = " . $candidateId . " AND `feedbackRequestId` = " . $feedbackRequestId . " ";

        $queryToCheckData = mysqli_query($databaseConnection, $queryToCheck);
        if (mysqli_num_rows($queryToCheckData) > 0) {
            if ($isInterested != '') {
                $queryToUpdate = "UPDATE `company_candidate_interest` SET `status`='" . $isInterested . "' WHERE `companyId`= (SELECT `company_id` FROM `preInterview` WHERE `userId` = " . $userId . " and company_id=" . $companyId . ") AND `candidateId`= " . $candidateId . " AND `feedbackRequestId`= " . $feedbackRequestId . "";
            }
            $queryToUpdateData = mysqli_query($databaseConnection, $queryToUpdate);
            if ($queryToUpdateData) {
                $to_encode = array(
                    'status' => 1,
                    'data' => 'Update Success'
                );
            } else {
                $to_encode = array(
                    'status' => -1,
                    'data' => 'Error While Update'
                );
            }
        } else {
            if ($isInterested != '') {
                $queryToInsert = "INSERT INTO `company_candidate_interest`(`companyId`, `candidateId`, `feedbackRequestId`,`status`) VALUES ((SELECT `company_id` FROM `preInterview` WHERE `userId` = " . $userId . " and company_id=" . $companyId . ")," . $candidateId . "," . $feedbackRequestId . ",'" . $isInterested . "')";
            }


            $queryToInsertData = mysqli_query($databaseConnection, $queryToInsert);
            if ($queryToInsertData) {
                $to_encode = array(
                    'status' => 1,
                    'data' => 'Insert Success'
                );
            } else {
                $to_encode = array(
                    'status' => -1,
                    'data' => 'Error While Insert'
                );
            }
        }
    } else {
        $to_encode = array(
            'data' => $values,
            'status' => 1
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['UserA/VConfirmation'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if ($json) {

        if (!empty($json['isconfirmCheckedYes']) == 'Y') {
            $queryToInsert = "UPDATE `users`SET `AVConfirm`='Y' , AVConfirmDate=Now() WHERE id = " . $json['candidateId'] . ";";
        } else if (!empty($json['isconfirmCheckedNo']) == 'N') {
            $queryToInsert = "UPDATE `users`SET `AVConfirm`='N', AVConfirmDate=Now() WHERE id = " . $json['candidateId'] . ";";
        } else {
            $queryToInsert = "UPDATE `users`SET `AVConfirm`='N', AVConfirmDate=Now() WHERE id = " . $json['candidateId'] . ";";
        }

        $queryToInsertData = mysqli_query($databaseConnection, $queryToInsert);

        if ($queryToInsertData) {
            $to_encode = array(
                'status' => 1,
                'data' => 'Insert Success'
            );
        } else {
            $to_encode = array(
                'status' => -1,
                'data' => 'Error While Insert'
            );
        }
    } else {
        $to_encode = array(
            'data' => $values,
            'status' => 1
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['checkForPromotionActive'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if ($json) {
        $flag = $json['flag'];



        if ($flag == 0) {
            $sql = "select * from promotion  where id=" . $json['preInterviewId'] . "";
            //echo $sql;
            $queryToCheckData = mysqli_query($databaseConnection, $sql);

            if (mysqli_num_rows($queryToCheckData) > 0) {
                $to_encode = array(
                    'status' => 1,
                    'data' => 'checked Successfully'
                );
            } else {
                $to_encode = array(
                    'status' => -1,
                    'data' => 'Error While check'
                );
            }
        } else {
            $to_encode = array(
                'data' => 'error while in the given data',
                'status' => -1
            );
        }
    }
    echo json_encode($to_encode);


} else if (isset($_GET['deactivate_job'])) {
    //this method is added by arun on 23 dec 2022 to deactivate the jobs only for corporate
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if ($json) {
        $flag = $json['flag'];
        if ($flag == 1) {
            $roleId = $json['roleId'];
            $companyId = $json['companyId'];
            $jobstatus = $json['jobstatus'];
            $publish = $json['publish'];

            $sql = "UPDATE `scps_transaction` set status='" . $jobstatus . "' where company=" . $companyId . " and position=" . $roleId . "";
            //echo $sql;
            $queryToInsertData = mysqli_query($databaseConnection, $sql);

            if ($queryToInsertData) {
                $to_encode = array(
                    'status' => 1,
                    'data' => 'Insert Success'
                );
            } else {
                $to_encode = array(
                    'status' => -1,
                    'data' => 'Error While Insert'
                );
            }
        } else if ($flag == 0) {
            $sql = "UPDATE `preInterview` set interviewStatus='" . $json['jobstatus'] . "' where id=" . $json['preInterviewId'] . "";
            //echo $sql;
            $queryToInsertData = mysqli_query($databaseConnection, $sql);

            $promotion = $json['promotions'];
            if ($promotion == 'promotion') {
                $sql1 = "UPDATE `promotion` set archiveDate= NOW() where preInterviewId=" . $json['preInterviewId'] . " AND archiveDate IS NULL";
                //echo $sql;
                $queryToInsertData1 = mysqli_query($databaseConnection, $sql1);

            }

            if ($queryToInsertData) {
                $to_encode = array(
                    'status' => 1,
                    'data' => 'Update Successfully'
                );
            } else {
                $to_encode = array(
                    'status' => -1,
                    'data' => 'Error While Update'
                );
            }
        } else if ($flag == 2) {
            $sql2 = "UPDATE `preInterview` set interviewStatus='" . $json['jobstatus'] . "', publish='" . $json['publish'] . "' where id=" . $json['preInterviewId'] . "";
            //echo $sql;
            $queryToInsertData = mysqli_query($databaseConnection, $sql2);


            $sql3 = "UPDATE `promotion` set archiveDate= NOW() where preInterviewId=" . $json['preInterviewId'] . " AND archiveDate IS NULL";

            $queryToInsertData1 = mysqli_query($databaseConnection, $sql3);

            if ($queryToInsertData) {
                $to_encode = array(
                    'status' => 1,
                    'data' => 'Update Successfully'
                );
            } else {
                $to_encode = array(
                    'status' => -1,
                    'data' => 'Error While Update'
                );
            }
        } else {
            $to_encode = array(
                'data' => 'error while in the given data',
                'status' => -1
            );
        }
    }
    echo json_encode($to_encode);
} else if (isset($_GET['close_job'])) {
    //this method is added by arun on 23 dec 2022 to deactivate the jobs only for corporate
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if ($json) {
        $flag = $json['flag'];
        if ($flag == 1) {
            $sql = "UPDATE `preInterview` set publish='C' where id=" . $json['preInterviewId'] . "";
            //echo $sql;
            $queryToInsertData = mysqli_query($databaseConnection, $sql);

            // $promotion = $json['promotions'];
            // if( $promotion  == 'promotion'){
            //     $sql1="UPDATE `promotion` set archiveDate= NOW() where preInterviewId=".$json['preInterviewId']." AND archiveDate IS NULL";
            //     //echo $sql;
            //     $queryToInsertData1 = mysqli_query($databaseConnection,$sql1);

            // }

            if ($queryToInsertData) {
                $to_encode = array(
                    'status' => 1,
                    'data' => 'Update Successfully: closed job'
                );
            } else {
                $to_encode = array(
                    'status' => -1,
                    'data' => 'Error While Update'
                );
            }
        } else if ($flag == 2) {
            $sql2 = "UPDATE `preInterview` set publish='Y' where id=" . $json['preInterviewId'] . "";
            //echo $sql;
            $queryToInsertData = mysqli_query($databaseConnection, $sql2);


            // $sql3="UPDATE `promotion` set archiveDate= NOW() where preInterviewId=".$json['preInterviewId']." AND archiveDate IS NULL";
            // $queryToInsertData1 = mysqli_query($databaseConnection,$sql3);

            if ($queryToInsertData) {
                $to_encode = array(
                    'status' => 1,
                    'data' => 'Update Successfully opened job'
                );
            } else {
                $to_encode = array(
                    'status' => -1,
                    'data' => 'Error While Update'
                );
            }
        } else {
            $to_encode = array(
                'data' => 'error while in the given data',
                'status' => -1
            );
        }
    }
    echo json_encode($to_encode);
} else if (isset($_GET['updateCompanyUrlviewed'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if ($json) {
        $userType = $json['userType'];
        $userId = $json['userId'];
        $companyId = $json['companyId'];
        $isviewed = $json['isviewed'];
        $candidateId = $json['candidateId'];
        $companyId = $json['companyId'];
        $feedbackRequestId = $json['feedbackRequestId'];

        $queryToCheck = "SELECT * FROM `company_candidate_interest` WHERE `companyId` in (SELECT `company_id` FROM `preInterview` WHERE `userId` = " . $userId . " and company_id=" . $companyId . ") AND `candidateId` = " . $candidateId . " AND `feedbackRequestId` = " . $feedbackRequestId . " ";

        $queryToCheckData = mysqli_query($databaseConnection, $queryToCheck);
        if (mysqli_num_rows($queryToCheckData) > 0) {
            if ($isviewed == 'Y') {
                $queryToUpdate = "UPDATE `company_candidate_interest` SET `checkurl`='Y' WHERE `companyId`= " . $companyId . " AND `candidateId`= " . $candidateId . " AND `feedbackRequestId`= " . $feedbackRequestId . "";
            } else if ($isviewed == 'N') {
                $queryToUpdate = "UPDATE `company_candidate_interest` SET `checkurl`='N' WHERE `companyId`= " . $companyId . " AND `candidateId`= " . $candidateId . " AND `feedbackRequestId`= " . $feedbackRequestId . "";
            }

            $queryToUpdateData = mysqli_query($databaseConnection, $queryToUpdate);
            if ($queryToUpdateData) {
                $to_encode = array(
                    'status' => 1,
                    'data' => 'Update Success'
                );
            } else {
                $to_encode = array(
                    'status' => -1,
                    'data' => 'Error While Update'
                );
            }
        } else {
            $queryToInsert = "INSERT INTO `company_candidate_interest`(`companyId`, `candidateId`, `feedbackRequestId`,`checkurl`) VALUES (" . $companyId . "," . $candidateId . "," . $feedbackRequestId . ",'" . $isviewed . "')";

            $queryToInsertData = mysqli_query($databaseConnection, $queryToInsert);
            if ($queryToInsertData) {
                $to_encode = array(
                    'status' => 1,
                    'data' => 'Insert Success'
                );
            } else {
                $to_encode = array(
                    'status' => -1,
                    'data' => 'Error While Insert'
                );
            }
        }
    } else {
        $to_encode = array(
            'data' => $values,
            'status' => 1
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['approveInterest'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if ($json) {
        $userType = $json['userType'];
        $companyId = $json['companyId'];
        $isApproved = $json['isApproved'];
        $candidateId = $json['candidateId'];
        $feedbackRequestId = $json['feedbackRequestId'];

        if ($isApproved == 'Y') {
            $queryToUpdate = "UPDATE `company_candidate_interest` SET `isApproved`='Y' WHERE `candidateId`= " . $candidateId . " AND `feedbackRequestId`= " . $feedbackRequestId . " AND `companyId` = " . $companyId . "";
        } else {
            $queryToUpdate = "UPDATE `company_candidate_interest` SET `isApproved`='N' WHERE `candidateId`= " . $candidateId . " AND `feedbackRequestId`= " . $feedbackRequestId . " AND `companyId` = " . $companyId . "";
        }
        $queryToUpdateData = mysqli_query($databaseConnection, $queryToUpdate);
        if ($queryToUpdateData) {
            $to_encode = array(
                'status' => 1,
                'data' => 'Update Success'
            );
        } else {
            $to_encode = array(
                'status' => -1,
                'data' => 'Error While Update'
            );
        }
    } else {
        $to_encode = array(
            'data' => $values,
            'status' => 1
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['getProfileViewData'])) {
    // this method is added by arun on 1 Sep 2023 to show the details of the candidates

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if ($json) {
        $userType = $json['userType'];
        $userId = $json['userId'];
        $limit = $json['limit'];
        $start = ($json['page'] - 1) * ($limit);
        $limit_query = $limit == 0 ? "" : " limit " . $start . "," . $limit;
        $filterQry = '';
        $rawData = '';
        $having_query = ' ';

        if ($json['interviewname'] != "") {
            // $filterQry.=" and isc.preInterviewId in (".$json['interviewname'].") ";
            $isApplyFilter = "CASE WHEN isc.preInterviewId in(" . $json['interviewname'] . ") THEN 'Yes' ELSE 'No' END AS isApply";
        } else {
            $isApplyFilter = "'No' AS isApply";
        }

        // $filterQry.=" AND isc.candidate_id IS NOT NULL";

        if ($userType == 'corporate') {
            $filterQry .= " and t.preInterviewId in (SELECT preinterviewId FROM preInterview_corporate WHERE userId=" . $userId . ") ";

            $rawData .= " LEFT JOIN company_candidate_interest cci ON cci.companyId in (SELECT cd.company_id FROM preInterview cd WHERE cd.id in (SELECT preinterviewId FROM preInterview_corporate WHERE userId=" . $userId . ")) AND cci.candidateId = u.id AND cci.feedbackRequestId = fbr.id ";
        } else if ($userType = 'admin') {
            $rawData .= " LEFT JOIN company_candidate_interest cci ON cci.candidateId = u.id AND cci.feedbackRequestId = fbr.id ";
        }


        if ($json['apply'] != '') {
            $having_query .= "HAVING isApply in ('" . implode("','", $json['apply']) . "')";
        }

        // for profile match %
        $preferenceResult = mysqli_query($databaseConnection, "SELECT * from profilePreferences where preInterviewId =" . $json['interviewname']);
        if (mysqli_num_rows($preferenceResult) > 0) {
            $total_data['preferences'] = mysqli_fetch_all($preferenceResult, MYSQLI_ASSOC);
        } else {
            $total_data['preferences'] = [];
        }
        // $query="select isc.emailId as scheduleEmail,pr.id as preInterviewId,u.id,isc.candidateStatus,isc.candidateStatusDate,pd.resumeSharedCompany,pd.resumeSharedDate,pd.noticePeriod,CONCAT(pd.salary,'/',pd.expectedSalary) as salary,pd.workExperience, concat(u.firstName,u.lastName) as name, u.emailId, u.mobileNumber, pd.college as cl_id, cl.collegeName as college, st.stream as specialization, pd.year,pd.cgpa,u.createdOn as signUpDate, concat('/review?profile=',fbr.candidateId) as url,pd.specialization as str_id,fbr.interviewSessionId as sessionId, case when pr.interviewName is null then ac.name else pr.interviewName end as interview_name, i.id as intId, fbr.id as fbr_id, (SELECT l.cityName from locations l where l.id=pd.currentLocation) as currentLocation,fbr.review_status as fbr_status,pd.fav_subjects as fav_subjectId,pd.fav_programming_skill as fav_programming_skillId,pd.languages as languageKnownId,pd.internship,pd.asp_companies as asp_companiesId,pr.hiringCompanies,cci.status as isInterested,cci.checkurl as isviewed,cci.isApproved as isApproved from feedback_request fbr left outer join interview i on fbr.interviewId = i.id left outer join feedback_report fr on fr.feedbackRequestId = fbr.id left outer join users u on u.id = fbr.candidateId left outer join interviewSchedule isc on isc.preInterviewId= i.preInterviewId and isc.emailId=u.emailId left outer join professionaldetails pd on pd.candidateId=u.id left outer join stream st on pd.specialization = st.id left outer join colleges cl on cl.id=pd.college left outer join preInterview pr on pr.id=i.preInterviewId left outer join aspiration_company ac on ac.id = i.companyId ".$rawData." where 1 and pr.jobCategory in ('profile') ".$filterQry." group by isc.emailId,isc.preInterviewId order by i.preInterviewId DESC";

        $query = "SELECT pi.id AS preinterviewid,isc.candidate_id AS user_id,pi.company_id as company_id,pi.jobType AS jobType,pi.interviewStartDate AS schedule_time,pi.interviewName AS interviewName,isc.workExperience AS workExperience,isc.currentCompany AS currentCompany,isc.currentLocation AS currentLocation,CONCAT(isc.currentSalary, '/', isc.expectedSalary) AS expectedSalary,pi.noticePeriod AS noticePeriod,isc.candidateName AS name,isc.emailId as scheduleEmail,isc.candidateStatus AS candidateStatus,isc.candidateStatusDate AS candidateStatusDate,ac.name As companyName,concat('/review?c=', u.id,'&prId=', isc.preinterviewid) AS url,pi.jobCategory as jobCategory," . $isApplyFilter . ", NULL AS interviewScheduleid,'preInterview' AS source FROM interviewSchedule isc  INNER JOIN users u ON isc.emailId = u.emailId LEFT JOIN preInterview pi ON isc.preinterviewid = pi.id LEFT JOIN aspiration_company ac ON pi.company_id = ac.id where 1 " . $filterQry . " " . $having_query . " ORDER BY CASE WHEN isApply = 'Yes' THEN 1 WHEN isApply = 'No' THEN 2 ELSE 3 END";

        // echo $query;

        $data = $query . $limit_query;



        $result = mysqli_query($databaseConnection, $data);
        if (mysqli_num_rows($result) > 0) {

            $count_query = mysqli_query($databaseConnection, $query);

            $values = mysqli_fetch_all($result, MYSQLI_ASSOC);

            $total_data['data'] = $values;
            $total_data['count'] = mysqli_num_rows($count_query);
            $to_encode = $total_data;


        } else {
            $to_encode = array(
                'status' => 0,
                'data' => 'Error While fetching'
            );
        }
    } else {
        $to_encode = array(
            'data' => $values,
            'status' => 1
        );
    }
    echo json_encode($to_encode);
}
else if (isset($_GET['getServiceDashboard'])) {
    // this method is added by sourabh on 18 Oct 2023 to show the details of the candidates

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if ($json) {
        $userType = $json['userType'];
        $userId = $json['userId'];
        $limit = $json['limit'];
        $start = ($json['page'] - 1) * ($limit);
        $limit_query = $limit == 0 ? "" : " limit " . $start . "," . $limit;
        $profileSkillMatchQuery = '';
        $filterQry = '';
        $rawData = '';
        $having_query = ' ';
        $condition1 = '';
        $condition2 = '';
        $condition3 = '';
        $condition4 = '';
        $condition5 = '';
        $condition6 = 'and preInterviewType="job" ';
        $condition7 = '';
        $condition8 = '';
        $interviewname = '';
        $interviewnameString = '';
        $profileMismatchFlag = $json['profileMismatchFlag'];
        $archiveflag = $json['archiveflag'];
        $archiveQry = '';
        // filters


        // if($json['interviewname'] != ""){
        //     $interviewname = " and interviewSchedule.preInterviewId in(".$json['interviewname'].") ";
        // }
        if ($archiveflag == 0) {
            $archiveQry = "and pr.interviewStatus ='Active'";
        } else {
            $archiveQry = '';
        }

        if (!empty($json['interviewname']) && $json['interviewname'] != ['0']) {
            if (is_array($json['interviewname'])) {
                $interviewnameString = implode(",", $json['interviewname']);
                $interviewname = " where interviewSchedule.preInterviewId IN (" . $interviewnameString . ")";
            } else {
                $interviewnameString = $json['interviewname'];
                $interviewname = " where interviewSchedule.preInterviewId IN (" . $interviewnameString . ")";
            }
        } else {

            $interviewname = "";
        }
        if (!empty($json['candidateExperience'])) {

            $experienceValues = array_map('floatval', (array) $json['candidateExperience']);
            sort($experienceValues);

            $conditions = [];

            foreach ($experienceValues as $experience) {
                if ($experience == 11) {
                    $conditions[] = "(workExperience >= 11.0)";
                } else {
                    // Calculate min and max for each selected experience value
                    $minExperience = $experience;
                    $maxExperience = $experience + 0.9;
                    $conditions[] = "(workExperience >= $minExperience AND workExperience <= $maxExperience)";
                }

            }

            // Join conditions with OR for multiple selected experiences
            if (!empty($conditions)) {
                $condition5 .= " AND (" . implode(" OR ", $conditions) . ")";
            }
        } else {
            // Handle the case when candidateExperience is empty or invalid
            $condition5 .= "";
        }


        if ($json['candidate_search'] != "") {
            if (preg_match('/^[0-9]{10}+$/', $json['candidate_search'])) {
                $condition1 .= " and mobileNumber=" . $json['candidate_search'] . "";
            } else if (filter_var($json['candidate_search'], FILTER_VALIDATE_EMAIL)) {
                $condition1 .= " and emailId='" . $json['candidate_search'] . "'";
            } else if (preg_match('/^[0-9]{1,5}$/', $json['candidate_search'])) {
                $condition1 .= " AND id = '" . $json['candidate_search'] . "'";
            } else {
                $condition1 .= " and candidateName like '%" . $json['candidate_search'] . "%'";
            }
        }

        if ($json['candidate_search'] == "") {
            if ($json['candidateStatus'] != '') {
                if ($json['candidateStatus'] == ['unAttended']) {
                    // $condition2 .=" and (candidateStatus in ('UnAttended','Not Attended') or candidateStatus is null) ";
                    $condition2 .= " and ( (candidateStatus is null and interviewStatus in ('Assessment Completed')) ) ";
                } else if ($json['candidateStatus'] == ['Assessment Completed']) {
                    $condition2 .= " and interviewStatus in ('" . implode("','", $json['candidateInterviewStatus']) . "')";
                } else if ($json['candidateStatus'] == ['totalSchedule']) {
                    // $condition2 .=" and t.submissionFlag IN('Y','WA')"; 
                } else if ($json['candidateStatus'] == ['Scheduled']) {
                    $condition2 .= " and (interviewStatus in ('Missed Schedule', 'Scheduled Today', 'Future Scheduled', 'Re-Scheduled','Scheduled') and candidateStatus is null) ";
                } else {
                    if ($profileMismatchFlag == 1) {
                        $condition2 .= " and (candidateStatus in ('" . implode("','", $json['candidateStatus']) . "') OR candidateStatus = 'Profile Mismatch') ";
                    } else {
                        $condition2 .= " and candidateStatus in ('" . implode("','", $json['candidateStatus']) . "') ";
                    }

                }
            } else {
                if ($profileMismatchFlag == 1) {
                    $condition2 .= " AND (candidateStatus NOT IN ('Recruiter Reject') OR candidateStatus IS NULL) ";
                } else {
                    $condition2 .= " AND (candidateStatus NOT IN ('Recruiter Reject','Profile Mismatch') OR candidateStatus IS NULL) ";
                    // xxx $condition2 .= " AND candidateStatus NOT IN ('Recruiter Reject') ";    
                }

            }

            // if($profileMismatchFlag == 1){
            //     $condition9 .= "and candidateStatus in ('Profile Mismatch')";
            // }

            if ($json['candidateInterviewStatus'] != '') {
                $condition7 .= " AND interviewStatus in ('" . implode("','", $json['candidateInterviewStatus']) . "') ";
            }

            if ($json['candidateSource'] != '') {
                $candidateSources = $json['candidateSource'];
                if (count($candidateSources) === 1 && in_array('gopracDB', $candidateSources)) {
                    // If the candidateSource array contains only 'gopracDB'
                    $condition8 .= " AND (promotionSource is null) ";
                } elseif (in_array('gopracDB', $candidateSources)) {
                    // If the candidateSource array contains 'gopracDB' among other sources
                    $condition8 .= " AND (promotionSource is null OR promotionSource in ('" . implode("','", $candidateSources) . "')) ";
                } else {
                    // If the candidateSource array does not contain 'gopracDB'
                    $condition8 .= " AND promotionSource in ('" . implode("','", $candidateSources) . "') ";
                }
            }
        }

        if ($json['candidate_search'] == "") {
            if ($json['noticePeriod'] != '') {
                if (is_array($json['noticePeriod'])) {
                    $condition3 .= " and noticePeriod in ('" . implode("','", $json['noticePeriod']) . "')";
                } else {
                    $condition3 .= " and noticePeriod in ('" . $json['noticePeriod'] . "')";
                }
            }
        }

        if ($json['candidateLocation'] != '') {
            $condition4 .= " and currentLocation in ('" . implode("','", $json['candidateLocation']) . "')";
        }



        if ($userType == 'corporate') {
            $filterQry .= " and t.preInterviewId in (SELECT preinterviewId FROM preInterview_corporate WHERE userId=" . $userId . ") ";

            $rawData .= " LEFT JOIN company_candidate_interest cci ON cci.companyId in (SELECT cd.company_id FROM preInterview cd WHERE cd.id in (SELECT preinterviewId FROM preInterview_corporate WHERE userId=" . $userId . ")) AND cci.candidateId = u.id AND cci.feedbackRequestId = fbr.id ";
        } else if ($userType = 'admin') {
            if ($json['workreportredirect'] == 'unAttended1') {
            } else {
                $filterQry .= " and t.submissionFlag IN('Y','WA')";
            }
            $rawData .= " LEFT JOIN company_candidate_interest cci ON cci.candidateId = u.id AND cci.feedbackRequestId = fbr.id ";
        }

        // for profile match %
        // $qq="SELECT * from profilePreferences where preInterviewId ='".$json['interviewname']. "';";
        if (!empty($json['interviewname']) && $json['interviewname'] !== ['0']) {

            // preferences
            $qq = "SELECT * from profilePreferences where preInterviewId IN(" . $interviewnameString . ");";
            // echo $qq ;
            $preferenceResult = mysqli_query($databaseConnection, $qq);
            if (mysqli_num_rows($preferenceResult) > 0) {
                $total_data['preferences'] = mysqli_fetch_all($preferenceResult, MYSQLI_ASSOC);
            } else {
                $total_data['preferences'] = [];
            }

            // jobDetails

            // $qq="SELECT * from preInterview LEFT JOIN interviewSchedule where id IN(".$interviewnameString.");";
            // // echo $qq ;
            // $jobDetailsResult = mysqli_query($databaseConnection,$qq);
            // if (mysqli_num_rows($jobDetailsResult)>0) {
            //     $total_data['jobDetails'] = mysqli_fetch_all($jobDetailsResult,MYSQLI_ASSOC);
            // } else {
            //     $total_data['jobDetails'] = [];
            // }
        } else if (!empty($json['interviewname']) && $json['interviewname'] === ['0']) {
            $qq = "SELECT * from profilePreferences ;";
            // echo $qq ;
            $preferenceResult = mysqli_query($databaseConnection, $qq);

            if (mysqli_num_rows($preferenceResult) > 0) {
                $total_data['preferences'] = mysqli_fetch_all($preferenceResult, MYSQLI_ASSOC);
            } else {
                $total_data['preferences'] = [];
            }
        } else {
            $total_data['preferences'] = [];
        }

        // COALESCE(pd.verifyFlag, isc.verifyFlag) as verifyFlag,



        // main query
        $query = "SELECT case when t.candidateStatus is null and t.interviewStatus in ('Assessment Completed') then 'Assessment Completed' when t.interviewStatus in ('Assessment in Progress', 'Internal Review') then 'Assessment Awaited' when t.candidateStatus is null and t.interviewStatus in ('duplicateAttempt', 'limitedFreeAssessment', 'unauthorizedUser', 'Incomplete', 'Technical Issue', 'Rejected') then 'Assessment Rejected' when t.candidateStatus is null and t.interviewStatus in ('Missed Schedule', 'Scheduled Today', 'Future Scheduled', 'Re-Scheduled')  then 'Scheduled'  WHEN t.candidateStatus is null and t.interviewStatus IN ('Job Invited') THEN 'Job Invited'  WHEN t.candidateStatus is null and t.interviewStatus IN ('Scheduled') THEN 'Scheduled' 
         else t.candidateStatus end as candidStatus,t.* ,CASE
		when t.speechAceJobWorked in('I','N','R') THEN 'In-Progress'
		when t.speechAceJobWorked in('Y') AND t.skillScore is null THEN 'N/A'
	    else t.skillScore
	    END as speakingSkill,
        t.suitability AS suitability_function,t.candidateStatus,
        calculateAverageSkillScoreSubjectWise(t.intId, 'Domain Knowledge') as subjectScores,
        CASE WHEN t.intScore IS NOT NULL AND t.intScore != -1 THEN applicantPercentile(t.intScore, t.preInterviewId) 
        ELSE 'N/A'
        END AS percentile_function,
        t.apm,t.apmStatus,t.source,t.intScore,
        case when t.relocateFlag ='YES' and t.companyJobLocation=t.currLocation then 'SL'
        when t.relocateFlag ='YES' then 'YES'
        when t.relocateFlag ='NO' then 'NO'
        when t.relocateFlag ='' then ''
        end as relocateStatus,
            (
            SELECT 
                JSON_ARRAYAGG(
                    JSON_OBJECT(
                        'malpracticeValue', mt.malpracticeValue,
                        'interviewName', mt.interviewName,
                        'interviewSessionId', mt.interviewSessionId,
                        'count', mt.cnt
                    )
                )
            FROM (
                SELECT 
                    mv.candidateId,
                    mv.malpracticeValue,
                    pr.interviewName,
                    mv.interviewSessionId,
                    COUNT(*) AS cnt
                FROM feedback_request fr
                JOIN mergedVideos mv ON fr.interviewSessionId = mv.interviewSessionId
                JOIN AnswerTranscription at ON mv.mergeId = at.mergeId
                JOIN preInterview pr ON pr.id = fr.preInterviewId
                WHERE at.ansText IS NOT NULL
                AND mv.malpracticeValue IS NOT NULL
                AND mv.interviewSessionId = t.sessionId
                 GROUP BY mv.malpracticeValue
            ) mt
        ) as malpractice_stats
        from (
            SELECT isc.iId as iId2, isc.emailId as scheduleEmail,
            CASE
            WHEN (fbr.id IS NOT NULL AND (fbr.review_status = 2)
                ) THEN 'Assessment Completed'
            WHEN ((fbr.id IS NOT NULL or cit.completion_status IS NOT NULL) AND fbr.review_status IN(0, 1)
                ) THEN 'Assessment in Progress'
            WHEN ((fbr.id IS NOT NULL or cit.completion_status IS NOT NULL) AND fbr.review_status = -2
                ) THEN 'Internal Review'
            WHEN (fbr.id IS NOT NULL AND (fbr.review_status = -4 AND fbr.reasonOfRejection = 'incompleteInterview')
                ) THEN 'Incomplete'
            WHEN (fbr.id IS NOT NULL AND (fbr.review_status = -4 AND fbr.reasonOfRejection = 'technicalIssue')
                ) THEN 'Technical Issue' 
            WHEN (fbr.id IS NOT NULL AND (fbr.review_status = -4 AND fbr.reasonOfRejection NOT IN('technicalIssue','incompleteInterview'))
                ) THEN 'Rejected'
            WHEN (fbr.id IS NOT NULL AND(
                    fbr.review_status = -4 AND fbr.reasonOfRejection = 'duplicateAttempt')
                ) THEN 'duplicateAttempt'
            WHEN (fbr.id IS NOT NULL AND(
                    fbr.review_status = -4 AND fbr.reasonOfRejection = 'limitedFreeAssessment')
                ) THEN 'limitedFreeAssessment' 
            WHEN (fbr.id IS NOT NULL AND(
                  fbr.review_status = -4 AND fbr.reasonOfRejection = 'unauthorizedUser')
                ) THEN 'unauthorizedUser' 
            WHEN (fbr.id IS NULL AND (isc.scheduleTime != isc.firstScheduleDate) 
                 AND (DATEDIFF(isc.scheduleTime, NOW())) >= 1
                 AND isc.candidateStatus not in ('Profile Mismatch','Error')) THEN 'Re-Scheduled' 
            WHEN (fbr.id IS NULL AND isc.scheduleTime = 1) THEN 'Future Scheduled' 
            WHEN (fbr.id IS NULL
            AND (isc.scheduleTime = isc.firstScheduleDate)
            AND (DATEDIFF(isc.scheduleTime, NOW())) >= 1) THEN 'Future Scheduled'
            WHEN (fbr.id IS NULL
            AND isc.scheduleTime is not null
            AND isc.scheduleTime < NOW()
            AND isc.candidateStatus not in ('Profile Mismatch', 'Error')) THEN 'Missed Schedule'
            WHEN (fbr.id IS NULL
            AND fbr.review_status IS NULL
            AND isc.scheduleTime is not null
            AND isc.candidateStatus not in ('Profile Mismatch', 'Error')) THEN 'Scheduled'
            WHEN (fbr.id IS NULL
            AND fbr.review_status IS NULL
            AND isc.scheduleTime is null
            AND isc.candidateStatus not in('applied')) THEN 'Job Invited'
            WHEN (fbr.id IS NULL
            AND fbr.review_status IS NULL
            AND isc.candidateStatus = 'applied') THEN 'NA'
            WHEN (fbr.id IS NULL
            AND fbr.review_status IS NULL
            AND isc.candidateStatus = 'Profile Mismatch') THEN 'NA'
            WHEN (fbr.id IS NULL
            AND fbr.review_status IS NULL
            AND isc.candidateStatus = 'Error') THEN 'NA'
            END AS interviewStatus,
            CASE
            WHEN isc.promotionSource = 'nau' then 'Naukri'
            when isc.promotionSource = 'lin' then 'LinkedIn'
            when isc.promotionSource = 'soc' then 'Social Media'
            when isc.promotionSource = 'ist' then COALESCE((select name from recruiterList where id in (isc.recruiterId)), 'IS Team')
            else 'Goprac DB'
            End as Source,
            CASE
            WHEN isc.outstationDeclaration = 'Y' THEN 'YES'
            WHEN isc.outstationDeclaration = 'N' THEN 'NO'
            WHEN isc.outstationDeclaration is null THEN ''
            END AS relocateFlag, 
            isc.candidateStatus,
            isc.promotionSource,
            isc.submissionFlag,
            isc.apm,
            isc.apmStatus,
            isc.candidateStatusDate,
            CONCAT(DATEDIFF(NOW(), isc.candidateStatusDate), ' days ago') AS leadAge,
            isc.candidateName,
            isc.scheduleTime,
            isc.candidate_id as id,
            isc.emailId,
            isc.mobileNumber,
            isc.preInterviewId,
            isc.candidateName AS name,
            isc.employmentStatus,
            isc.resume,
            pd.assignMentorId,
            pd.resumeSharedCompany,
            pd.candidateFeedback,
            pd.resumeSharedDate,
            COALESCE(pd.noticePeriod, isc.noticePeriod) as noticePeriod,
            pd.workLocationPreference,
            pd.shift,
            CASE 
                WHEN isc.submissionFlag = 'WA' THEN isc.skillValues 
                ELSE pd.skills 
            END AS skills,
            isc.verifyFlag,
            COALESCE(pd.currentLocation, isc.currentLocation) as currentLocation,
            pd.jobType,
            CASE 
                WHEN isc.submissionFlag = 'WA' THEN isc.currentCompany 
                ELSE pd.currentCompany
            END AS currentCompany,
            COALESCE(pd.expectedSalary, isc.expectedSalary) as expectedSalary,
            COALESCE(pd.salary, isc.currentSalary) as currentSalary,
            COALESCE(pd.workExperience, isc.workExperience) as workExperience,
            COALESCE(pd.offer, isc.offer) as offerFlag,
            COALESCE(pd.offeredCTC, isc.offeredCTC) as offeredCTC,
            pd.college as cl_id,
            pd.year,
            pd.cgpa,
            pd.specialization as str_id,
            pd.fav_subjects as fav_subjectId,
            pd.fav_programming_skill as fav_programming_skillId,
            pd.languages as languageKnownId,
            pd.internship,
            pd.asp_companies as asp_companiesId,
            fbr.reasonOfRejection as reasonOfRejection,
            fbr.interviewSessionId as sessionId,
            fbr.id as fbr_id,
            fbr.suitability,
            fbr.dk_score,
            fbr.intScore,
            fbr.requestDate as InterviewDate,
                        fbr.review_status as fbr_status,
            fbr.viewAssessment,
            fbr.updatedAt as skillUpdateDate,
            pr.hiringCompanies,
            pr.RecruiterEmail,
            pr.requiredSkills,
            pr.ultraMandatorySkill,
            pr.company_id,
            i.assessmenttype as assessmenttype,
            i.companyId,
            i.id as intId,
            nfbr.skillScore,
            fbr.speechAceJobWorked,
            COALESCE(fbr.updatedAt, pd.updateAt, isc.firstScheduleDate) AS profileUpdateDate,
            CASE
            when pd.updateAt is not null then pd.updateAt
            else isc.recruiterScheduleDate
            END AS signUpDate,
            CASE
            WHEN fbr.interviewId IS NOT NULL
            AND fbr.interviewSessionId IS NOT NULL
            AND fbr.candidateId IS NOT NULL THEN CONCAT( '/review?i=', fbr.interviewId, '&c=', fbr.candidateId, '&s=', fbr.interviewSessionId )
            WHEN isc.candidate_id IS NOT NULL
            AND isc.preinterviewid IS NOT NULL THEN CONCAT('/review?c=', isc.candidate_id, '&prId=', isc.preinterviewid)
            WHEN isc.emailId IS NOT NULL
            AND isc.preinterviewid IS NOT NULL THEN CONCAT('/review?eId=', isc.emailId, '&prId=', isc.preinterviewid)
            ELSE ''
            END AS url,
            case
            when pr.interviewName is null then ac.name
            else pr.interviewName
            end as interview_name,
            pp1.fieldValue as companyNoticePeriod,
            pp2.fieldValue as companySalaryRange,
            loc.cityName as companyJobLocation,
            pp4.fieldValue as companyWorkExperience,
            (
            SELECT
            l.cityName
            from
            locations l
            where
            l.id = COALESCE(pd.currentLocation, isc.currentLocation)) as currLocation,
            pr.interviewType as preInterviewType,
            isc.apmDashId,
            isc.comment
            FROM
                        (
            select
            interviewSchedule.submissionFlag,
            interviewSchedule.outstationDeclaration,
            interviewSchedule.apm,
            interviewSchedule.apmStatus,
            interviewSchedule.id as iId,
            interviewSchedule.preInterviewId as preInterviewId,
            interviewSchedule.interviewId,
            candidate_id,
            interviewSchedule.firstScheduleDate,
            interviewSchedule.candidateStatusDate,
            interviewSchedule.scheduleTime,
            interviewSchedule.emailId,
            interviewSchedule.mobileNumber,
            interviewSchedule.recruiterScheduleDate,
            interviewSchedule.candidateName,
            interviewSchedule.candidateStatus,
            interviewSchedule.currentCompany,
            interviewSchedule.expectedSalary,
            interviewSchedule.currentSalary,
            interviewSchedule.noticePeriod,
            interviewSchedule.currentLocation,
            interviewSchedule.promotionSource,
            interviewSchedule.resume,
            interviewSchedule.workExperience,
            interviewSchedule.recruiterId,
            interviewSchedule.employmentStatus,
            interviewSchedule.skillValues,
            interviewSchedule.offer,
            interviewSchedule.offeredCTC,
            interviewSchedule.verifyFlag,
            interviewSchedule.apmDashId,
            interviewSchedule.comment
            FROM
            interviewSchedule
            left join feedback_request on
            interviewSchedule.candidate_id = feedback_request.candidateId and interviewSchedule.preInterviewId = feedback_request.preInterviewId
            " . $interviewname . "
            Group by
            interviewSchedule.emailId,
            interviewSchedule.interviewId,
            interviewSchedule.apmDashId
            ORDER BY
			CASE 
			    WHEN interviewSchedule.candidateStatus IN ('Profile Match', 'Interview Scheduled') THEN 1
			    WHEN interviewSchedule.candidateStatus IS NOT NULL AND interviewSchedule.candidateStatus <> 'Profile Mismatch' THEN 2
			    ELSE 3
			END,
            CASE 
                WHEN feedback_request.review_status = 2 THEN 1
                ELSE 0
            END DESC,
            COALESCE(interviewSchedule.interviewId IS NOT NULL, 0) DESC,
            COALESCE(feedback_request.review_status IS NOT NULL, 0) DESC,
            COALESCE(feedback_request.review_status, interviewSchedule.id) DESC ) isc
            LEFT JOIN professionaldetails pd ON
            pd.candidateId = isc.candidate_id
            LEFT JOIN feedback_request fbr ON
            isc.candidate_id = fbr.candidateId and isc.preInterviewId = fbr.preInterviewId
            LEFT JOIN preInterview pr ON
            isc.preInterviewId = pr.id
            LEFT JOIN aspiration_company ac ON
            pr.company_id = ac.id
            LEFT JOIN interview i ON
            fbr.interviewId = i.id
            left join candidate_interview_transection cit on
            fbr.candidateId = cit.candidateId
            and fbr.interviewId = cit.interviewId
            LEFT JOIN newFeedbackReport nfbr ON
                            nfbr.interviewId = i.id
            and nfbr.key_skill_id = 1
            AND nfbr.id = (
            select
            MAX(id)
            from
            newFeedbackReport
            where 
                            skillScore in(
            SELECT
                MAX(skillScore)
            FROM
                newFeedbackReport
            WHERE
                interviewId = i.id
                AND key_skill_id = 1)
            and interviewId = i.id
            AND key_skill_id = 1
                        )
            LEFT JOIN profilePreferences pp1 ON
            pp1.preInterviewId = pr.id
            and pp1.fieldName = 'noticePeriod'
            LEFT JOIN profilePreferences pp2 ON
            pp2.preInterviewId = pr.id
            and pp2.fieldName = 'currentSalary'
            LEFT JOIN profilePreferences pp3 ON
            pp3.preInterviewId = pr.id
            and pp3.fieldName = 'currentLocation'
            LEFT JOIN locations loc ON
            loc.id = pp3.fieldValue
            LEFT JOIN profilePreferences pp4 ON
            pp4.preInterviewId = pr.id
            and pp4.fieldName = 'workExperience'
            where
            1 " . $archiveQry . "
            GROUP BY
            isc.emailId, isc.apmDashId ) as t
            WHERE
            1 " . $filterQry . " " . $having_query . " " . $condition1 . " " . $condition2 . " " . $condition3 . " " . $condition4 . " " . $condition5 . " " . $condition6 . " " . $condition7 . " " . $condition8 . "
            GROUP BY
                scheduleEmail
            ORDER BY
            intScore desc,
            CASE
                suitability_function
            WHEN 'Must meet' THEN 1
            WHEN 'Recommended to meet' THEN 2
            WHEN 'Do not meet' THEN 3
            ELSE 4
            END,
            apmDashId desc,
            intId DESC";

        // iId2
        // removed on count issue service report  and (interviewStatus not IN ('Job Invited') or interviewStatus is null ) 
        $data = $query . $limit_query;
        // echo $data;
                    // exit();
        $result = mysqli_query($databaseConnection, $data);
        $values = array();

        if (mysqli_num_rows($result) > 0) {
            while ($row = mysqli_fetch_assoc($result)) {

                $intId = $row['intId'];
                $fbrId = $row['fbr_id'];
                $preId = $row['preInterviewId'];
                $candidate_Id = $row['id'];
                $workExperenceMinMax = $row['companyWorkExperience'];

                if ($intId != null && $intId != '') {
                    $skillScore = skillWiseScore($databaseConnection, $intId);
                    //$technicalsubjects1=array($skillScore);
                    $row['technicalsubjectsScore'] = $skillScore;

                } else {
                    $row['technicalsubjectsScore'] = null;
                }

                // Prepare SQL statement to fetch candidate skills
                $sql = "SELECT skillId, name, yoe, projectDetails FROM candidate_skills WHERE emailId = ?";
                $stmt = $databaseConnection->prepare($sql);
                $stmt->bind_param("s", $row['emailId']);
                $stmt->execute();
                $result1 = $stmt->get_result();

                // Fetch results and store skillId along with yoe and projectDetails
                $candidateSkillsArray = [];
                while ($row1 = $result1->fetch_assoc()) {
                    $candidateSkillsArray[$row1['skillId']] = [
                        'name' => $row1['name'],
                        'yoe' => $row1['yoe'],
                        'projectDetails' => $row1['projectDetails']
                    ];
                }

                // Old skills (previously stored as a string)
                $candidateSkills2 = $row['skills'];

                $jobSkills = $row['ultraMandatorySkill'];

                // Convert jobSkills from a comma-separated string to an array
                $jobSkillsArray = (!empty($jobSkills)) ? array_map('trim', explode(',', $jobSkills)) : [];

                // Prepare an array to store matching skills with additional details
                $matchingSkillsArr = [];

                // Find the matching skills and get their details
                foreach ($jobSkillsArray as $jobSkill) {
                    if (isset($candidateSkillsArray[$jobSkill])) {
                        $matchingSkillsArr[] = [
                            'skillId' => $jobSkill,
                            'name' => $candidateSkillsArray[$jobSkill]['name'],
                            'yoe' => $candidateSkillsArray[$jobSkill]['yoe'],
                            'projectDetails' => $candidateSkillsArray[$jobSkill]['projectDetails']
                        ];
                    }
                }

                // Add to row data
                $row['matchingSkillsArr'] = $matchingSkillsArr;

                // Calculate the number of jobSkills
                $totalJobSkills = count($jobSkillsArray);
                $matchingSkillsCount = count($matchingSkillsArr);

                $row['skillMatchCount'] = $matchingSkillsCount;

                // Output the ratio as a fraction
                $row['skillMatchRatio'] = "{$matchingSkillsCount}/{$totalJobSkills}";

                $row['skillMatchPer'] = ($totalJobSkills > 0) ? ($matchingSkillsCount / $totalJobSkills) * 100 : 0;

                // Get matching skill IDs as a comma-separated string
                $matchingSkillsIds = implode(',', array_column($matchingSkillsArr, 'skillId'));

                if (!empty($matchingSkillsIds)) {
                    $matchSkillsStringQuery = "SELECT GROUP_CONCAT(fs.favourite_subject SEPARATOR ', ') AS skillNames
                                FROM favourite_subject fs
                                WHERE FIND_IN_SET(fs.id, '$matchingSkillsIds') > 0";
                    $matchSkillsString = mysqli_query($databaseConnection, $matchSkillsStringQuery);

                    if ($matchSkillsString && mysqli_num_rows($matchSkillsString) > 0) {
                        $matchSkillsStringResult = mysqli_fetch_assoc($matchSkillsString);
                        $row['matchSkillNames'] = $matchSkillsStringResult['skillNames'] ?? '';
                    } else {
                        $row['matchSkillNames'] = '';
                    }
                } else {
                    $row['matchSkillNames'] = '';
                }



                $jobLocations = mysqli_query($databaseConnection, "SELECT GROUP_CONCAT(l.cityName SEPARATOR ', ') AS cityNames
                         FROM profilePreferences p
                         JOIN locations l ON FIND_IN_SET(l.id, REPLACE(p.fieldValue, ' ', ''))
                         WHERE p.fieldName = 'currentLocation' AND p.preInterviewId =" . $preId . ";");

                if (mysqli_num_rows($jobLocations) > 0) {
                    $jobLocationsResult = mysqli_fetch_assoc($jobLocations);
                    $row['jobLocationsString'] = $jobLocationsResult['cityNames'];
                }

                // Remove non-numeric characters at the end
                $workExperenceMinMax1 = preg_replace('/\D+$/', '', $workExperenceMinMax);

                // Split the string into min and max values
                $ranges = explode('-', $workExperenceMinMax1);

                if (count($ranges) === 1) {
                    // If there's only one element, set $minLimit to 0 and $maxLimit to the integer value of the single element
                    $minLimit = 0;
                    $maxLimit = (int) $ranges[0];
                } else {
                    // Convert the values to integers
                    $minLimit = (int) $ranges[0];
                    $maxLimit = (int) $ranges[1];
                }


                //Shrikant added : 27/2/2024
                // Calculate average score
                if ($intId !== null) {
                    $avgScore = '';
                    // $techSpeaking = mysqli_query($databaseConnection, "SELECT  AVG(er.overallRating) AS score FROM expert_review er INNER JOIN questions q ON er.questionId = q.id WHERE q.subjectId != 178 AND FIND_IN_SET('1', q.key_skill_id) > 0 and  er.overallRating != 'videoIssue' and er.overallRating != 2 and er.interviewId=" . $intId . ";");

                    $techSpeaking = mysqli_query($databaseConnection, "SELECT MAX(er.overallRating) AS score FROM expert_review er INNER JOIN questions q ON er.questionId = q.id WHERE FIND_IN_SET('1', q.key_skill_id) > 0 and  er.overallRating != 'videoIssue' and er.interviewId=" . $intId . ";");

                    // echo $techSpeaking;
                    // exit();

                    if (mysqli_num_rows($techSpeaking) > 0) {
                        $techScoreQueryResult = mysqli_fetch_assoc($techSpeaking);
                        $avgScore = $techScoreQueryResult['score'];
                    }

                    $row['technicalSpeakingScore'] = '';
                    if ($avgScore >= 0 && $avgScore != '' && $avgScore != NULL) {
                        $row['technicalSpeakingScore'] = $avgScore;
                    }

                    $malpracticeCount = mysqli_query($databaseConnection, " SELECT  SUM(CASE  WHEN erod.observationValueId IN (308, 442, 443) THEN 1 ELSE 0 END) AS malpractcount, SUM(CASE WHEN erod.observationValueId IN (447) THEN 1 ELSE 0 END) AS goodcount FROM  expert_review er  INNER JOIN expert_review_observation_details erod ON erod.expertReviewId = er.id WHERE  erod.observationValueId IN (308,442,443,447)  AND er.feedback_request_id = '" . $fbrId . "' ;");

                    $respondedCount = mysqli_query($databaseConnection, "select mergeId from mergedVideos where interviewId='" . $intId . "';");


                    $malpracticeRes = mysqli_fetch_assoc($malpracticeCount);
                    $respondedRes = mysqli_fetch_assoc($respondedCount);

                    // if (mysqli_num_rows($malpracticeCount) > 0) {
                    // $row['malpractcount'] = $malpracticeRes['malpractcount'];
                    // }else{
                    //     $row['malpractcount'] = '';
                    // }
                    if (mysqli_num_rows($malpracticeCount) > 0 && mysqli_num_rows($respondedCount) > 0) {
                        $malpractcount = $malpracticeRes['malpractcount'];
                        $goodcount = $malpracticeRes['goodcount'];
                        $mergeIdCount = mysqli_num_rows($respondedCount);

                        if ($goodcount == $mergeIdCount) {

                            $row['malpractcount'] = 0;
                        } else {
                            $row['malpractcount'] = $malpractcount;
                        }
                    } else {
                        $row['malpractcount'] = '';
                    }

                } else {
                    $row['malpractcount'] = '';
                    $row['technicalSpeakingScore'] = '';
                }


                // $denomCount = mysqli_query($databaseConnection,"SELECT COUNT(DISTINCT subquery.interviewId) as denom FROM (SELECT fr.interviewId FROM feedback_request fr WHERE fr.interviewId IN (SELECT id FROM interview WHERE preInterviewId =  '" .  $preId . "' )) AS subquery;");
                $denomCount = mysqli_query($databaseConnection, "SELECT COUNT(fr.interviewId) as denom FROM feedback_request fr INNER JOIN interview i ON i.id = fr.interviewId INNER JOIN interviewSchedule isc ON i.id = isc.interviewId AND i.preInterviewId = isc.preInterviewId INNER JOIN preInterview pr ON pr.id = isc.preInterviewId 
                WHERE pr.interviewType != 'Practice' AND fr.review_status = 2 AND fr.intScore >= 0 
                AND isc.workExperience BETWEEN '" . $minLimit . "' AND '" . $maxLimit . "'");

                $denomRes = mysqli_fetch_assoc($denomCount);

                if (mysqli_num_rows($denomCount) > 0) {
                    $row['denominator_percentile'] = $denomRes['denom'];
                }



                $PracticeCount = mysqli_query($databaseConnection, "SELECT COUNT(CASE WHEN sq.review_status IN (2, 3) THEN 1 ELSE NULL END) AS completed, COUNT(CASE WHEN sq.review_status NOT IN (2, 3) THEN 1 ELSE NULL END) AS attempted FROM ( SELECT DISTINCT fr.review_status, m.interviewId FROM mergedVideos m INNER JOIN interview i ON m.interviewId = i.id INNER JOIN feedback_request fr ON fr.candidateId = m.candidateId AND fr.interviewSessionId = m.interviewSessionId INNER JOIN interviewSchedule isc ON isc.candidate_id = m.candidateId AND isc.interviewId = m.interviewId WHERE m.candidateId = '$candidate_Id' AND i.preInterviewId IN ( SELECT cim.preInterviewId FROM candidateInterviewMapping cim WHERE cim.candidateId = '$candidate_Id' AND cim.preInterviewId IN ( SELECT practicePreInterviewId FROM jobPracticeMapping WHERE jobPreInterviewId = '$preId' ))) AS sq;");

                $PracticeCountRes = mysqli_fetch_assoc($PracticeCount);

                if (mysqli_num_rows($PracticeCount) > 0) {
                    $row['practiceCount'] = ($PracticeCountRes['completed'] == 0) ? '' : $PracticeCountRes['completed'];
                    $row['practiceAttempted'] = $PracticeCountRes['attempted'];
                } else {
                    $row['practiceCount'] = '';
                    $row['practiceAttempted'] = '';
                }

                $assignedSql = "select id from candidateInterviewMapping where candidateId=" . $candidate_Id . " and preInterviewId IN ( SELECT practicePreInterviewId FROM jobPracticeMapping
            WHERE jobPreInterviewId = " . $preId . " ) ";

                $assigned_query = mysqli_query($databaseConnection, $assignedSql);

                if ($assigned_query) {
                    $row['practiceAssigned'] = mysqli_num_rows($assigned_query);

                } else {
                    $row['practiceAssigned'] = '';
                }

                if ($row['practiceCount'] >= 10) {
                    $row['practiceStatus'] = 'Practice Completed';
                } elseif ($row['practiceCount'] >= 1) {
                    $row['practiceStatus'] = 'Practice InProgress';
                } elseif ($row['practiceAttempted'] > 0) {
                    $row['practiceStatus'] = 'Practice Initiated';
                } elseif ($row['practiceAssigned'] > 0) {
                    $row['practiceStatus'] = 'Practice Assigned';
                } else {
                    $row['practiceStatus'] = '';
                }

                $values[] = $row;
                // array_push($values,$row);
            }

        }

        if ($values > 0) {
            // $values=mysqli_fetch_all($result,MYSQLI_ASSOC);
            // Get the total count using a separate count query
            $queryTotalCount = "SELECT COUNT(isc2.iId) as total_count FROM ( SELECT MAX(isc.id) as iId, isc.preInterviewId, isc.interviewId, candidate_id, candidateStatus, candidateStatusDate, scheduleTime, emailId, mobileNumber, recruiterScheduleDate, candidateName FROM interviewSchedule isc left join interview i on isc.preInterviewId = i.preInterviewId left join feedback_request fbr on i.id = fbr.interviewId WHERE isc.preInterviewId in('" . $interviewnameString . "') and fbr.review_status = 2 and isc.interviewId IS NOT NULL " . $having_query . " " . $condition1 . " " . $condition2 . " " . $condition3 . "  " . $condition4 . " " . $condition5 . " " . $condition6 . "" . $condition7 . " GROUP BY emailId, preInterviewId ) AS isc2 ";
            // echo $queryTotalCount;
            // $resultTotalCount = mysqli_query($databaseConnection, $queryTotalCount);
            // $totalCount = mysqli_fetch_assoc($resultTotalCount)['total_count'];
            $resultTotalCount = mysqli_query($databaseConnection, $query);
            $totalCount = mysqli_num_rows($resultTotalCount);

            $total_data['data'] = $values;
            $total_data['count'] = $totalCount;
            $to_encode = $total_data;
        }


        // $result = mysqli_query($databaseConnection,$data);
        // $num_rows = mysqli_num_rows($result);

        // if($num_rows >0) {
        //     $values=mysqli_fetch_all($result,MYSQLI_ASSOC);
        //     // Get the total count using a separate count query
        //     $queryTotalCount = "SELECT COUNT(isc2.iId) as total_count FROM ( SELECT MAX(isc.id) as iId, isc.preInterviewId, isc.interviewId, candidate_id, candidateStatus, candidateStatusDate, scheduleTime, emailId, mobileNumber, recruiterScheduleDate, candidateName FROM interviewSchedule isc left join interview i on isc.preInterviewId = i.preInterviewId left join feedback_request fbr on i.id = fbr.interviewId WHERE isc.preInterviewId in('".$json['interviewname']."') and fbr.review_status = 2 and isc.interviewId IS NOT NULL ".$having_query." ".$condition1." ".$condition2." ".$condition3." GROUP BY emailId, preInterviewId ) AS isc2 ";
        //     // echo $queryTotalCount;
        //     // $resultTotalCount = mysqli_query($databaseConnection, $queryTotalCount);
        //     // $totalCount = mysqli_fetch_assoc($resultTotalCount)['total_count'];
        //     $resultTotalCount = mysqli_query($databaseConnection, $query);
        //     $totalCount = mysqli_num_rows($resultTotalCount);

        //     $total_data['data'] = $values;
        //     $total_data['count'] = $totalCount;
        //     $to_encode = $total_data;
        // }
        else {
            $to_encode = array(
                'status' => 0,
                'data' => 'Error While fetching' . mysqli_error($databaseConnection)
            );
        }
    } else {
        $to_encode = array(
            'data' => $values,
            'status' => 1
        );
    }
    echo json_encode($to_encode);
}
else if (isset($_GET['getServiceDashboardnew2'])) {
    // This API is used to fetch the data for IAS Assessment Dashboard (Service Dashboard)

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (is_array($json)) {
        $userType = strtolower(trim((string) ($json['userType'] ?? '')));
        $userId = filter_var($json['userId'] ?? null, FILTER_VALIDATE_INT);

        if (!$userId || !in_array($userType, ['admin', 'corporate'], true)) {
            echo json_encode(array("status" => 0, "result" => "error", "message" => "Unauthorized access"));
            exit();
        }

        $userAccessResult = mysqli_query(
            $databaseConnection,
            "SELECT id FROM users WHERE id = " . (int) $userId . " AND usertype = '" . $userType . "' AND active = 'Y' LIMIT 1"
        );
        if (!$userAccessResult || mysqli_num_rows($userAccessResult) !== 1) {
            echo json_encode(array("status" => 0, "result" => "error", "message" => "Unauthorized access"));
            exit();
        }

        $page = max(1, (int) ($json['page'] ?? 1));
        $requestedLimit = (int) ($json['limit'] ?? 10);
        $limit = $requestedLimit > 0 ? min($requestedLimit, 100) : 10;
        $start = ($page - 1) * $limit;
        $archiveflag = !empty($json['archiveflag']) ? 1 : 0;

        $whereConditions = array(
            "pr.interviewType = 'job'",
            "pr.serviceType = 'IAS'",
            "LOWER(TRIM(COALESCE(isc.`access`, ''))) = 'i'"
        );

        if ($archiveflag === 0) {
            $whereConditions[] = "LOWER(TRIM(COALESCE(pr.interviewStatus, ''))) = 'active'";
        }

        $interviewNames = $json['interviewname'] ?? array();
        if (!is_array($interviewNames)) {
            $interviewNames = array($interviewNames);
        }
        $jobIds = array();
        foreach ($interviewNames as $interviewName) {
            if (ctype_digit((string) $interviewName) && (int) $interviewName > 0) {
                $jobIds[] = (int) $interviewName;
            }
        }
        if (!empty($jobIds)) {
            $whereConditions[] = "isc.preInterviewId IN (" . implode(',', array_unique($jobIds)) . ")";
        }

        $candidateSearch = trim((string) ($json['candidate_search'] ?? ''));
        if ($candidateSearch !== '') {
            $escapedSearch = mysqli_real_escape_string($databaseConnection, $candidateSearch);
            if (preg_match('/^[0-9]{10}$/', $candidateSearch)) {
                $whereConditions[] = "isc.mobileNumber = '" . $escapedSearch . "'";
            } else if (filter_var($candidateSearch, FILTER_VALIDATE_EMAIL)) {
                $whereConditions[] = "isc.emailId = '" . $escapedSearch . "'";
            } else if (preg_match('/^[0-9]{1,10}$/', $candidateSearch)) {
                $whereConditions[] = "isc.candidate_id = " . (int) $candidateSearch;
            } else {
                $whereConditions[] = "isc.candidateName LIKE '%" . $escapedSearch . "%'";
            }
        }

        $requestedStatuses = $json['candidateInterviewStatus'] ?? array();
        if (!is_array($requestedStatuses)) {
            $requestedStatuses = array($requestedStatuses);
        }
        $statusConditions = array();
        foreach ($requestedStatuses as $status) {
            if ($status === 'Completed') {
                $statusConditions[] = "fbr.review_status = 2";
            } else if ($status === 'In-Progress') {
                $statusConditions[] = "fbr.review_status = 1";
            } else if ($status === 'Incomplete') {
                $statusConditions[] = "fbr.review_status = -4";
            }
        }
        if (!empty($statusConditions)) {
            $whereConditions[] = '(' . implode(' OR ', array_unique($statusConditions)) . ')';
        }

        if ($userType === 'corporate') {
            $whereConditions[] = "EXISTS (
                SELECT 1
                FROM preInterview_corporate pic
                WHERE pic.preinterviewId = isc.preInterviewId
                  AND pic.userId = " . (int) $userId . "
            )";
        }

        $whereQuery = implode("\n    AND ", $whereConditions);
        $baseFromQuery = "FROM interviewSchedule isc
            INNER JOIN (
                SELECT
                    MAX(id) AS id
                FROM interviewSchedule
                GROUP BY
                    preInterviewId,
                    CASE
                        WHEN candidate_id IS NOT NULL THEN CONCAT('candidate:', candidate_id)
                        WHEN emailId IS NOT NULL AND emailId != '' THEN CONCAT('email:', LOWER(TRIM(emailId)))
                        ELSE CONCAT('schedule:', id)
                    END
            ) latest_isc ON latest_isc.id = isc.id
            INNER JOIN preInterview pr
                ON pr.id = isc.preInterviewId
            LEFT JOIN (
                SELECT
                    candidateId,
                    preInterviewId,
                    MAX(id) AS id
                FROM feedback_request
                GROUP BY
                    candidateId,
                    preInterviewId
            ) latest_fbr
                ON latest_fbr.candidateId = isc.candidate_id
            AND latest_fbr.preInterviewId = isc.preInterviewId
            LEFT JOIN feedback_request fbr
                ON fbr.id = latest_fbr.id";

                    $query = "SELECT
                isc.candidateName,
                isc.emailId AS contactEmail,
                isc.mobileNumber AS phoneNumber,
                fbr.suitability,
                CASE
                    WHEN fbr.review_status = 2 THEN COALESCE(mv.genuineCount, 0)
                    ELSE 0
                END AS genuineCount,
                CASE
                    WHEN fbr.review_status = 2 THEN COALESCE(mv.suspiciousCount, 0)
                    ELSE 0
                END AS suspiciousCount,
                CASE
                    WHEN fbr.review_status = 2 THEN COALESCE(mv.malpracticeCount, 0)
                    ELSE 0
                END AS malpracticeCount,
                CASE
                    WHEN fbr.review_status = 2 THEN 'Completed'
                    WHEN fbr.review_status = 1 THEN 'In-Progress'
                    WHEN fbr.review_status = -4 THEN 'Incomplete'
                    ELSE ''
                END AS intStatus,
                fbr.intScore,
                fbr.reportpdf2 AS report,
                CASE
                    WHEN fbr.interviewId IS NOT NULL
                        AND fbr.interviewSessionId IS NOT NULL
                        AND fbr.candidateId IS NOT NULL
                    THEN CONCAT('/review?i=', fbr.interviewId, '&c=', fbr.candidateId, '&s=', fbr.interviewSessionId)
                    ELSE ''
                END AS url,
                isc.candidate_id AS candidateId,
                isc.id AS interviewScheduleId,
                isc.id,
                fbr.interviewId AS intId,
                fbr.id AS fbr_id,
                isc.preInterviewId,
                isc.apmDashId,
                'N/A' AS percentile_function
            " . $baseFromQuery . "
            LEFT JOIN (
                SELECT interviewSessionId,
                    SUM(CASE WHEN malpracticeValue = 'GENUINE' THEN 1 ELSE 0 END) AS genuineCount,
                    SUM(CASE WHEN malpracticeValue = 'SUSPICIOUS' THEN 1 ELSE 0 END) AS suspiciousCount,
                    SUM(CASE WHEN malpracticeValue = 'MALPRACTICE' THEN 1 ELSE 0 END) AS malpracticeCount
                FROM mergedVideos
                WHERE malpracticeValue IS NOT NULL
                GROUP BY interviewSessionId
            ) mv ON mv.interviewSessionId = fbr.interviewSessionId
            WHERE " . $whereQuery . "
            ORDER BY
                fbr.intScore DESC,
                isc.apmDashId DESC,
                fbr.interviewId DESC,
                isc.id DESC
            LIMIT " . $start . ", " . $limit;

        $countQuery = "SELECT COUNT(*) AS totalCount
        " . $baseFromQuery . "
        WHERE " . $whereQuery;
        $countResult = mysqli_query($databaseConnection, $countQuery);
        if (!$countResult) {
            echo json_encode(['status' => 0, 'data' => 'err', 'error' => mysqli_error($databaseConnection)]);
            exit;
        }
        $countRow = mysqli_fetch_assoc($countResult);
        $totalCount = (int) ($countRow['totalCount'] ?? 0);

        $data = $query;
        $result = mysqli_query($databaseConnection, $data);
        if (!$result) {
            echo json_encode(['status' => 0, 'data' => 'err', 'error' => mysqli_error($databaseConnection)]);
            exit;
        }
        $values = array();

        if (mysqli_num_rows($result) > 0) {
            $values = mysqli_fetch_all($result, MYSQLI_ASSOC);
        }

        // Attach job screening answers for the visible dashboard rows.
        $screeningPreInterviewIds = array();
        $screeningCandidateIds = array();
        foreach ($values as $row) {
            if (isset($row['preInterviewId']) && is_numeric($row['preInterviewId'])) {
                $screeningPreInterviewIds[] = (int) $row['preInterviewId'];
            }
            if (isset($row['candidateId']) && is_numeric($row['candidateId'])) {
                $screeningCandidateIds[] = (int) $row['candidateId'];
            }
        }

        $screeningAnswersByCandidateJob = array();
        $screeningPreInterviewIds = array_values(array_unique(array_filter($screeningPreInterviewIds)));
        $screeningCandidateIds = array_values(array_unique(array_filter($screeningCandidateIds)));

        if (!empty($screeningPreInterviewIds) && !empty($screeningCandidateIds)) {
            $screeningAnswersQuery = "
                SELECT
                    q.preInterviewId,
                    q.id AS questionId,
                    q.questionText,
                    q.questionType,
                    q.sortOrder,
                    a.candidateId,
                    a.answerText
                FROM jobScreeningQuestions q
                INNER JOIN jobScreeningAnswers a
                    ON a.preInterviewId = q.preInterviewId
                    AND a.scrnQuestionId = q.id
                WHERE q.preInterviewId IN (" . implode(',', $screeningPreInterviewIds) . ")
                    AND a.candidateId IN (" . implode(',', $screeningCandidateIds) . ")
                    AND (q.isActive IS NULL OR q.isActive = 'Y')
                    AND a.answerText IS NOT NULL
                    AND TRIM(a.answerText) != ''
                ORDER BY q.preInterviewId ASC, a.candidateId ASC, q.sortOrder ASC, q.id ASC";
            $screeningAnswersResult = mysqli_query($databaseConnection, $screeningAnswersQuery);

            if ($screeningAnswersResult) {
                while ($screeningAnswer = mysqli_fetch_assoc($screeningAnswersResult)) {
                    $screeningKey = $screeningAnswer['preInterviewId'] . '_' . $screeningAnswer['candidateId'];
                    if (!isset($screeningAnswersByCandidateJob[$screeningKey])) {
                        $screeningAnswersByCandidateJob[$screeningKey] = array();
                    }
                    $screeningAnswersByCandidateJob[$screeningKey][] = array(
                        'questionId' => $screeningAnswer['questionId'],
                        'questionText' => $screeningAnswer['questionText'],
                        'questionType' => $screeningAnswer['questionType'],
                        'sortOrder' => $screeningAnswer['sortOrder'],
                        'answerText' => $screeningAnswer['answerText']
                    );
                }
            }
        }

        foreach ($values as &$row) {
            $screeningKey = (isset($row['preInterviewId']) ? $row['preInterviewId'] : '') . '_' . (isset($row['candidateId']) ? $row['candidateId'] : '');
            $row['jobScreeningAnswers'] = isset($screeningAnswersByCandidateJob[$screeningKey])
                ? $screeningAnswersByCandidateJob[$screeningKey]
                : array();
        }
        unset($row);
        
        // --- Batched applicantPercentile Calculation ---
        // Calculate repeated score/job pairs once to avoid row-by-row SQL execution overhead.
        $uniquePairs = [];
        foreach ($values as $row) {
            if ($row['percentile_function'] === 'N/A' && is_numeric($row['preInterviewId']) && is_numeric($row['intScore']) && $row['intScore'] != -1) {
                $preId = (int) $row['preInterviewId'];
                $score = (float) $row['intScore'];
                $pairKey = $preId . '_' . $score;
                $uniquePairs[$pairKey] = [
                    'preId' => $preId,
                    'score' => $score
                ];
            }
        }
        
        $percentileMap = [];
        if (!empty($uniquePairs)) {
            $chunks = array_chunk($uniquePairs, 100);
            foreach ($chunks as $chunk) {
                $cases = [];
                foreach ($chunk as $pair) {
                    $cases[] = "SELECT " . $pair['preId'] . " AS preId, " . $pair['score'] . " AS score, applicantPercentile(" . $pair['score'] . ", " . $pair['preId'] . ") AS pct";
                }
                $pctQuery = implode(" UNION ALL ", $cases);
                $pctResult = mysqli_query($databaseConnection, $pctQuery);
                if ($pctResult) {
                    while ($pRow = mysqli_fetch_assoc($pctResult)) {
                        $percentileMap[$pRow['preId'] . '_' . $pRow['score']] = $pRow['pct'];
                    }
                }
            }
        }

        foreach ($values as &$row) {
            if ($row['percentile_function'] === 'N/A' && is_numeric($row['preInterviewId']) && is_numeric($row['intScore']) && $row['intScore'] != -1) {
                $pairKey = (int) $row['preInterviewId'] . '_' . (float) $row['intScore'];
                if (isset($percentileMap[$pairKey])) {
                    $row['percentile_function'] = $percentileMap[$pairKey];
                }
            }
        }
        // --- End Batched Calculation ---

        $total_data['data'] = $values;
        $total_data['count'] = $totalCount;
        $to_encode = $total_data;
    } else {
        $to_encode = array(
            'data' => [],
            'status' => 1
        );
    }
    echo json_encode($to_encode);
}
else if (isset($_GET['getServiceDashboardFilters'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $values = array();

        if ($json['userType'] == 'corporate') {

            $filter1_sql = "SELECT pr.id, COALESCE(pr.interviewName, ac.name) AS name FROM preInterview pr LEFT JOIN aspiration_company ac ON ac.id = pr.id WHERE pr.id != 0 AND pr.interviewStatus = 'Active' AND (pr.interviewName IS NOT NULL OR ac.name IS NOT NULL) AND pr.id IN (SELECT preinterviewId FROM preInterview_corporate WHERE userId='" . $json['userId'] . "') ORDER BY pr.id DESC";

        } else {

            $filter1_sql = "SELECT pr.id, COALESCE(pr.interviewName, ac.name) AS name FROM preInterview pr LEFT JOIN aspiration_company ac ON ac.id = pr.id WHERE pr.id != 0 AND pr.interviewStatus = 'Active' AND (pr.interviewName IS NOT NULL OR ac.name IS NOT NULL) ORDER BY pr.id DESC";
        }

        $filter1_result = mysqli_query($databaseConnection, $filter1_sql);

        $values['job_list'] = mysqli_fetch_all($filter1_result, MYSQLI_ASSOC);

        $to_encode = array(
            'data' => $values,
            'status' => 1
        );
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving interview information."
        );
    }

    echo json_encode($to_encode);
} else if (isset($_GET['getEmployabilityFilters'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    $userId = $json['userId'];
    $preInterviewId = $json['preInterviewId'];

    //echo  $preInterviewId;
    if (!empty($json['companyId'])) {
        $companyId = $json['companyId'];
    }
    if (!empty($json['sectorId'])) {
        $sectorId = $json['sectorId'];
    }
    if (!empty($json['preInterviewId'])) {
        $preInterviewId = $json['preInterviewId'];
    }

    // updating professionaldetails from interviewSchedule table
    // $workExpField = mysqli_query($databaseConnection, "select workExperience from professionaldetails where candidateId = " . $userId . "");

    $pdUpdateAtField = mysqli_query($databaseConnection, "select updateAt from professionaldetails where candidateId = " . $userId . "");

    if (mysqli_num_rows($pdUpdateAtField) == 1) {
        $pdUpdateAtFieldResult = mysqli_fetch_all($pdUpdateAtField, MYSQLI_ASSOC);

        // if ($pdUpdateAtFieldResult[0]['updateAt'] == null) {

        $scheduleField = mysqli_query($databaseConnection, "select id,emailId,preInterviewId, recruiterScheduleDate, submissionFlag from interviewSchedule where emailId in (select emailId from users where id = " . $userId . " and preInterviewid = " . $preInterviewId . ")");

        if (mysqli_num_rows($scheduleField) >= 1) {
            $scheduleFieldResult = mysqli_fetch_all($scheduleField, MYSQLI_ASSOC);

            $datepd = new DateTime($pdUpdateAtFieldResult[0]['updateAt']);
            $dateis = new DateTime($scheduleFieldResult[0]['recruiterScheduleDate']);

            // Update submissionFlag to 'Y'
            if ($scheduleFieldResult[0]['submissionFlag'] !== null && $scheduleFieldResult[0]['submissionFlag'] === 'WA') {
                $updateQuery = "UPDATE interviewSchedule 
                                    SET submissionFlag = 'Y' ,
                                    candidate_id = " . $userId . "
                                    WHERE id = " . $scheduleFieldResult[0]['id'];

                mysqli_query($databaseConnection, $updateQuery);
            }

            if ($scheduleFieldResult[0]['id'] != null && ($pdUpdateAtFieldResult[0]['updateAt'] == null || ($scheduleFieldResult[0]['recruiterScheduleDate'] != null && $datepd < $dateis))) {
                // prodessionldetails update date is earlier then interviewschedule date

                $updateProfessionaldetails_sql = "UPDATE professionaldetails pd JOIN users u ON u.id = pd.candidateId JOIN interviewSchedule isc ON isc.emailId=u.emailId SET pd.workExperience = isc.workExperience,pd.jobType = isc.jobType,pd.currentCompany = isc.currentCompany,pd.currentProcess = isc.currentProcess,pd.processType = isc.processType,pd.clientType = isc.clientType,pd.salary = isc.currentSalary,pd.expectedSalary = isc.expectedSalary,pd.noticePeriod = isc.noticePeriod,pd.processPreference = isc.processPreference,pd.shift = isc.shift,pd.workLocationPreference = isc.workLocationPreference,pd.timeToCall = isc.timeToCall,pd.preferedJobType = isc.preferedJobType,pd.currentLocation = isc.currentLocation,pd.preferredWorkLocation = isc.preferredWorkLocation,pd.languages = isc.languages,pd.joiningTimeline = isc.joiningTimeline,pd.certifications = isc.certiValues,pd.preferredRole = isc.preferredRole,pd.joinstatus=isc.joinstatus,pd.preferredrole=isc.preferredrole,pd.resume=isc.resume, pd.updateAt=NOW() where u.id = " . $userId . " and isc.preInterviewid = " . $scheduleFieldResult[0]['preInterviewId'] . "";

                // echo $updateProfessionaldetails_sql;

                $updateProfessionaldetails = mysqli_query($databaseConnection, $updateProfessionaldetails_sql);


            }
        }
        // }

    }

    $values = array();
    $filter1 = "SELECT id, cityName FROM locations WHERE ID NOT IN(512,518,513,516,514,515,517,519,525) ORDER BY 
                    CASE 
                    WHEN cityName LIKE '%Any%' THEN 0
                    WHEN cityName LIKE '%Remote%' THEN 1
                    ELSE 2
                    END,
                    cityName ASC";
    $filter1Result = mysqli_query($databaseConnection, $filter1);

    $values['locationList'] = mysqli_fetch_all($filter1Result, MYSQLI_ASSOC);

    // $filter2 = "SELECT cityName as label,id as value FROM locations ORDER BY cityName ASC;";
    // $filter2Result = mysqli_query($databaseConnection,$filter2);

    // $values['locations'] = mysqli_fetch_all($filter2Result,MYSQLI_ASSOC);

    $filter3 = "SELECT id,name from language;";
    $filter3Result = mysqli_query($databaseConnection, $filter3);

    $values['language'] = mysqli_fetch_all($filter3Result, MYSQLI_ASSOC);

    $filter4 = "SELECT * from  relavant_role WHERE active='Y';";
    $filter4Result = mysqli_query($databaseConnection, $filter4);

    $values['subroles'] = mysqli_fetch_all($filter4Result, MYSQLI_ASSOC);

    $candidateSkillsQuery = "
    SELECT * 
    FROM candidate_skills 
    WHERE candidateId = " . $userId . " 
    OR emailId = (SELECT emailId FROM users WHERE id = " . $userId . ");
    ";
    $candidateSkillsResult = mysqli_query($databaseConnection, $candidateSkillsQuery);
    // Check if the query was successful and if there are rows in the result
    if ($candidateSkillsResult && mysqli_num_rows($candidateSkillsResult) > 0) {
        $result['candidateSkills'] = mysqli_fetch_all($candidateSkillsResult, MYSQLI_ASSOC);
    } else {
        // Handle case where no rows are returned
        $result['candidateSkills'] = [];
    }



    $filter6 = "select fieldValue as skills from profilePreferences p where preference='Mandatory' and fieldName='skills' and preInterviewId = " . $preInterviewId . " ";
    $filter6Result = mysqli_query($databaseConnection, $filter6);

    $values['profilepreferences'] = mysqli_fetch_all($filter6Result, MYSQLI_ASSOC);

    $w1 = "select pd.*,u.firstName, u.AVConfirm, u.instituteCode, u.mobileNumber from interviewSchedule isd  inner join users u on u.emailId=isd.emailId left join professionaldetails pd on pd.candidateId=u.id where u.id=" . $userId . " order by isd.id desc limit 1 ";
    $fetchingdata = mysqli_query($databaseConnection, $w1);


    if (mysqli_num_rows($fetchingdata) > 0) {
        $result['candidateDetails'] = mysqli_fetch_all($fetchingdata, MYSQLI_ASSOC);
    } else {
        $fetchingdata = "SELECT pd.*,u.* from users u left join professionaldetails pd on u.id=pd.candidateId where u.id= " . $userId . ";";
        $fetchingdataResult = mysqli_query($databaseConnection, $fetchingdata);
        $result['candidateDetails'] = mysqli_fetch_all($fetchingdataResult, MYSQLI_ASSOC);
    }

    $preferredLocation = "SELECT l.id as value,l.cityName as label from professionaldetails pd inner join locations l on FIND_IN_SET(l.id,pd.preferredWorkLocation) where candidateId= " . $userId . ";";
    $preferredLocationResult = mysqli_query($databaseConnection, $preferredLocation);
    $result['preferredLocation'] = mysqli_fetch_all($preferredLocationResult, MYSQLI_ASSOC);

    // AND interviewId IS NULL
    if (!empty($json['preInterviewId'])) {
        $interviewSchedule = "SELECT isc.*, fr.review_status from interviewSchedule isc left join feedback_request fr on fr.interviewId = isc.interviewId  where isc.emailId in (select emailId from users where id = " . $userId . ") AND isc.preInterviewId = " . $json['preInterviewId'] . "  ORDER BY id DESC;";
        $interviewScheduleResult = mysqli_query($databaseConnection, $interviewSchedule);
        $result['interviewSchedule'] = mysqli_fetch_all($interviewScheduleResult, MYSQLI_ASSOC);

    } else {
        $result['interviewSchedule'] = [];
    }
    if (!empty($json['sectorId'])) {
        $interviewSchedule = "SELECT isc.*, fr.review_status from interviewSchedule isc left join feedback_request fr on fr.interviewId = isc.interviewId  where isc.emailId in (select emailId from users where id = " . $userId . ") AND isc.sectorId = " . $sectorId . ";";
        $interviewScheduleResult = mysqli_query($databaseConnection, $interviewSchedule);
        $result['interviewSchedule'] = mysqli_fetch_all($interviewScheduleResult, MYSQLI_ASSOC);
    }

    $interviewAttempts = "SELECT fr.review_status FROM interviewSchedule isc LEFT JOIN feedback_request fr ON isc.interviewId = fr.interviewId WHERE isc.emailId IN (SELECT emailId FROM users WHERE id = " . $userId . ") AND fr.review_status = '2' AND isc.preInterviewId = " . $preInterviewId . "";
    // echo $interviewAttempts;
    // exit();
    $interviewAttemptsResult = mysqli_query($databaseConnection, $interviewAttempts);
    if ($interviewAttemptsResult) {
        $numberOfRows = mysqli_num_rows($interviewAttemptsResult);
        $result['interviewAttempts'] = $numberOfRows;
    } else {
        // Handle query execution error
        $result['interviewAttempts'] = 0;
    }

    $incompInterviewAttempts = "SELECT fr.review_status FROM feedback_request fr  LEFT JOIN interviewSchedule isc ON isc.candidate_id = fr.candidateId AND isc.preInterviewId = fr.preInterviewId WHERE isc.emailId IN (SELECT emailId FROM users WHERE id = " . $userId . ") AND fr.review_status = '-4' AND isc.preInterviewId = " . $preInterviewId . "";

    // echo $incompInterviewAttempts;

    $incompInterviewAttemptsResult = mysqli_query($databaseConnection, $incompInterviewAttempts);
    if ($incompInterviewAttemptsResult) {
        $numberOfRows = mysqli_num_rows($incompInterviewAttemptsResult);
        $result['incompInterviewAttempts'] = $numberOfRows;
    } else {
        // Handle query execution error
        $result['incompInterviewAttempts'] = 0;
    }


    $noFbInterviewAttempts = "SELECT fr.review_status FROM feedback_request fr  LEFT JOIN interviewSchedule isc ON isc.candidate_id = fr.candidateId AND isc.preInterviewId = fr.preInterviewId WHERE isc.emailId IN (SELECT emailId FROM users WHERE id = " . $userId . ") AND fr.review_status = '-2' AND isc.preInterviewId = " . $preInterviewId . "";

    // echo $incompInterviewAttempts;

    $noFbInterviewAttemptsResult = mysqli_query($databaseConnection, $noFbInterviewAttempts);
    if ($noFbInterviewAttemptsResult) {
        $numberOfRows = mysqli_num_rows($noFbInterviewAttemptsResult);
        $result['noFbInterviewAttempts'] = $numberOfRows;
    } else {
        // Handle query execution error
        $result['noFbInterviewAttempts'] = 0;
    }



    $filter9 = "select * from profilePreferences where preInterviewId = " . $preInterviewId . " ";
    $filter9Result = mysqli_query($databaseConnection, $filter9);

    $values['profilePrefFields'] = mysqli_fetch_all($filter9Result, MYSQLI_ASSOC);

    //added by shrikant : 11/1/2024
    $emailId = '';
    $query10 = "SELECT emailId FROM users WHERE id = '" . $userId . "'";
    $getData = mysqli_query($databaseConnection, $query10);

    if (mysqli_num_rows($getData) > 0) {
        $result10 = mysqli_fetch_assoc($getData);
        $emailId = $result10['emailId'];
    }

    $safePreInterviewId = (int) $preInterviewId;
    $safeUserId = (int) $userId;
    $result['screeningQuestions'] = 'N';
    $result['jobScreeningQuestions'] = array();
    $result['jobScreeningAnswers'] = array();

    if ($safePreInterviewId > 0) {
        $screeningFlagQuery = mysqli_query($databaseConnection, "SELECT screeningQuestions FROM preInterview WHERE id = " . $safePreInterviewId . " LIMIT 1");
        if ($screeningFlagQuery && mysqli_num_rows($screeningFlagQuery) > 0) {
            $screeningFlagRow = mysqli_fetch_assoc($screeningFlagQuery);
            $screeningFlag = isset($screeningFlagRow['screeningQuestions']) && $screeningFlagRow['screeningQuestions'] == 'Y' ? 'Y' : 'N';
            $result['screeningQuestions'] = $screeningFlag;

            if ($screeningFlag == 'Y') {
                $screeningQuestionsQuery = "SELECT id, preInterviewId, questionText, questionType, optionsJson, sortOrder, isActive, createdAt FROM jobScreeningQuestions WHERE preInterviewId = " . $safePreInterviewId . " AND (isActive IS NULL OR isActive = 'Y') ORDER BY sortOrder ASC, id ASC";
                $screeningQuestionsResult = mysqli_query($databaseConnection, $screeningQuestionsQuery);
                if ($screeningQuestionsResult) {
                    $result['jobScreeningQuestions'] = mysqli_fetch_all($screeningQuestionsResult, MYSQLI_ASSOC);
                }

                if ($safeUserId > 0) {
                    $screeningAnswersQuery = "SELECT id, preInterviewId, scrnQuestionId, candidateId, answerText, createdAt, updatedAt FROM jobScreeningAnswers WHERE preInterviewId = " . $safePreInterviewId . " AND candidateId = " . $safeUserId;
                    $screeningAnswersResult = mysqli_query($databaseConnection, $screeningAnswersQuery);
                    if ($screeningAnswersResult) {
                        $result['jobScreeningAnswers'] = mysqli_fetch_all($screeningAnswersResult, MYSQLI_ASSOC);
                    }
                }
            }
        }
    }

    $jSkill = "select jobMatch('$emailId', $preInterviewId) AS jobMatchResult";
    $result1 = mysqli_query($databaseConnection, $jSkill);
    $jobMatchResult = '';
    if ($result1) {
        $resultData = mysqli_fetch_assoc($result1);
        if ($resultData) {
            $jobMatchResult = $resultData['jobMatchResult'];

        }
    }
    $values['jobMatch'] = $jobMatchResult;

    $to_encode = array(
        'data' => $values,
        'data2' => $result,
        'status' => 1
    );
    echo json_encode($to_encode);
} else if (isset($_GET['getEmployabilityFilters1'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);


    $values = array();
    // $filter1 = "SELECT id,cityName FROM locations where id not in (512,518,513,516,514,515,517,519) ORDER BY cityName ASC;";
    // $filter1Result = mysqli_query($databaseConnection,$filter1);

    // $values['locationList'] = mysqli_fetch_all($filter1Result,MYSQLI_ASSOC);

    // $filter2 = "SELECT cityName as label,id as value FROM locations ORDER BY cityName ASC;";
    // $filter2Result = mysqli_query($databaseConnection,$filter2);

    // $values['locations'] = mysqli_fetch_all($filter2Result,MYSQLI_ASSOC);

    $filter3 = "SELECT id,name from language;";
    $filter3Result = mysqli_query($databaseConnection, $filter3);

    $values['language'] = mysqli_fetch_all($filter3Result, MYSQLI_ASSOC);

    $filter4 = "SELECT * from  relavant_role WHERE active='Y'";
    $filter4Result = mysqli_query($databaseConnection, $filter4);

    $values['subroles'] = mysqli_fetch_all($filter4Result, MYSQLI_ASSOC);

    $filter5 = "select *, favourite_subject.favourite_subject as name from favourite_subject where active='Y'";
    $filter5Result = mysqli_query($databaseConnection, $filter5);

    $values['skills'] = mysqli_fetch_all($filter5Result, MYSQLI_ASSOC);

    // $departments_sql = "SELECT * from  departments";
    // $departments = mysqli_query($databaseConnection,$departments_sql);
    // $values['departments'] = mysqli_fetch_all($departments,MYSQLI_ASSOC);

    // $sub_departments_sql = "SELECT * from  sub_departments";
    // $sub_departments = mysqli_query($databaseConnection,$sub_departments_sql);
    // $values['sub_departments'] = mysqli_fetch_all($sub_departments,MYSQLI_ASSOC);

    // $role_dep_sql = "SELECT * from  role_department_subdepartment";
    // $role_dep = mysqli_query($databaseConnection,$role_dep_sql);
    // $values['role_dep'] = mysqli_fetch_all($role_dep,MYSQLI_ASSOC);


    // $values['roles_subject'] = mysqli_fetch_all($filter5Result,MYSQLI_ASSOC);

    //  $filter6 = "select  GROUP_CONCAT(DISTINCT s.skillName) as skills  from 
    //  profilePreferences p left join skills s on FIND_IN_SET(s.id,p.fieldValue) where preference = 'Mandatory' And fieldName='skills' and preInterviewId = " . $preInterviewId . " ";
    //  $filter6="select fieldValue as skills from profilePreferences p where preference='Mandatory' and fieldName='skills' and preInterviewId = " . $preInterviewId . " ";
    //  $filter6Result = mysqli_query($databaseConnection,$filter6);

    //  $values['profilepreferences'] = mysqli_fetch_all($filter6Result,MYSQLI_ASSOC);



    // $w1="select pd.*,u.firstName from interviewSchedule isd  inner join users u on u.emailId=isd.emailId inner join professionaldetails pd on pd.candidateId=u.id where u.id=".$userId." order by isd.id desc limit 1 ";
    // $fetchingdata=mysqli_query($databaseConnection,$w1);


    // if(mysqli_num_rows($fetchingdata)>0){
    //     $result['candidateDetails'] = mysqli_fetch_all($fetchingdata,MYSQLI_ASSOC);
    // }else{
    //     $fetchingdata = "SELECT pd.*,u.firstName from professionaldetails pd left join users u on u.id=pd.candidateId where candidateId= " . $userId . ";";
    //     $fetchingdataResult = mysqli_query($databaseConnection,$fetchingdata);
    //     $result['candidateDetails'] = mysqli_fetch_all($fetchingdataResult,MYSQLI_ASSOC);
    // }

    // $preferredLocation = "SELECT l.id as value,l.cityName as label from professionaldetails pd inner join locations l on FIND_IN_SET(l.id,pd.preferredWorkLocation) where candidateId= " . $userId . ";";
    // $preferredLocationResult = mysqli_query($databaseConnection,$preferredLocation);
    // $result['preferredLocation'] = mysqli_fetch_all($preferredLocationResult,MYSQLI_ASSOC);

    // if(!empty($json['preInterviewId'])){
    // $interviewSchedule = "SELECT * from interviewSchedule where emailId in (select emailId from users where id = " . $userId . ") AND preInterviewId = ".$json['preInterviewId'].";";
    // $interviewScheduleResult = mysqli_query($databaseConnection,$interviewSchedule);
    // $result['interviewSchedule'] = mysqli_fetch_all($interviewScheduleResult,MYSQLI_ASSOC);

    // }else{
    //     $result['interviewSchedule'] =[];
    // }
    // if(!empty($json['sectorId'])){
    //     $interviewSchedule = "SELECT * from interviewSchedule where emailId in (select emailId from users where id = " . $userId . ") AND sectorId = ".$sectorId.";";
    //     $interviewScheduleResult = mysqli_query($databaseConnection,$interviewSchedule);
    //     $result['interviewSchedule'] = mysqli_fetch_all($interviewScheduleResult,MYSQLI_ASSOC);
    // }

    // $filter9="select * from profilePreferences where preInterviewId = " . $preInterviewId . " ";
    // $filter9Result = mysqli_query($databaseConnection,$filter9);

    // $values['profilePrefFields'] = mysqli_fetch_all($filter9Result,MYSQLI_ASSOC);


    $to_encode = array(
        'data' => $values,
        'status' => 1
    );
    echo json_encode($to_encode);
} else if (isset($_GET['registerInfo'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    $roleId = $json['roleId'];
    $subject = $json['subject'];

    $name = $json['name'];
    $phone_number = $json['phone_number'];
    $email = $json['email'];
    $resume = $json['resume'];
    $userId = $json['userId'];

    if (!empty($json['roleId'])) {
        if (is_array($json['roleId'])) {
            $roleId = implode(',', $json['roleId']);
        } else {
            $roleId = $json['roleId'];
        }
    } else {
        $roleId = null;
    }

    if (!empty($json['subject'])) {
        if (is_array($json['subject'])) {
            $subject = implode(',', $json['subject']);
        } else {
            $subject = $json['subject'];
        }
    } else {
        $subject = null;
    }
    if ($json['name'] == '') {
        $name = NULL;
    }

    if ($json['phone_number'] == '') {

        $phone_number = NULL;
    }
    if ($json['email'] == '') {

        $email = NULL;
    }

    if ($json['resume'] == '') {
        $resume = NULL;
    }

    if (!empty($email)) {
        $useId = "SELECT id AS candidateId FROM users WHERE emailId = '" . $email . "'";
        $useIdIdResult = mysqli_query($databaseConnection, $useId);

        if ($useIdIdResult) {
            $row = mysqli_fetch_assoc($useIdIdResult);
            if ($row) {
                $userId = $row['candidateId'];
            }
        }
    }
    if (empty($userId)) {
        if (!empty($phone_number)) {
            $useId1 = "SELECT id AS candidateId FROM users WHERE mobileNumber = '" . $phone_number . "'";
            $useIdIdResult1 = mysqli_query($databaseConnection, $useId1);

            if ($useIdIdResult1) {
                $row1 = mysqli_fetch_assoc($useIdIdResult1);
                if ($row1) {
                    $userId = $row1['candidateId'];
                }
            }
        }
    }
    if (empty($userId)) {
        $userId = NULL;
    }

    // $message = "<p>Dear " . $name . ",</p>

    // <p>Your video resume is not approved. We request you to re-take the video resume interview till you are confident & satisfied. Link: " .$name. "</p>
    // <p>In case you have any doubt , please call us +91-9731107508.</p>
    // <p> Thanks & Regards,<br>GoPrac Team,<br>Bangalore</p>
    // ";dd


    $role_query = mysqli_query($databaseConnection, "select id,Name as role from relavant_role where active ='Y' ");
    $values['roles'] = mysqli_fetch_all($role_query, MYSQLI_ASSOC);


    $sql = "SELECT id, favourite_subject FROM favourite_subject WHERE id IN (" . $subject . ") ";
    $subject_query = mysqli_query($databaseConnection, $sql);
    $subjectResult = mysqli_fetch_all($subject_query, MYSQLI_ASSOC);
    $subjectName = $subjectResult[0]['favourite_subject'];

    $sql1 = "SELECT id, name as roleName FROM relavant_role WHERE id IN (" . $roleId . ") ";
    $role_query = mysqli_query($databaseConnection, $sql1);
    $role_queryResult = mysqli_fetch_all($role_query, MYSQLI_ASSOC);
    $roleName = $role_queryResult[0]['roleName'];


    $topics = null;

    // if ($subject != '' && $subject != null && $subject != '0') {
    //     $sql2 = "SELECT st.preInterviewId from scps_transaction st inner join preInterview pr ON pr.id=st.preInterviewId where pr.interviewType = 'Practice' and st.subject IN (" . $subject . ") group by st.subject";
    //     $subject_query2 = mysqli_query($databaseConnection, $sql2);
    //     if (mysqli_num_rows($subject_query2) > 0) {
    //         $subjectResult2 = mysqli_fetch_all($subject_query2, MYSQLI_ASSOC);

    //         if (!empty($subjectResult2[0]['preInterviewId'])) {
    //             $preId = $subjectResult2[0]['preInterviewId'];
    //         } else {
    //             $preId = '904';
    //         }
    //     } else {
    //         $preId = '904';
    //     }
    // } else {
    //     $preId = '904';
    // }


    if ($subject != '' && $subject != null && $subject != '0') {

        $sql2 = "SELECT cim.preInterviewId from candidateInterviewMapping cim where cim.preInterviewId IS NOT NULL and cim.candidateid = '" . $userId . "' and cim.subject IN (" . $subject . ") order by id desc limit 1";

        // echo $sql2;
        $subject_query2 = mysqli_query($databaseConnection, $sql2);
        if (mysqli_num_rows($subject_query2) > 0) {
            $subjectResult2 = mysqli_fetch_all($subject_query2, MYSQLI_ASSOC);
            $preId = $subjectResult2[0]['preInterviewId'];
        } else {
            $qi = "INSERT INTO preInterview(`company_id`,`roleId`, `interviewLevel`, `interviewType`, `interviewName`, `interviewStartDate`, `interviewExpireDate`,`sectorId`,`productId`,`AdvancedProfileMatch`) VALUES ('0','0', 'Medium', 'Practice', '" . $subjectName . "', CURDATE(), DATE_ADD(CURDATE(), INTERVAL 60 DAY),2,1,'Y')";

            $preInterviewInsert = mysqli_query($databaseConnection, $qi);

            if ($preInterviewInsert) {
                $preInterviewId = mysqli_query($databaseConnection, "SELECT id FROM preInterview ORDER BY id DESC LIMIT 1");
                $preId = mysqli_fetch_assoc($preInterviewId)['id'];

                //1425

                if ($preId) {

                    $topics_query = mysqli_query($databaseConnection, "SELECT GROUP_CONCAT(DISTINCT topic_id ORDER BY topic_id ASC) AS topic_ids
                        FROM questions
                        WHERE deleted_at IS NULL AND subjectId = '" . $subject . "'");

                    $topics = mysqli_fetch_assoc($topics_query)['topic_ids'];


                    $interviewStructure = "INSERT INTO interviewStructure(`companyId`,`sectorId`, `roleId`, `sectionSequence`, `sectionId`, `noOfAnswer`, `noOfSkip`, `depthRequired`, `clusterLevel`,`preInterviewId`) VALUES";

                    $interviewStructure .= "('0','2','" . $roleId . "','2','3','2','2','N','Basic,Average,Advanced','" . $preId . "'),";

                    $interviewStructure .= "('0','2','" . $roleId . "','5','7','0','0','N','Basic,Average,Advanced','" . $preId . "');";

                    $interviewStructureInsert = mysqli_query($databaseConnection, $interviewStructure);


                    $scpsInsertion = mysqli_query($databaseConnection, "INSERT INTO scps_transaction(`company`,`sector`,`position`,`subject`,`coreSubjectSequence`,`priority`,`dropdown`,`preInterviewId`,`subjectType`,`weightage`,`topics`) VALUES ('0','2','0','" . $subject . "','1','1',1,'" . $preId . "','technical','4',NULLIF('" . $topics . "',''))");

                } else {
                    $preId = '904';
                }
            } else {
                $preId = '904';
            }
        }
    } else {
        $preId = '904';
    }


    //      // Map roleId to role names
    // $roleIdsArray = explode(',', $roleId);
    // $roleNames = array_map(function ($roleId) use ($values) {
    //     foreach ($values['roles'] as $role) {
    //         if ($role['id'] == $roleId) {
    //             return $role['role'];
    //         }
    //     }
    //     return null;
    // }, $roleIdsArray);

    // // Map subjectId to subject names
    // $subjectIdsArray = explode(',', $subject);
    // $subjectNames = array_map(function ($subjectId) use ($values) {
    //     foreach ($values['subjects'] as $subject) {
    //         if ($subject['subjectId'] == $subjectId) {
    //             return $subject['favourite_subject'];
    //         }
    //     }
    //     return null;
    // }, $subjectIdsArray);

    // Now, use $roleNames and $subjectNames in your message
    // $roleName = implode(', ', array_filter($roleNames));
    // $subjectName = implode(', ', array_filter($subjectNames));
    // echo  $subjectName ;
    // exit();
    //     $checkingEntrysql="SELECT * FROM `register` WHERE `roleId`= ".$roleId." and `subjectId` = ".$subject." and `email`= '".$email."' ";
    //     $checkingEntry=mysqli_query($databaseConnection, $checkingEntrysql);
    // //   echo  $checkingEntrysql;
    // //   exit();
    //      if(mysqli_num_rows($checkingEntry)==0){ 


    // $queryToInsert = "INSERT INTO `register`(`roleId`,`subjectId`,`name`,`phone_no`,`email`,`source`,`registeredTime`,`resume`) VALUES (".($roleId==NULL?'NULL':("'".$roleId."'")).",".($subject==NULL?'NULL':("'".$subject."'")).",".($name=="NULL"?'NULL':("'".$name."'")).",".($phone_number=="NULL"?'NULL':("'".$phone_number."'")).",".($email=="NULL"?'NULL':("'".$email."'")).",'homepage',now(),".($resume=="NULL"?'NULL':("'".$resume."'")).")";
    // // echo $queryToInsert;
    // $result=mysqli_query($databaseConnection,$queryToInsert);
    // if($result){
    //         //Data saved successfully, now send the email
    //     //  $to = "nitin@goprac.com";
    //     //$to = "shrikantkolhatkar30336@gmail.com";
    //         $to = "sourabh13689@gmail.com";
    //         $subjects = "Book a Free Class";
    //         $messages =  "Dear Admin,\n
    //                     There is interest for Role: " . $roleName . ", and subjects: " .  $subjectName . " from " . $name . ", Phone NO: " . $phone_number . ", Email: " . $email . ".\n
    //                     Thanks.";
    //         // Send the email
    //         sendEmailToUser($to, null, $subjects, $messages);

    //     // Assign Default Practice
    //     $practiceFrequency = 'sunday 7:00 PM Once';
    //     $candidPreId ="INSERT INTO candidateInterviewMapping(`candidateId`,`emailId`, `preInterviewId`, `createdAt`, `practiceFrequency`, `role`, `subject`) VALUES(".($userId === NULL ? "NULL" : "'".$userId."'").",'".$email."', '".$preId ."', NOW(), '".$practiceFrequency."', '".$roleId."', '".$subject."')";
    //     $candidPreIdInsert=mysqli_query($databaseConnection,$candidPreId);

    //     // Assign Default Practice
    //     if($candidPreIdInsert>0){

    //         $frequencyArray = explode(',', $practiceFrequency);

    //         // Get the first value
    //         $firstFrequency = trim($frequencyArray[0]); 
    //         list($day, $time, $period, $freq) = explode(' ', $firstFrequency);

    //         $scheduletime = $time . ' ' . $period; 

    //         $now = new DateTime();
    //         $currentDayOfWeek = $now->format('l'); 

    //         $daysToAdd = (7 + array_search(ucfirst(strtolower($day)), ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']) - $now->format('w')) % 7;
    //         if ($currentDayOfWeek === ucfirst(strtolower($day))) {
    //         $daysToAdd = 0;
    //         }

    //         $now->modify("+{$daysToAdd} days");
    //         $scheduledate = $now->format('d F Y'); 
    //         $interviewName = '';
    //         $interviewLink = '';
    //         if ($preId != '') {
    //             $Query = mysqli_query($databaseConnection, "SELECT id, interviewName FROM preInterview WHERE id = '" . $preId . "'");
    //             $Result = mysqli_fetch_assoc($Query);

    //             if ($Result['id'] != NULL) {
    //                 $interviewLink = 'https://goprac.com/job?p=' . $Result['id'];
    //             }

    //             if ($Result['interviewName'] != NULL) {
    //                 $interviewName = $Result['interviewName'];
    //                 $interviewName = str_replace(array("\n", "\r"), ' ', $interviewName);
    //                 $interviewName = preg_replace('/\s+/', ' ', $interviewName);
    //             }
    //         }

    //         $data = array();
    //         $data["subject"] = $interviewName;
    //         $data["name"] = $name;
    //         $data["scheduletime"] = $scheduletime;
    //         $data["scheduledate"] = $scheduledate;
    //         $data["interviewlink"] = $interviewLink;

    //         if ($phone_number != '') {
    //             //whatsAppMsg($databaseConnection, '9767479189', $data, "practiceAssign");
    //             whatsAppMsg($databaseConnection, $phone_number, $data, "practiceAssign");
    //         }    
    //     }

    //     $to_encode = array(
    //         'status'=> 1,
    //         'preId' => $preId,
    //         'values' => $values,
    //     );


    // }else{
    //     $to_encode = array(
    //         'status'=> 0
    //         // 'message'=> mysqli_error($databaseConnection)
    //     );
    // }
    // }
    // $to_encode = array(
    //     'status'=> 1,
    //     'message'=>'Already exists'
    // );

    $to_encode = array(
        'status' => 1,
        'preId' => $preId,
        'topics' => $topics,
        'values' => $values,
    );


    echo json_encode($to_encode);
}
else if (isset($_GET['registerUpskill'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    $userId = $json['userId'];
    $preInterviewId = $json['preInterviewId'];
    $action = $json['action'];

    $emailId = "";
    $mobileNumber = "";
    $name = "";

    $subjectId = "";
    $roleId = "";
    $source = isset($json['source']) && $json['source'] !== '' ? $json['source'] : "goprac";
    $inviteCode = isset($json['code']) && $json['code'] !== '' ? $json['code'] : null;

    if (!empty($userId)) {
        $user = "SELECT emailId, mobileNumber, firstName FROM users WHERE id = '" . $userId . "'";
        $userResult = mysqli_query($databaseConnection, $user);

        if ($userResult) {
            $row = mysqli_fetch_assoc($userResult);
            if ($row) {
                $emailId = $row['emailId'];
                $mobileNumber = $row['mobileNumber'];
                $name = $row['firstName'];
            }
        }
    }
    if (!empty($preInterviewId)) {
        $preInterview = "SELECT st.subject from scps_transaction st inner join preInterview pr ON pr.id=st.preInterviewId where pr.interviewType = 'Practice' and pr.id IN (" . $preInterviewId . ") group by st.subject";
        $preInterviewResult = mysqli_query($databaseConnection, $preInterview);

        if ($preInterviewResult) {
            $row1 = mysqli_fetch_assoc($preInterviewResult);
            if ($row1) {
                $subjectId = $row1['subject'];
            }
        }
    }
    if (!empty($subjectId)) {
        $role = "SELECT roleId FROM role_subject where subjectId IN ($subjectId)";
        // echo $role;
        $roleResult = mysqli_query($databaseConnection, $role);

        if ($roleResult) {
            $row = mysqli_fetch_assoc($roleResult);
            if ($row) {
                $roleId = $row['roleId'];
            }
        }
    }

    // echo $subjectId;
    // echo $roleId;

    if ($subjectId) {
        $sql = "SELECT id, favourite_subject FROM favourite_subject WHERE id IN (" . $subjectId . ") ";
        $subject_query = mysqli_query($databaseConnection, $sql);
        $subjectResult = mysqli_fetch_all($subject_query, MYSQLI_ASSOC);
        $subjectName = $subjectResult[0]['favourite_subject'];

    } else {
        $subjectName = "";
    }

    if ($roleId) {

        $sql1 = "SELECT id, name as roleName FROM relavant_role WHERE id IN (" . $roleId . ") ";
        $role_query = mysqli_query($databaseConnection, $sql1);
        $role_queryResult = mysqli_fetch_all($role_query, MYSQLI_ASSOC);
        $roleName = $role_queryResult[0]['roleName'];
    } else {
        $roleName = "";
    }





    $checkQuery = "
        SELECT id FROM candidateInterviewMapping 
        WHERE emailId = '" . $emailId . "' 
        AND preInterviewId = '" . $preInterviewId . "'";

    // echo $checkQuery;
    $checkResult = mysqli_query($databaseConnection, $checkQuery);

    if (mysqli_num_rows($checkResult) == 0) {

        //now send the email


        if ($action == 'register') {
            $to = "nitin@goprac.com";
            // $to = "sourabh13689@gmail.com";
            $subjects = "Book a Free Class";
            $messages = "Dear Admin,\n
                            There is interest for Role: " . $roleName . ", and subjects: " . $subjectName . " from " . $name . ", Phone NO: " . $mobileNumber . ", Email: " . $emailId . ".\n
                            Thanks.";
            // Send the email
            sendEmailToUser($to, null, $subjects, $messages);

        }

        $candidPreId = "
            INSERT INTO candidateInterviewMapping(
                `candidateId`, 
                `emailId`, 
                `mobileNumber`, 
                `candidateName`, 
                `preInterviewId`, 
                `createdAt`, 
                `inviteDate`,
                `role`, 
                `subject`, 
                `source`,
                `code`
            ) 
            VALUES(
                " . ($userId === null ? "NULL" : "'" . $userId . "'") . ",
                '" . $emailId . "', 
                '" . $mobileNumber . "', 
                '" . $name . "', 
                '" . $preInterviewId . "', 
                NOW(), 
                NOW(),
                " . ($roleId === null ? "NULL" : "'" . $roleId . "'") . ", 
                " . ($subjectId === null ? "NULL" : "'" . $subjectId . "'") . ",
                '" . $source . "',
                " . ($inviteCode ? "'" . mysqli_real_escape_string($databaseConnection, $inviteCode) . "'" : "NULL") . "
            )
        ";


        $candidPreIdInsert = mysqli_query($databaseConnection, $candidPreId);


        // Assign Default Practice
        if ($candidPreIdInsert > 0) {

            $interviewName = '';
            $interviewLink = '';
            if ($preInterviewId != '') {
                $Query = mysqli_query($databaseConnection, "SELECT id, interviewName FROM preInterview WHERE id = '" . $preInterviewId . "'");
                $Result = mysqli_fetch_assoc($Query);

                if ($Result['id'] != NULL) {
                    $interviewLink = 'https://goprac.com/job?p=' . $Result['id'];
                }

                if ($Result['interviewName'] != NULL) {
                    $interviewName = $Result['interviewName'];
                    $interviewName = str_replace(array("\n", "\r"), ' ', $interviewName);
                    $interviewName = preg_replace('/\s+/', ' ', $interviewName);
                }
            }

            $data = array();
            $data["subject"] = $interviewName;
            $data["name"] = $name;
            $data["interviewlink"] = $interviewLink;

            if ($mobileNumber != '' && $action == 'register') {
                //whatsAppMsg($databaseConnection, '9767479189', $data, "practiceAssign");
                // whatsAppMsg($databaseConnection, $mobileNumber, $data, "practiceAssign");
            } else if ($emailId != '' && $action == 'register') {

                // send email
                $messages = "<html>
                <head>
                </head>
                <body>
                    <p style='font-weight:bold'>Hi " . $name . ",</p>
                    <p>Your practice Interview will be conducted on " . $interviewName . " Please access your interview practice link here: " . $interviewLink . ".</p>   
                    <p>Select your subject, take a 15-min AI BOT interview anytime on any device, and learn from instant feedback.</p>
                    <p style='font-weight:bold'>Placement Support:</p>
                    <p>Your profile will be processed by our Placement Support Team once you complete your practice and achieve your best score. Higher scores increase your chances of receiving job interview calls. </p>
                    <p>For assistance, contact us: +91 6360060622</p> 
                    <p style='font-weight:bold'>Best regards,<br />Nitin Rakesh Prasad <br />Founder - GoPrac</p>
                </body>
                </html>";


                // Send email
                $to = $emailId;
                $message = $messages;
                sendEmailToUser($to, null, $subjects, $message);


            }
        }
    } else {

        $candidPreId = "
        UPDATE candidateInterviewMapping 
        SET 
            candidateId = " . ($userId === NULL ? "NULL" : "'" . $userId . "'") . "
        WHERE 
            emailId = '" . $emailId . "' 
            AND preInterviewId = '" . $preInterviewId . "'";

        $candidPreIdUpdate = mysqli_query($databaseConnection, $candidPreId);

        if ($candidPreIdUpdate) {
        }

    }

    $to_encode = array(
        'status' => 1
    );

    echo json_encode($to_encode);
}
else if (isset($_GET['getRegisterInfo'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    if (isset($json['userId'])) {
        $userId = $json['userId'];
        $queryToSelect = "SELECT * FROM `users` WHERE `id` = $userId";

        $result = mysqli_query($databaseConnection, $queryToSelect);
        if ($result) {
            $numRows = mysqli_num_rows($result);
            if ($numRows > 0) {
                while ($row = mysqli_fetch_assoc($result)) {
                    $mobile = $row['mobileNumber'];
                    $email = $row['emailId'];
                    $queryToSelect = "SELECT * FROM `register` WHERE `email` = '$email'";
                    $result = mysqli_query($databaseConnection, $queryToSelect);

                    if ($result) {
                        $numRows = mysqli_num_rows($result);

                        if ($numRows > 0) {
                            while ($row = mysqli_fetch_assoc($result)) {
                                $email = $row['email'];
                                $to_encode = array(
                                    'data' => $email,
                                    'status' => 'found',
                                );
                            }
                        } else {
                            $to_encode = array(
                                'status' => 'nodata',
                            );
                        }
                    } else {
                        $to_encode = array(
                            'error' => mysqli_error($databaseConnection),
                            'status' => 'error'
                        );
                    }
                }
            } else {
                $to_encode = array(
                    'status' => 'error'
                );
            }
        } else {
            $to_encode = array(
                'error' => mysqli_error($databaseConnection),
                'status' => 'error'
            );
        }
    } else {
        $to_encode = array(
            'status' => 'error'
        );
    }
    echo json_encode($to_encode);
}
// node-api
else if (isset($_GET['registercompanyInfo'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

     if (!empty($json['website'])) {
        // Log the bot attempt if needed
        error_log("Bot detected - honeypot filled: " . json_encode($json));
        
        // Return success to fool the bot
        header('Content-Type: application/json');
        echo json_encode(['status' => 1]);
        exit;
    }

    $source = $json['source'];
    // $productType = $json['productType'];
    $company = isset($json['companyName']) ? $json['companyName'] : (isset($json['company']) ? $json['company'] : (isset($json['fullName']) ? $json['fullName'] : ""));
    $contactName = isset($json['contactName']) ? trim($json['contactName']) : "";
    $phone_number = $json['phone_number'];
    $email = $json['email'];
    $msg = isset($json['msg']) ? trim($json['msg']) : "";

    // Remove non-digit characters for phone (handle +91 etc)
    $cleaned_phone = preg_replace('/\\D/', '', $phone_number);

    // Phone should be exactly 10 digits, starts with 6,7,8,9
    if (!preg_match('/^[6789][0-9]{9}$/', $cleaned_phone)) {
        header('Content-Type: application/json');
        echo json_encode(['status'=>0, 'errorCode'=>'Invalid phone format']); 
        exit;
    }

    // Email validation
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        header('Content-Type: application/json');
        echo json_encode(['status'=>0, 'errorCode'=>'Invalid email']); 
        exit;
    }

    // Company required
    if (empty($company)) {
        header('Content-Type: application/json');
        echo json_encode(['status'=>0, 'errorCode'=>'Company required']); 
        exit;
    }

    // Use cleaned phone for DB insert
    $phone_number = $cleaned_phone;

    // Prepare statement with error handling
    $stmt = $databaseConnection->prepare(
           "INSERT INTO `corporateMailList` (`companyName`, `contactName`, `mobileNumber`, `emailId`, `source`, `msg`) 
            VALUES (?, ?, ?, ?, ?, ?)"
    );
    
    // Check if prepare() was successful
    if (!$stmt) {
        error_log("Prepare failed: " . $databaseConnection->error);
        header('Content-Type: application/json');
        echo json_encode(['status'=>0, 'errorCode'=>'Database error']);
        exit;
    }
    
    $stmt->bind_param("ssssss", $company, $contactName, $phone_number, $email, $source, $msg);
    $result = $stmt->execute();

    if ($result) {
        $to_encode = array(
            'status' => 1
        );

        // Convert to JSON early
        $json = json_encode($to_encode);

        // Send response headers
        header('Content-Type: application/json');
        header('Connection: close');
        header('Content-Length: ' . strlen($json));
        ob_end_clean(); // Clean any previous output buffer

        // Send and flush response immediately
        echo $json;
        flush();

        // Let client disconnect but continue server execution
        if (function_exists('ignore_user_abort')) {
            ignore_user_abort(true);
        }

        // Continue in background (async-like)
        // Use a new process or thread if possible
        // Email sending after response

        // $to = "sourabh13689@gmail.com";
        $to = "nitin@goprac.com";
        $subjects = "Talk to our Sales Team";
        $messages = "Dear Admin,\n
                    There is interest from the Company: " . $company . ",Contact Name: " . $contactName . ", Phone NO: " . $phone_number . ", Email: " . $email . ", Message: " . $msg . ".\n
                    Thanks. \n  
                     ";
        // Send the email
        if($company){
            sendEmailToUser($to, null, $subjects, $messages);
        }
        $stmt->close();
        exit;
    } else {
        // Log execution error
        error_log("Execute failed: " . $stmt->error);
        $to_encode = array('status' => 0, 'errorCode' => 'Execution failed');
        
        // Close statement on error too
        $stmt->close();
    }

    echo json_encode($to_encode);
}
else if (isset($_GET['registerupskillInfo'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);



    $name = $json['name'];
    $phone_number = $json['phone_number'];
    $email = $json['email'];


    $queryToInsert = "INSERT INTO `register`(`name`,`phone_no`,`email`,`source`) VALUES (" . ($name == "NULL" ? 'NULL' : ("'" . $name . "'")) . "," . ($phone_number == "NULL" ? 'NULL' : ("'" . $phone_number . "'")) . "," . ($email == "NULL" ? 'NULL' : ("'" . $email . "'")) . ",'upskillpage')";

    $result = mysqli_query($databaseConnection, $queryToInsert);
    if ($result) {
        $to = "nitin@goprac.com";
        //  $to = "krishnaathi27@gmail.com";
        $subjects = "Subscribe monthly at INR 2000";

        $messages = "Dear Admin,\n
                                   There is interest from the Candidate:  " . $name . ", Phone NO: " . $phone_number . ", Email: " . $email . ".\n
                                   Thanks. \n  
                                   ";
        // Send the email
        sendEmailToUser($to, null, $subjects, $messages);
        $to_encode = array(
            'status' => 1
        );
    } else {
        $to_encode = array(
            'status' => 0
        );
    }

    echo json_encode($to_encode);
} else if (isset($_GET['getEmployabilityJobDetails'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    // $str = str_replace(', ', ',', $json['tokenfield']);
    // print_r($json['workexperience']);

    $jobType = "";
    $joinstatus = "";
    $preferedJobType = "";
    $currentProcess = "";
    $processType = "";
    $currentCompany = "";
    $clienttype = "";
    $processPreference = "";
    $shift = "";
    $workLocation = "";
    $convinientTime = "";
    $expectedsalary = "";
    $joiningTimeline = "";
    $workexperience = "";
    $currentlocation = "";
    $Language = "";
    $str = "";
    $resume = "";

    if (!empty($json['assessmentDeclaration'])) {
        $assessmentDeclaration = $json['assessmentDeclaration'];
    } else {
        $assessmentDeclaration = null;
    }


    if ($json['jobType'] == '') {
        $jobType = NULL;
    }

    if ($json['joinstatus'] == '') {
        $joinstatus = NULL;
    }

    if ($json['joiningTimeline'] == '') {
        $joiningTimeline = NULL;
    }

    if ($json['preferedJobType'] == '') {

        $preferedJobType = NULL;
    }

    if ($json['currentProcess'] == '') {

        $currentProcess = NULL;
    }

    if ($json['processType'] == '') {

        $processType = NULL;
    }

    if ($json['currentCompany'] == '') {

        $currentCompany = NULL;
    }

    if ($json['clienttype'] == '') {

        $clienttype = NULL;
    }

    if ($json['processPreference'] == '') {

        $processPreference = NULL;
    }

    if ($json['shift'] == '') {

        $shift = NULL;
    }

    if ($json['workLocation'] == '') {

        $workLocation = NULL;
    }

    if ($json['convinientTime'] == '') {

        $convinientTime = NULL;
    }

    if ($json['expectedsalary'] == '') {

        $expectedsalary = NULL;
    }

    if ($json['resume'] == '') {

        $resume = NULL;
    }

    if (!empty($json['workexperience'])) {
        if (is_array($json['workexperience'])) {
            $workexperience = implode(',', $json['workexperience']);
        } else {
            $workexperience = $json['workexperience'];
        }
    } else {
        $workexperience = null;
    }
    if (!empty($json['currentlocation'])) {
        if (is_array($json['currentlocation'])) {
            $currentlocation = implode(',', $json['currentlocation']);
        } else {
            $currentlocation = $json['currentlocation'];
        }
    } else {
        $currentlocation = null;
    }
    if (!empty($json['Language'])) {
        if (is_array($json['Language'])) {
            $Language = implode(',', $json['Language']);
        } else {
            $Language = $json['Language'];
        }
    } else {
        $Language = null;
    }

    if (!empty($json['tokenfield'])) {
        $str = str_replace(', ', ',', $json['tokenfield']);
    } else {
        $str = null;
    }

    // if(!empty($json['tokenfield'])){
    //     if(is_array($json['tokenfield'])){
    //         $str=implode(',', $json['tokenfield']);
    //     }else{
    //         $str=$json['tokenfield'];
    //     }
    //     }else{
    //         $str=null;
    //     }

    if (!empty($json['noticePeriod'])) {
        if (is_array($json['noticePeriod'])) {
            $noticePeriod = implode(',', $json['noticePeriod']);
        } else {
            $noticePeriod = $json['noticePeriod'];
        }
    } else {
        $noticePeriod = null;
    }
    if (!empty($json['skillValues'])) {
        if (is_array($json['skillValues'])) {
            $skillValues = implode(',', $json['skillValues']);
        } else {
            $skillValues = $json['skillValues'];
        }
    } else {
        $skillValues = null;
    }
    if (!empty($json['certiValues'])) {
        if (is_array($json['certiValues'])) {
            $certiValues = implode(',', $json['certiValues']);
        } else {
            $certiValues = $json['certiValues'];
        }
    } else {
        $certiValues = null;
    }
    if (!empty($json['avgTenure'])) {
        if (is_array($json['avgTenure'])) {
            $avgTenure = implode(',', $json['avgTenure']);
        } else {
            $avgTenure = $json['avgTenure'];
        }
    } else {
        $avgTenure = null;
    }
    if (!empty($json['preferredrole'])) {
        if (is_array($json['preferredrole'])) {
            $preferredrole = implode(',', $json['preferredrole']);
        } else {
            $preferredrole = $json['preferredrole'];
        }
    } else {
        $preferredrole = null;
    }
    if (!empty($json['resume'])) {
        if (is_array($json['resume'])) {
            $resume = implode(',', $json['resume']);
        } else {
            $resume = $json['resume'];
        }
    } else {
        $resume = null;
    }

    if ($json['userId'] != '') {

        $query = "select emailId from users where id=" . $json['userId'] . "";

        $queryToCheckData = mysqli_query($databaseConnection, $query);

        if (mysqli_num_rows($queryToCheckData) > 0) {

            $emailId = mysqli_fetch_assoc($queryToCheckData)['emailId'];

            $data = "update professionaldetails set workExperience = '" . $workexperience . "', salary = '" . $json['currentsalary'] . "', currentLocation = '" . $currentlocation . "', languages = '" . $Language . "', noticePeriod = '" . $noticePeriod . "',assessmentDeclaration = '" . $assessmentDeclaration . "',preferredWorkLocation = '" . $str . "',";

            if (is_null($jobType)) {
                $data .= "jobType=NULL, ";
            } else {
                if (is_array($json['jobType'])) {
                    $data .= " jobType='" . implode(',', $json['jobType']) . "',";
                } else {
                    $data .= " jobType='" . $json['jobType'] . "',";
                }
            }

            if (is_null($joiningTimeline)) {
                $data .= "joiningTimeline=NULL, ";
            } else {
                if (is_array($json['joiningTimeline'])) {
                    $data .= " joiningTimeline='" . implode(',', $json['joiningTimeline']) . "',";
                } else {
                    $data .= " joiningTimeline='" . $json['joiningTimeline'] . "',";
                }
            }

            if (is_null($joinstatus)) {
                $data .= "joinstatus=NULL, ";
            } else {
                if (is_array($json['joinstatus'])) {
                    $data .= " joinstatus='" . implode(',', $json['joinstatus']) . "',";
                } else {
                    $data .= " joinstatus='" . $json['joinstatus'] . "',";
                }
            }

            if (is_null($preferedJobType)) {
                $data .= "preferedJobType=NULL, ";
            } else {
                if (is_array($json['preferedJobType'])) {
                    $data .= " preferedJobType='" . implode(',', $json['preferedJobType']) . "',";
                } else {
                    $data .= " preferedJobType='" . $json['preferedJobType'] . "',";
                }
            }

            if (is_null($currentProcess)) {
                $data .= "currentProcess=NULL, ";
            } else {
                if (is_array($json['currentProcess'])) {
                    $data .= " currentProcess='" . implode(',', $json['currentProcess']) . "',";
                } else {
                    $data .= " currentProcess='" . $json['currentProcess'] . "',";
                }
            }

            if (is_null($processType)) {
                $data .= "processType=NULL, ";
            } else {
                if (is_array($json['processType'])) {
                    $data .= " processType='" . implode(',', $json['processType']) . "',";
                } else {
                    $data .= " processType='" . $json['processType'] . "',";
                }
            }

            if (is_null($currentCompany)) {
                $data .= "currentCompany=NULL, ";
            } else {
                $data .= " currentCompany='" . $json['currentCompany'] . "',";
            }

            if (is_null($clienttype)) {
                $data .= "clienttype=NULL, ";
            } else {
                if (is_array($json['clienttype'])) {
                    $data .= " clienttype='" . implode(',', $json['clienttype']) . "',";
                } else {
                    $data .= " clienttype='" . $json['clienttype'] . "',";
                }
            }

            if (is_null($processPreference)) {
                $data .= "processPreference=NULL, ";
            } else {
                if (is_array($json['processPreference'])) {
                    $data .= " processPreference='" . implode(',', $json['processPreference']) . "',";
                } else {
                    $data .= " processPreference='" . $json['processPreference'] . "',";
                }
            }

            if (is_null($shift)) {
                $data .= "shift=NULL, ";
            } else {
                if (is_array($json['shift'])) {
                    $data .= " shift='" . implode(',', $json['shift']) . "',";
                } else {
                    $data .= " shift='" . $json['shift'] . "',";
                }
            }

            if (is_null($workLocation)) {
                $data .= "workLocationPreference=NULL, ";
            } else {
                if (is_array($json['workLocation'])) {
                    $data .= " workLocationPreference='" . implode(',', $json['workLocation']) . "',";
                } else {
                    $data .= " workLocationPreference='" . $json['workLocation'] . "',";
                }
            }

            if (is_null($convinientTime)) {
                $data .= "timeToCall=NULL, ";
            } else {
                if (is_array($json['convinientTime'])) {
                    $data .= " timeToCall='" . implode(',', $json['convinientTime']) . "',";
                } else {
                    $data .= " timeToCall='" . $json['convinientTime'] . "',";
                }
            }

            if (is_null($expectedsalary)) {
                $data .= "expectedsalary=NULL, ";
            } else {
                $data .= " expectedsalary='" . $json['expectedsalary'] . "',";
            }

            if (is_null($certiValues)) {
                $data .= "certifications=NULL, ";
            } else {
                $data .= " certifications='" . $json['certiValues'] . "',";
            }

            if (is_null($avgTenure)) {
                $data .= "avgTenure=NULL, ";
            } else {
                if (is_array($json['avgTenure'])) {
                    $data .= " avgTenure='" . implode(',', $json['avgTenure']) . "',";
                } else {
                    $data .= " avgTenure='" . $json['avgTenure'] . "',";
                }
            }

            if (is_null($preferredrole)) {
                $data .= "preferredRole=NULL, ";
            } else {
                $data .= " preferredRole='" . $json['preferredrole'] . "',";
            }

            if (is_null($skillValues)) {
                $data .= "skills=NULL, ";
            } else {
                $data .= " skills='" . $json['skillValues'] . "',";
            }

            if (is_null($resume)) {
                $data .= "resume=NULL ";
            } else {
                $data .= " resume='" . $json['resume'] . "'";
            }


            $data .= " where candidateId='" . $json['userId'] . "'";

            $userData = mysqli_query($databaseConnection, $data);

            $query2 = "select emailId from interviewSchedule where emailId='" . $emailId . "' and preInterviewId=" . $json['preInterviewId'] . "";

            $queryToCheckData2 = mysqli_query($databaseConnection, $query2);

            if (mysqli_num_rows($queryToCheckData2) > 0) {

                $sql = "update interviewSchedule set workExperience = '" . $workexperience . "', currentSalary = '" . $json['currentsalary'] . "', noticePeriod = '" . $noticePeriod . "',preferredWorkLocation = '" . $str . "',languages='" . $Language . "',currentLocation='" . $currentlocation . "',";


                if (is_null($jobType)) {
                    $sql .= "jobType=NULL, ";
                } else {
                    if (is_array($json['jobType'])) {
                        $sql .= " jobType='" . implode(',', $json['jobType']) . "',";
                    } else {
                        $sql .= " jobType='" . $json['jobType'] . "',";
                    }
                }

                if (is_null($joiningTimeline)) {
                    $sql .= "joiningTimeline=NULL, ";
                } else {
                    if (is_array($json['joiningTimeline'])) {
                        $sql .= " joiningTimeline='" . implode(',', $json['joiningTimeline']) . "',";
                    } else {
                        $sql .= " joiningTimeline='" . $json['joiningTimeline'] . "',";
                    }
                }

                if (is_null($preferedJobType)) {
                    $sql .= "preferedJobType=NULL, ";
                } else {
                    if (is_array($json['preferedJobType'])) {
                        $sql .= " preferedJobType='" . implode(',', $json['preferedJobType']) . "',";
                    } else {
                        $sql .= " preferedJobType='" . $json['preferedJobType'] . "',";
                    }
                }

                if (is_null($currentProcess)) {
                    $sql .= "currentProcess=NULL, ";
                } else {
                    if (is_array($json['currentProcess'])) {
                        $sql .= " currentProcess='" . implode(',', $json['currentProcess']) . "',";
                    } else {
                        $sql .= " currentProcess='" . $json['currentProcess'] . "',";
                    }
                }

                if (is_null($processType)) {
                    $sql .= "processType=NULL, ";
                } else {
                    if (is_array($json['processType'])) {
                        $sql .= " processType='" . implode(',', $json['processType']) . "',";
                    } else {
                        $sql .= " processType='" . $json['processType'] . "',";
                    }
                }

                if (is_null($currentCompany)) {
                    $sql .= "currentCompany=NULL, ";
                } else {
                    if (is_array($json['currentCompany'])) {
                        $sql .= " currentCompany='" . implode(',', $json['currentCompany']) . "',";
                    } else {
                        $sql .= " currentCompany='" . $json['currentCompany'] . "',";
                    }
                }

                if (is_null($clienttype)) {
                    $sql .= "clienttype=NULL, ";
                } else {
                    if (is_array($json['clienttype'])) {
                        $sql .= " clienttype='" . implode(',', $json['clienttype']) . "',";
                    } else {
                        $sql .= " clienttype='" . $json['clienttype'] . "',";
                    }
                }

                if (is_null($processPreference)) {
                    $sql .= "processPreference=NULL, ";
                } else {
                    if (is_array($json['processPreference'])) {
                        $sql .= " processPreference='" . implode(',', $json['processPreference']) . "',";
                    } else {
                        $sql .= " processPreference='" . $json['processPreference'] . "',";
                    }
                }

                if (is_null($shift)) {
                    $sql .= "shift=NULL, ";
                } else {
                    if (is_array($json['shift'])) {
                        $sql .= " shift='" . implode(',', $json['shift']) . "',";
                    } else {
                        $sql .= " shift='" . $json['shift'] . "',";
                    }
                }

                if (is_null($workLocation)) {
                    $sql .= "workLocationPreference=NULL, ";
                } else {
                    if (is_array($json['workLocation'])) {
                        $sql .= " workLocationPreference='" . implode(',', $json['workLocation']) . "',";
                    } else {
                        $sql .= " workLocationPreference='" . $json['workLocation'] . "',";
                    }
                }

                if (is_null($convinientTime)) {
                    $sql .= "timeToCall=NULL, ";
                } else {
                    if (is_array($json['convinientTime'])) {
                        $sql .= " timeToCall='" . implode(',', $json['convinientTime']) . "',";
                    } else {
                        $sql .= " timeToCall='" . $json['convinientTime'] . "',";
                    }
                }

                if (is_null($expectedsalary)) {
                    $sql .= "expectedsalary=NULL, ";
                } else {
                    if (is_array($json['expectedsalary'])) {
                        $sql .= " expectedsalary='" . implode(',', $json['expectedsalary']) . "',";
                    } else {
                        $sql .= " expectedsalary='" . $json['expectedsalary'] . "',";
                    }
                }

                if (is_null($skillValues)) {
                    $sql .= "skillValues=NULL, ";
                } else {
                    if (is_array($json['skillValues'])) {
                        $sql .= " skillValues='" . implode(',', $json['skillValues']) . "',";
                    } else {
                        $sql .= " skillValues='" . $json['skillValues'] . "',";
                    }
                }

                if (is_null($certiValues)) {
                    $sql .= "certiValues=NULL, ";
                } else {
                    if (is_array($json['certiValues'])) {
                        $sql .= " certiValues='" . implode(',', $json['certiValues']) . "',";
                    } else {
                        $sql .= " certiValues='" . $json['certiValues'] . "',";
                    }
                }
                if (is_null($avgTenure)) {
                    $sql .= "avgTenure=NULL, ";
                } else {
                    if (is_array($json['avgTenure'])) {
                        $sql .= " avgTenure='" . implode(',', $json['avgTenure']) . "',";
                    } else {
                        $sql .= " avgTenure='" . $json['avgTenure'] . "',";
                    }
                }

                if (is_null($preferredrole)) {
                    $sql .= "preferredrole=NULL ";
                } else {
                    if (is_array($json['preferredrole'])) {
                        $sql .= " preferredrole='" . implode(',', $json['preferredrole']) . "',";
                    } else {
                        $sql .= " preferredrole='" . $json['preferredrole'] . "',";
                    }
                }

                if (is_null($resume)) {
                    // $sql .="resume=NULL ";
                } else {
                    $sql .= " resume='" . $json['resume'] . "'";
                }

                $sql .= " where emailId='" . $emailId . "' and preInterviewId=" . $json['preInterviewId'] . "";

                // var_dump($sql);
                $updateSchedule = mysqli_query($databaseConnection, $sql);
            } else {


                if (!is_null($jobType)) {
                    // $jobType=implode(',',$json['jobType']);
                    if (is_array($json['jobType'])) {
                        $jobType = implode(',', $json['jobType']);
                    } else {
                        $jobType = $json['jobType'];
                    }
                }

                if (!is_null($joiningTimeline)) {
                    $joiningTimeline = implode(',', $json['joiningTimeline']);
                }

                if (!is_null($joinstatus)) {
                    $joinstatus = $json['joinstatus'];
                }

                if (!is_null($preferedJobType)) {

                    $preferedJobType = implode(',', $json['preferedJobType']);
                }

                if (!is_null($currentProcess)) {

                    $currentProcess = implode(',', $json['currentProcess']);
                }

                if (!is_null($processType)) {
                    $processType = implode(',', $json['processType']);
                }

                if (!is_null($currentCompany)) {
                    $currentCompany = $json['currentCompany'];
                }

                if (!is_null($clienttype)) {

                    $clienttype = implode(',', $json['clienttype']);
                }

                if (!is_null($processPreference)) {

                    $processPreference = implode(',', $json['processPreference']);
                }

                if (!is_null($shift)) {

                    $shift = implode(',', $json['shift']);
                }

                if (!is_null($workLocation)) {

                    // $workLocation=implode(',',$json['workLocation']);
                    if (is_array($json['workLocation'])) {
                        $workLocation = implode(',', $json['workLocation']);
                    } else {
                        $workLocation = $json['workLocation'];
                    }

                }

                if (!is_null($convinientTime)) {

                    // $convinientTime=implode(',',$json['convinientTime']);
                    if (is_array($json['convinientTime'])) {
                        $convinientTime = implode(',', $json['convinientTime']);
                    } else {
                        $convinientTime = $json['convinientTime'];
                    }

                }


                if (!is_null($skillValues)) {

                    // $skillValues=implode(',',$json['skillValues']);
                    if (is_array($json['skillValues'])) {
                        $skillValues = implode(',', $json['skillValues']);
                    } else {
                        $skillValues = $json['skillValues'];
                    }

                }

                if (!is_null($certiValues)) {

                    // $certiValues=implode(',',$json['certiValues']);
                    if (is_array($json['certiValues'])) {
                        $certiValues = implode(',', $json['certiValues']);
                    } else {
                        $certiValues = $json['certiValues'];
                    }

                }

                if (!is_null($avgTenure)) {

                    // $avgTenure=implode(',',$json['avgTenure']);
                    if (is_array($json['avgTenure'])) {
                        $avgTenure = implode(',', $json['avgTenure']);
                    } else {
                        $avgTenure = $json['avgTenure'];
                    }

                }

                if (!is_null($preferredrole)) {

                    // $preferredrole=implode(',',$json['preferredrole']);
                    if (is_array($json['preferredrole'])) {
                        $preferredrole = implode(',', $json['preferredrole']);
                    } else {
                        $preferredrole = $json['preferredrole'];
                    }

                }

                if (!is_null($expectedsalary)) {
                    $expectedsalary = $json['expectedsalary'];
                }

                if (!is_null($resume)) {
                    $resume = $json['resume'];
                }



                // $queryToInsert = "INSERT INTO `interviewSchedule`(`company_id`,`candidate_id`,`candidateName`,`emailId`,`mobileNumber`,`scheduleTime`,`firstScheduleDate`,`sectorId`,`jobType`,`currentCompany`, `currentProcess`, `processType`, `clientType`, `workExperience`, `currentSalary`, `expectedSalary`, `noticePeriod`, `processPreference`, `shift`, `workLocationPreference`, `timeToCall`, `preferedJobType`, `currentLocation`, `preferredWorkLocation`, `languages`,`joiningTimeline`,`preferredrole`,`certiValues`,`skillValues`,`avgTenure`,`preInterviewId`,`resume`) VALUES (".$json['companyId'].",".$json['userId'].",(select firstName from users where id=".$json['userId']."),(select emailId from users where id=".$json['userId']."),(select mobileNumber from users where id=".$json['userId']."),now(),now(),".$json['sectorId'].",".($jobType=="NULL"?'NULL':("'".$jobType."'")).",".($currentCompany=="NULL"?'NULL':("'".$currentCompany."'")).",".($currentProcess=="NULL"?'NULL':("'".$currentProcess."'")).",".($processType=="NULL"?'NULL':("'".$processType."'")).",".($clienttype=="NULL"?'NULL':("'".$clienttype."'"))."," .($workexperience=="NULL"?'NULL':("'".$workexperience."'")).",'".$json['currentsalary']."',".($expectedsalary=="NULL"?'NULL':("'".$expectedsalary."'")).",".($noticePeriod=="NULL"?'NULL':("'".$noticePeriod."'")).",".($processPreference=="NULL"?'NULL':("'".$processPreference."'")).",".($shift=="NULL"?'NULL':("'".$shift."'")).",".($workLocation=="NULL"?'NULL':("'".$workLocation."'")).",".($convinientTime=="NULL"?'NULL':("'".$convinientTime."'")).",".($preferedJobType=="NULL"?'NULL':("'".$preferedJobType."'")).",".($currentlocation=="NULL"?'NULL':("'".$currentlocation."'")).",".($str=="NULL"?'NULL':("'".$str."'")).",".($Language=="NULL"?'NULL':("'".$Language."'")).",".($joiningTimeline=="NULL"?'NULL':("'".$joiningTimeline."'")).",".($preferredrole=="NULL"?'NULL':("'".$preferredrole."'")).",".($certiValues=="NULL"?'NULL':("'".$certiValues."'")).",".($skillValues=="NULL"?'NULL':("'".$skillValues."'")).",".($avgTenure=="NULL"?'NULL':("'".$avgTenure."'")).",'".$json['preInterviewId']."',".($resume=="NULL"?'NULL':("'".$resume."'")).")";
                // sourabh 

                $queryToInsert = "INSERT INTO `interviewSchedule`(`company_id`,`candidate_id`,`candidateName`,`emailId`,`mobileNumber`,`scheduleTime`,`firstScheduleDate`,`sectorId`,`jobType`,`currentCompany`, `currentProcess`, `processType`, `clientType`, `workExperience`, `currentSalary`, `expectedSalary`, `noticePeriod`, `processPreference`, `shift`, `workLocationPreference`, `timeToCall`, `preferedJobType`, `currentLocation`, `preferredWorkLocation`, `languages`,`joiningTimeline`,`preferredrole`,`certiValues`,`skillValues`,`avgTenure`,`preInterviewId`,`resume`) VALUES (" . $json['companyId'] . "," . $json['userId'] . ",(select firstName from users where id=" . $json['userId'] . "),(select emailId from users where id=" . $json['userId'] . "),(select mobileNumber from users where id=" . $json['userId'] . "),NULL,now()," . $json['sectorId'] . "," . ($jobType == "NULL" ? 'NULL' : ("'" . $jobType . "'")) . "," . ($currentCompany == "NULL" ? 'NULL' : ("'" . $currentCompany . "'")) . "," . ($currentProcess == "NULL" ? 'NULL' : ("'" . $currentProcess . "'")) . "," . ($processType == "NULL" ? 'NULL' : ("'" . $processType . "'")) . "," . ($clienttype == "NULL" ? 'NULL' : ("'" . $clienttype . "'")) . "," . ($workexperience == "NULL" ? 'NULL' : ("'" . $workexperience . "'")) . ",'" . $json['currentsalary'] . "'," . ($expectedsalary == "NULL" ? 'NULL' : ("'" . $expectedsalary . "'")) . "," . ($noticePeriod == "NULL" ? 'NULL' : ("'" . $noticePeriod . "'")) . "," . ($processPreference == "NULL" ? 'NULL' : ("'" . $processPreference . "'")) . "," . ($shift == "NULL" ? 'NULL' : ("'" . $shift . "'")) . "," . ($workLocation == "NULL" ? 'NULL' : ("'" . $workLocation . "'")) . "," . ($convinientTime == "NULL" ? 'NULL' : ("'" . $convinientTime . "'")) . "," . ($preferedJobType == "NULL" ? 'NULL' : ("'" . $preferedJobType . "'")) . "," . ($currentlocation == "NULL" ? 'NULL' : ("'" . $currentlocation . "'")) . "," . ($str == "NULL" ? 'NULL' : ("'" . $str . "'")) . "," . ($Language == "NULL" ? 'NULL' : ("'" . $Language . "'")) . "," . ($joiningTimeline == "NULL" ? 'NULL' : ("'" . $joiningTimeline . "'")) . "," . ($preferredrole == "NULL" ? 'NULL' : ("'" . $preferredrole . "'")) . "," . ($certiValues == "NULL" ? 'NULL' : ("'" . $certiValues . "'")) . "," . ($skillValues == "NULL" ? 'NULL' : ("'" . $skillValues . "'")) . "," . ($avgTenure == "NULL" ? 'NULL' : ("'" . $avgTenure . "'")) . ",'" . $json['preInterviewId'] . "'," . ($resume == "NULL" ? 'NULL' : ("'" . $resume . "'")) . ")";


                // var_dump($queryToInsert);
                $result = mysqli_query($databaseConnection, $queryToInsert);
                if ($result) {
                    $to_encode = array(
                        'status' => 1
                    );
                } else {
                    $to_encode = array(
                        'status' => 0
                        // 'message'=> mysqli_error($databaseConnection)
                    );
                }


            }


            if ($userData) {
                $to_encode = array(
                    'status' => 1
                );
            } else {
                $to_encode = array(
                    'status' => 0
                );
            }


        }
    }

    echo json_encode($to_encode);
}
else if (isset($_GET['getEmployabilityJobDetailsCompanyDetails'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    // print_r($json);
    // exit();

    $serviceType = "";
    $jobType = "";
    $joinstatus = "";
    $preferedJobType = "";
    $currentProcess = "";
    $processType = "";
    $currentCompany = "";
    $clienttype = null;
    $processPreference = null;
    $shift = "";
    $workLocation = "";
    $convinientTime = "";
    $mobileNumber = "";
    $workExperience = "";
    $currentSalary = "";
    $expectedSalary = "";
    $joiningTimeline = "";
    $currentlocation = "";
    $Language = "";
    $str = "";
    $resume = "";
    $noticePeriod = "";
    // $joiningPeriod = "";
    $currentLocation = "";
    // $promotionSource = "";
    $url = '';
    $candidateStatus = "";
    $employmentStatus = "";
    $interviewDatetime = "";
    $outstationDeclaration = '';
    $offer = '';
    $offeredCTC = '';
    $skills = '';
    $instituteCode = "";
    $userSkills = "";

    if ($json['mobileNumber'] == '') {
        $mobileNumber = NULL;
    } else {
        $mobileNumber = $json['mobileNumber'];
    }

    if ($json['workExperience'] == '') {
        $workExperience = NULL;
    } else {
        $workExperience = $json['workExperience'];
    }

    if ($json['currentSalary'] == '') {
        $currentSalary = NULL;
    } else {
        $currentSalary = $json['currentSalary'];
    }

    if ($json['expectedSalary'] == '') {
        $expectedSalary = NULL;
    } else {
        $expectedSalary = $json['expectedSalary'];
    }

    if ($json['outstationDeclaration'] == '') {
        $outstationDeclaration = NULL;
    } else {
        $outstationDeclaration = $json['outstationDeclaration'];
    }

    if ($json['interviewDatetime'] == '') {
        $interviewDatetime = NULL;
    } else {
        $interviewDatetime = $json['interviewDatetime'];
    }

    if ($json['serviceType'] == '') {
        $serviceType = NULL;
    } else {
        $serviceType = $json['serviceType'];
    }

    if (!empty($json['interviewRequired'])) {
        if ($json['interviewRequired'] == 'y') {
            $firstScheduleDate = 'NOW()';
        } else {
            $firstScheduleDate = 'NULL';
        }
    } else {
        $firstScheduleDate = 'NULL';
    }


    if (!empty($json['assessmentDeclaration'])) {
        $assessmentDeclaration = $json['assessmentDeclaration'];
    } else {
        $assessmentDeclaration = null;
    }


    if ($json['jobType'] == '') {
        $jobType = NULL;
    } else {
        if (is_array($json['jobType'])) {
            $jobType = implode(',', $json['jobType']);
        } else {
            $jobType = $json['jobType'];
        }

    }

    if ($json['currentCompany'] == '') {
        $currentCompany = NULL;
    } else {
        $currentCompany = $json['currentCompany'];
    }

    if ($json['resume'] == '') {
        $resume = NULL;
    } else {
        if (is_array($json['resume'])) {
            $resume = implode(',', $json['resume']);
        } else {
            $resume = $json['resume'];
        }
    }

    if (!empty($json['noticePeriod'])) {
        if (is_array($json['noticePeriod'])) {
            $noticePeriod = implode(',', $json['noticePeriod']);
        } else {
            $noticePeriod = $json['noticePeriod'];
        }
    } else {
        $noticePeriod = null;
    }

    if ($json['currentLocation'] == '') {
        $currentLocation = null;
    } else {
        if (is_array($json['currentLocation'])) {
            $currentLocation = implode(',', $json['currentLocation']);
        } else {
            $currentLocation = $json['currentLocation'];
        }
    }

    if ($json['candidateStatus'] == '') {
        $candidateStatus = null;
    } else {
        $candidateStatus = $json['candidateStatus'];
    }

    if (!empty($json['skillValues'])) {
        if (is_array($json['skillValues'])) {
            $skillValues = implode(',', $json['skillValues']);
        } else {
            $skillValues = $json['skillValues'];
        }
    } else {
        $skillValues = null;
    }

    if ($json['currentProcess'] == '') {
        $currentProcess = NULL;
    } else {
        if (is_array($json['currentProcess'])) {
            $currentProcess = implode(',', $json['currentProcess']);
        } else {
            $currentProcess = $json['currentProcess'];
        }
    }

    if ($json['processType'] == '') {
        $processType = NULL;
    } else {
        if (is_array($json['processType'])) {
            $processType = implode(',', $json['processType']);
        } else {
            $processType = $json['processType'];
        }
    }

    if ($json['shift'] == '') {
        $shift = NULL;
    } else {
        if (is_array($json['shift'])) {
            $shift = implode(',', $json['shift']);
        } else {
            $shift = $json['shift'];
        }

    }

    if ($json['promotionSource'] == '') {
        $promotionSource = NULL;
    } else {
        $promotionSource = $json['promotionSource'];
    }

    if (!empty($json['url'])) {
        $url = $json['url'];
    } else {
        $url = null;
    }

    if ($json['employmentStatus'] == '') {
        $employmentStatus = NULL;
    } else {
        $employmentStatus = $json['employmentStatus'];
    }


    if ($json['offer'] == '') {
        $offer = NULL;
    } else {
        $offer = $json['offer'];
    }

    if ($json['offeredCTC'] == '') {
        $offeredCTC = NULL;
    } else {
        $offeredCTC = $json['offeredCTC'];
    }

    if (!empty($json['skills'])) {
        $skills_json = $json['skills'];
        $skills = $skills_json;
    } else {
        $skills = null;
    }



    if ($json['instituteCode'] == '') {
        $instituteCode = NULL;
    } else {
        $instituteCode = $json['instituteCode'];
    }

    if ($json['userSkills'] == '') {
        $userSkills = NULL;
    } else {
        $userSkills = $json['userSkills'];
    }

    // var_dump($skills);
    // exit();


    if ($json['userId'] != '') {

        $user_id = $json['userId'];

        $professionalDetailsQuery = mysqli_query($databaseConnection, "SELECT * FROM professionaldetails WHERE candidateId='" . $user_id . "'");

        if ($professionalDetailsQuery) {
            // Fetch the result as an associative array
            $professionalDetails = mysqli_fetch_assoc($professionalDetailsQuery);

            // Check if there are results
            if ($professionalDetails) {
                $jsonCompanyId = $json['companyId'];
                $jsonUserId = $json['userId'];
                $jsonSectorId = $json['sectorId'];
                $processPreference = $professionalDetails['processPreference'];
                $workLocation = $professionalDetails['preferredWorkLocation'];
                $convinientTime = $professionalDetails['timeToCall'];
                $preferedJobType = $professionalDetails['preferedJobType'];
                $preferredWorkLocation = $professionalDetails['workLocationPreference'];
                $languages = $professionalDetails['languages'];
                $joiningTimeline = $professionalDetails['joiningTimeline'];
                $preferredrole = $professionalDetails['preferredRole'];
                $avgTenure = $professionalDetails['avgTenure'];
                $preInterviewId = $json['preInterviewId'];
                $certiValues = NULL;
                // $workexperience = $professionalDetails['workExperience'];
                // $currentSalary = $professionalDetails['salary'];
                // $expectedSalary = $professionalDetails['expectedSalary'];

                $query = "select emailId from users where id=" . $json['userId'] . "";
                $queryToCheckData = mysqli_query($databaseConnection, $query);

                if (mysqli_num_rows($queryToCheckData) > 0) {

                    $emailId = mysqli_fetch_assoc($queryToCheckData)['emailId'];




                     //
                    //"13,21,422,424,435,440,471,604,716,726,1014,1063,1099,1102"
                    if (!empty($userSkills)) {

                        // Fetch existing skills for the user from candidate_skills using both candidateId and emailId
                        $existingSkillsQuery = "
                            SELECT skillId, candidateId 
                            FROM candidate_skills 
                            WHERE candidateId = $user_id
                            OR emailId = (SELECT emailId FROM users WHERE id = $user_id);
                        ";

                        $existingSkillsResult = mysqli_query($databaseConnection, $existingSkillsQuery);
                        $existingSkills = [];
                        while ($row = mysqli_fetch_assoc($existingSkillsResult)) {
                            $existingSkills[] = $row['skillId']; // Collect existing skill IDs
                        }

                        // Process the incoming skill IDs
                        $skillsArray = explode(',', $userSkills);
                        $skillsArray = array_map('intval', $skillsArray); // Convert IDs to integers
                        $skillsList = implode(',', $skillsArray);

                        // Query to fetch skill names and IDs
                        $query = "SELECT id, favourite_subject AS name FROM favourite_subject WHERE id IN ($skillsList)";
                        // echo $query;
                        $result = mysqli_query($databaseConnection, $query);

                        // Initialize array to store skills
                        $newSkillsArray = [];

                        if ($result && mysqli_num_rows($result) > 0) {
                            while ($row = mysqli_fetch_assoc($result)) {
                                $newSkillsArray[] = $row; // Store each skill
                            }
                        }

                        // var_dump($newSkillsArray);
                        // exit();

                        // Process skills: Insert new, Delete old, Do nothing for matching ones
                        foreach ($newSkillsArray as $skill) {
                            $skillId = $skill['id'];
                            $skillName = mysqli_real_escape_string($databaseConnection, $skill['name']);
                            $yoe = 0;
                            $projectDetails = ''; // Set project details here if needed

                            // Check if the skill is already in the existing skills array
                            if (!in_array($skillId, $existingSkills)) {
                                // Insert new skill if not already present
                                $insertQuery = "
                                    INSERT INTO candidate_skills (candidateId, skillId, name, yoe, projectDetails, emailId)
                                    VALUES ($user_id, $skillId, '$skillName', '$yoe', " . ($projectDetails !== null ? "'$projectDetails'" : "NULL") . ", 
                                    (SELECT emailId FROM users WHERE id = $user_id))
                                ";

                                // echo $insertQuery;

                                // Execute insert query
                                $insertQueryResult = mysqli_query($databaseConnection, $insertQuery);

                                if (!$insertQueryResult) {
                                    $to_encode = array(
                                        'result' => "error",
                                        'error' => "Error inserting skill: " . mysqli_error($databaseConnection),
                                        'status' => -6
                                    );
                                }
                            }
                        }

                        // Update skills that exist in both existingSkills and newSkillsArray
                        foreach ($newSkillsArray as $skill) {
                            $skillId = $skill['id'];

                            if (in_array($skillId, $existingSkills)) {
                                // Check if the skill exists in candidate_skills but has no candidateId set
                                $updateQuery = "
                                    UPDATE candidate_skills 
                                    SET candidateId = IF(candidateId IS NULL, $user_id, candidateId)
                                    WHERE skillId = $skillId 
                                    AND (candidateId IS NULL OR candidateId != $user_id)
                                    AND emailId = (SELECT emailId FROM users WHERE id = $user_id);
                                ";

                                $updateQueryResult = mysqli_query($databaseConnection, $updateQuery);

                                if (!$updateQueryResult) {
                                    $to_encode = array(
                                        'result' => "error",
                                        'error' => "Error updating skill: " . mysqli_error($databaseConnection),
                                        'status' => -8
                                    );
                                }
                            }
                        }

                        // Delete skills that are no longer in the $newSkillsArray but are in the existingSkills
                        foreach ($existingSkills as $existingSkillId) {
                            if (!in_array($existingSkillId, $skillsArray)) {
                                // Delete skill if it exists in existingSkills but not in the new skills list
                                $deleteQuery = "
                                    DELETE FROM candidate_skills
                                    WHERE candidateId = $user_id AND skillId = $existingSkillId
                                ";

                                $deleteQueryResult = mysqli_query($databaseConnection, $deleteQuery);

                                if (!$deleteQueryResult) {
                                    $to_encode = array(
                                        'result' => "error",
                                        'error' => "Error deleting skill: " . mysqli_error($databaseConnection),
                                        'status' => -7
                                    );
                                }
                            }
                        }
                    }
                    //



                    if (!empty($skills)) {
                        foreach ($skills as $skill) {
                            $skillId = (int) $skill['skillId'];
                            $name = $databaseConnection->real_escape_string($skill['name']);
                            $yoe = (int) $skill['years'];
                            $projectDetails = isset($skill['projects']) && !empty($skill['projects']) ? $databaseConnection->real_escape_string($skill['projects']) : null;

                            // Check if the skill already exists for the candidate
                            $checkQuery = "
                                SELECT skillId, candidateId 
                                FROM candidate_skills 
                                WHERE (candidateId = $jsonUserId OR emailId = (SELECT emailId FROM users WHERE id = $jsonUserId)) 
                                AND skillId = '$skillId';
                            ";

                            $result = $databaseConnection->query($checkQuery);

                            if ($result && $result->num_rows > 0) {
                                // Skill exists, get current candidateId
                                $existingSkill = $result->fetch_assoc();

                                // If candidateId in the database is different from the provided one, update it
                                if ($existingSkill['candidateId'] != $jsonUserId) {
                                    // Update the candidateId only if it's different
                                    $updateCandidateIdQuery = "
                                        UPDATE candidate_skills 
                                        SET candidateId = $jsonUserId
                                        WHERE skillId = '$skillId' AND emailId = (SELECT emailId FROM users WHERE id = $jsonUserId)
                                    ";
                                    $databaseConnection->query($updateCandidateIdQuery);
                                }

                                // Update other skill details (yoe and projectDetails)
                                $updateQuery = "
                                    UPDATE candidate_skills 
                                    SET yoe = $yoe, projectDetails = " . ($projectDetails !== null ? "'$projectDetails'" : "NULL") . " 
                                    WHERE skillId = '$skillId' AND candidateId = $jsonUserId
                                ";
                                $databaseConnection->query($updateQuery);
                            } else {
                                // Skill does not exist, insert it
                                $insertQuery = "
                                    INSERT INTO candidate_skills (candidateId, skillId, name, yoe, projectDetails, emailId) 
                                    VALUES ($jsonUserId, $skillId, '$name', $yoe, " . ($projectDetails !== null ? "'$projectDetails'" : "NULL") . ", (SELECT emailId FROM users WHERE id = $jsonUserId))
                                ";
                                // echo $insertQuery;
                                $databaseConnection->query($insertQuery);
                            }

                        }

                        $checkQuery = "
                            SELECT GROUP_CONCAT(skillId) AS skillIds 
                            FROM candidate_skills 
                            WHERE emailId = '$emailId';
                        ";

                        $result = mysqli_query($databaseConnection, $checkQuery);
                        $skillIds = null; // Default to NULL if no skills are found

                        if ($result && mysqli_num_rows($result) > 0) {
                            $row = mysqli_fetch_assoc($result);
                            $skillIds = $row['skillIds'] ?? null; // Use the result if available, otherwise NULL
                        }

                        // Now, $skillIds will either contain the comma-separated string or remain NULL

                    } else {
                        $checkQuery = "
                            SELECT GROUP_CONCAT(skillId) AS skillIds 
                            FROM candidate_skills 
                            WHERE emailId = '$emailId';
                        ";

                        $result = mysqli_query($databaseConnection, $checkQuery);
                        $skillIds = null; // Default to NULL if no skills are found

                        if ($result && mysqli_num_rows($result) > 0) {
                            $row = mysqli_fetch_assoc($result);
                            $skillIds = $row['skillIds'] ?? null; // Use the result if available, otherwise NULL
                        }
                    }

                    $data = "update professionaldetails set noticePeriod = '" . $noticePeriod . "',workExperience = '" . $workExperience . "', currentLocation = '" . $currentLocation . "', employmentStatus = '" . $employmentStatus . "',assessmentDeclaration = '" . $assessmentDeclaration . "',";

                    if (is_null($jobType)) {
                        $data .= "jobType=NULL, ";
                    } else {
                        $data .= " jobType='" . $jobType . "',";
                    }
                    if (is_null($currentCompany)) {
                        $data .= "currentCompany=NULL, ";
                    } else {
                        $data .= " currentCompany='" . $currentCompany . "',";
                    }
                    if (is_null($workExperience)) {
                        $data .= "workExperience=NULL, ";
                    } else {
                        $data .= "workExperience='" . $workExperience . "',";
                    }
                    if (is_null($currentSalary)) {
                        $data .= "salary=NULL, ";
                    } else {
                        $data .= "salary='" . $currentSalary . "',";
                    }
                    if (is_null($expectedSalary)) {
                        $data .= "expectedSalary=NULL, ";
                    } else {
                        $data .= " expectedSalary='" . $expectedSalary . "',";
                    }
                    if (is_null($currentLocation)) {
                        $data .= "currentLocation=NULL, ";
                    } else {
                        $data .= " currentLocation='" . $currentLocation . "',";
                    }

                    if (is_null($resume)) {
                        $data .= "resume=NULL, ";
                    } else {
                        $data .= " resume='" . $resume . "',";
                    }

                    if (is_null($currentProcess)) {
                        $data .= "currentProcess=NULL, ";
                    } else {
                        $data .= " currentProcess='" . $currentProcess . "',";
                    }

                    if (is_null($processType)) {
                        $data .= "processType=NULL, ";
                    } else {
                        $data .= " processType='" . $processType . "',";
                    }

                    if (is_null($clienttype)) {
                        $data .= "clienttype=NULL, ";
                    } else {
                        $data .= " clienttype='" . $clienttype . "',";
                    }

                    if (is_null($shift)) {
                        $data .= "shift=NULL, ";
                    } else {
                        $data .= " shift='" . $shift . "',";
                    }

                    if (is_null($candidateStatus)) {
                        $data .= "candidateStatus=NULL,";
                    } else {
                        $data .= " candidateStatus='" . $candidateStatus . "',";
                    }

                    if (is_null($offer)) {
                        $data .= "offer=NULL, ";
                    } else {
                        $data .= " offer='" . $offer . "',";
                    }

                    if (is_null($skillIds)) {
                        $data .= "skills=NULL, ";
                    } else {
                        $data .= " skills='" . $skillIds . "',";
                    }

                    if (is_null($offeredCTC)) {
                        $data .= "offeredCTC=NULL ";
                    } else {
                        $data .= " offeredCTC='" . $offeredCTC . "'";
                    }

                    $data .= " where candidateId='" . $json['userId'] . "'";

                    // echo $data;
                    // exit();

                    $userData = mysqli_query($databaseConnection, $data);

                    // interviewId is null
                    $query2 = "select * from interviewSchedule where emailId='" . $emailId . "' and preInterviewId=" . $json['preInterviewId'] . " order by id desc";

                    // var_dump($query2);

                    $queryToCheckData2 = mysqli_query($databaseConnection, $query2);

                    if (mysqli_num_rows($queryToCheckData2) > 0) {

                        $row = mysqli_fetch_assoc($queryToCheckData2);
                        // var_dump($row['interviewId']);
                        // echo $row['interviewId'];
                        if (empty($row['interviewId'])) {

                            $sql = "UPDATE interviewSchedule SET 
                                outstationDeclaration = " . ($outstationDeclaration !== null ? "'" . $outstationDeclaration . "'" : "NULL") . ", 
                                scheduleTime = " . ($interviewDatetime !== null ? "'" . $interviewDatetime . "'" : "NULL") . ", 
                                candidate_id = '" . $jsonUserId . "', 
                                employmentStatus = '" . $employmentStatus . "', 
                                noticePeriod = '" . $noticePeriod . "',
                                skillValues = " . ($skillIds !== null ? "'" . $skillIds . "'" : "NULL") . ", 
                                company_id = '" . $json['companyId'] . "',";



                            if (is_null($jobType)) {
                                $sql .= "jobType=NULL, ";
                            } else {
                                $sql .= " jobType='" . $jobType . "',";
                            }

                            if (is_null($joiningTimeline)) {
                                $sql .= "joiningTimeline=NULL, ";
                            } else {
                                if (is_array($json['joiningTimeline'])) {
                                    $sql .= " joiningTimeline='" . implode(',', $json['joiningTimeline']) . "',";
                                } else {
                                    $sql .= " joiningTimeline='" . $json['joiningTimeline'] . "',";
                                }
                            }

                            if (is_null($currentProcess)) {
                                $sql .= "currentProcess=NULL, ";
                            } else {
                                $sql .= " currentProcess='" . $currentProcess . "',";
                            }

                            if (is_null($processType)) {
                                $sql .= "processType=NULL, ";
                            } else {
                                $sql .= " processType='" . $processType . "',";
                            }

                            if (is_null($currentCompany)) {
                                $sql .= "currentCompany=NULL, ";
                            } else {

                                $sql .= " currentCompany='" . $currentCompany . "',";
                            }
                            if (is_null($workExperience)) {
                                $sql .= "workExperience=NULL, ";
                            } else {
                                $sql .= " workExperience='" . $workExperience . "',";
                            }
                            if (is_null($currentSalary)) {
                                $sql .= "currentSalary=NULL, ";
                            } else {
                                $sql .= " currentSalary='" . $currentSalary . "',";
                            }
                            if (is_null($expectedSalary)) {
                                $sql .= "expectedSalary=NULL, ";
                            } else {
                                $sql .= " expectedSalary='" . $expectedSalary . "',";
                            }

                            if (is_null($currentLocation)) {
                                $sql .= "currentLocation=NULL, ";
                            } else {
                                $sql .= " currentLocation='" . $currentLocation . "',";
                            }

                            if (is_null($clienttype)) {
                                $sql .= "clienttype=NULL, ";
                            } else {
                                $sql .= " clienttype='" . $clienttype . "',";
                            }

                            if (is_null($processPreference)) {
                                $sql .= "processPreference=NULL, ";
                            } else {

                                $sql .= " processPreference='" . $processPreference . "',";
                            }

                            if (is_null($shift)) {
                                $sql .= "shift=NULL, ";
                            } else {
                                $sql .= " shift='" . $shift . "',";
                            }


                            // if (is_null($skillValues)) {
                            //     $sql .= "skillValues=NULL, ";
                            // } else {

                            //     $sql .= " skillValues='" . $skillValues . "',";
                            // }
                            if (is_null($resume)) {
                                // $sql .="resume=NULL ";
                            } else {
                                $sql .= " resume='" . $json['resume'] . "',";
                            }
                            if (is_null($offer)) {
                                $data .= "offer=NULL, ";
                            } else {
                                $data .= " offer='" . $offer . "',";
                            }

                            if (is_null($offeredCTC)) {
                                $data .= "offeredCTC=NULL, ";
                            } else {
                                $data .= " offeredCTC='" . $offeredCTC . "',";
                            }

                            if (is_null($candidateStatus)) {
                                $sql .= "candidateStatus=NULL ";
                            } else {
                                $sql .= " candidateStatus='" . $candidateStatus . "'";
                            }

                            $sql .= " where emailId='" . $emailId . "' and preInterviewId=" . $json['preInterviewId'] . "";

                            // var_dump($sql);
                            // exit();
                            $updateSchedule = mysqli_query($databaseConnection, $sql);
                            if ($updateSchedule) {
                                $to_encode = array(
                                    'status' => 1,
                                    'action' => "update",
                                );
                            } else {
                                $to_encode = array(
                                    'status' => 0,
                                    'message' => "updation in schedule failed",
                                );
                            }

                        } else {

                            // Construct the SQL query using the defined variables

                            $queryToInsert = "
                                INSERT INTO `interviewSchedule`(
                                    `outstationDeclaration`, `company_id`, `candidate_id`, `candidateName`, `emailId`, `mobileNumber`, 
                                    `scheduleTime`, `firstScheduleDate`, `sectorId`, `jobType`, `currentCompany`, `currentSalary`, 
                                    `expectedSalary`, `currentProcess`, `processType`, `clientType`, `workExperience`, `employmentStatus`, 
                                    `noticePeriod`, `processPreference`, `shift`, `workLocationPreference`, `timeToCall`, `preferedJobType`, 
                                    `currentLocation`, `preferredWorkLocation`, `languages`, `joiningTimeline`, `preferredrole`, 
                                    `certiValues`, `avgTenure`, `preInterviewId`, `resume`, `url`, `candidateStatus`, 
                                    `apmStatus`, `apm`, `promotionSource`, `offer`,`skillValues`, `offeredCTC`
                                ) 
                                VALUES (
                                    " . ($outstationDeclaration == NULL ? 'NULL' : "'" . $outstationDeclaration . "'") . ",
                                    " . $jsonCompanyId . ",
                                    " . $jsonUserId . ",
                                    (SELECT firstName FROM users WHERE id=" . $jsonUserId . "),
                                    (SELECT emailId FROM users WHERE id=" . $jsonUserId . "),
                                    " . ($mobileNumber == NULL ? 'NULL' : "'" . $mobileNumber . "'") . ",
                                    " . ($interviewDatetime == NULL ? 'NULL' : "'" . $interviewDatetime . "'") . ",
                                    " . $firstScheduleDate . ",
                                    " . $jsonSectorId . ",
                                    " . ($jobType == "NULL" ? 'NULL' : "'" . $jobType . "'") . ",
                                    " . ($currentCompany == "NULL" ? 'NULL' : "'" . $currentCompany . "'") . ",
                                    " . ($currentSalary == "NULL" ? 'NULL' : "'" . $currentSalary . "'") . ",
                                    " . ($expectedSalary == "NULL" ? 'NULL' : "'" . $expectedSalary . "'") . ",
                                    " . ($currentProcess == "NULL" ? 'NULL' : "'" . $currentProcess . "'") . ",
                                    " . ($processType == "NULL" ? 'NULL' : "'" . $processType . "'") . ",
                                    " . ($clienttype == "NULL" ? 'NULL' : "'" . $clienttype . "'") . ",
                                    " . ($workExperience == "NULL" ? 'NULL' : "'" . $workExperience . "'") . ",
                                    " . ($employmentStatus == "NULL" ? 'NULL' : "'" . $employmentStatus . "'") . ",
                                    " . ($noticePeriod == "NULL" ? 'NULL' : "'" . $noticePeriod . "'") . ",
                                    " . ($processPreference == "NULL" ? 'NULL' : "'" . $processPreference . "'") . ",
                                    " . ($shift == "NULL" ? 'NULL' : "'" . $shift . "'") . ",
                                    " . ($workLocation == "NULL" ? 'NULL' : "'" . $workLocation . "'") . ",
                                    " . ($convinientTime == "NULL" ? 'NULL' : "'" . $convinientTime . "'") . ",
                                    " . ($preferedJobType == "NULL" ? 'NULL' : "'" . $preferedJobType . "'") . ",
                                    " . ($currentLocation == "NULL" ? 'NULL' : "'" . $currentLocation . "'") . ",
                                    " . ($preferredWorkLocation == "NULL" ? 'NULL' : "'" . $preferredWorkLocation . "'") . ",
                                    " . ($languages == "NULL" ? 'NULL' : "'" . $languages . "'") . ",
                                    " . ($joiningTimeline == "NULL" ? 'NULL' : "'" . $joiningTimeline . "'") . ",
                                    " . ($preferredrole == "NULL" ? 'NULL' : "'" . $preferredrole . "'") . ",
                                    " . ($certiValues == "NULL" ? 'NULL' : "'" . $certiValues . "'") . ",
                                    " . ($avgTenure == "NULL" ? 'NULL' : "'" . $avgTenure . "'") . ",
                                    '" . $preInterviewId . "',
                                    " . ($resume == "NULL" ? 'NULL' : "'" . $resume . "'") . ",
                                    " . ($url == '' ? 'NULL' : "'" . $url . "'") . ",
                                    " . ($candidateStatus == '' ? 'NULL' : "'" . $candidateStatus . "'") . ",
                                    " . $row['apmStatus'] . ",
                                    " . ($row['apm'] == '' ? 'NULL' : "'" . $row['apm'] . "'") . ",
                                    '" . $row['promotionSource'] . "',
                                    " . ($offer == "NULL" ? 'NULL' : "'" . $offer . "'") . ",
                                    " . ($skillIds == "NULL" ? 'NULL' : "'" . $skillIds . "'") . ",
                                    " . ($offeredCTC == "NULL" ? 'NULL' : "'" . $offeredCTC . "'") . "
                                )
                            ";

                            // echo $queryToInsert;
                            // exit();

                            $result = mysqli_query($databaseConnection, $queryToInsert);
                            // var_dump($result);
                            if ($result) {
                                $insertedId = mysqli_insert_id($databaseConnection);
                                $to_encode = array(
                                    'status' => 1,
                                    'action' => "insert",
                                );

                            } else {
                                $to_encode = array(
                                    'status' => 1,
                                    'message' => mysqli_error($databaseConnection)
                                );
                            }

                        }
                    } else {
                        // Construct the SQL query using the defined variables
                        $queryToInsert = "INSERT INTO `interviewSchedule`(
                            `outstationDeclaration`, `company_id`, `candidate_id`, `candidateName`, `emailId`, `mobileNumber`, 
                            `scheduleTime`, `firstScheduleDate`, `sectorId`, `jobType`, `currentCompany`, `currentSalary`, 
                            `expectedSalary`, `currentProcess`, `processType`, `clientType`, `workExperience`, `employmentStatus`, 
                            `noticePeriod`, `processPreference`, `shift`, `workLocationPreference`, `timeToCall`, `preferedJobType`, 
                            `currentLocation`, `preferredWorkLocation`, `languages`, `joiningTimeline`, `preferredrole`, `certiValues`, `avgTenure`, `preInterviewId`, `resume`, `promotionSource`, `url`, `candidateStatus`, 
                            `offer`,`skillValues`, `offeredCTC`
                        ) VALUES (
                            " . ($outstationDeclaration == NULL ? 'NULL' : ("'" . $outstationDeclaration . "'")) . ",
                            " . $jsonCompanyId . ",
                            " . $jsonUserId . ",
                            (SELECT firstName FROM users WHERE id = " . $jsonUserId . "),
                            (SELECT emailId FROM users WHERE id = " . $jsonUserId . "),
                            " . ($mobileNumber == "NULL" ? 'NULL' : ("'" . $mobileNumber . "'")) . ",
                            " . ($interviewDatetime == NULL ? 'NULL' : ("'" . $interviewDatetime . "'")) . ",
                            " . $firstScheduleDate . ",
                            " . $jsonSectorId . ",
                            " . ($jobType == "NULL" ? 'NULL' : ("'" . $jobType . "'")) . ",
                            " . ($currentCompany == "NULL" ? 'NULL' : ("'" . $currentCompany . "'")) . ",
                            " . ($currentSalary == "NULL" ? 'NULL' : ("'" . $currentSalary . "'")) . ",
                            " . ($expectedSalary == "NULL" ? 'NULL' : ("'" . $expectedSalary . "'")) . ",
                            " . ($currentProcess == "NULL" ? 'NULL' : ("'" . $currentProcess . "'")) . ",
                            " . ($processType == "NULL" ? 'NULL' : ("'" . $processType . "'")) . ",
                            " . ($clienttype == "NULL" ? 'NULL' : ("'" . $clienttype . "'")) . ",
                            " . ($workExperience == "NULL" ? 'NULL' : ("'" . $workExperience . "'")) . ",
                            " . ($employmentStatus == "NULL" ? 'NULL' : ("'" . $employmentStatus . "'")) . ",
                            " . ($noticePeriod == "NULL" ? 'NULL' : ("'" . $noticePeriod . "'")) . ",
                            " . ($processPreference == "NULL" ? 'NULL' : ("'" . $processPreference . "'")) . ",
                            " . ($shift == "NULL" ? 'NULL' : ("'" . $shift . "'")) . ",
                            " . ($workLocation == "NULL" ? 'NULL' : ("'" . $workLocation . "'")) . ",
                            " . ($convinientTime == "NULL" ? 'NULL' : ("'" . $convinientTime . "'")) . ",
                            " . ($preferedJobType == "NULL" ? 'NULL' : ("'" . $preferedJobType . "'")) . ",
                            " . ($currentLocation == "NULL" ? 'NULL' : ("'" . $currentLocation . "'")) . ",
                            " . ($preferredWorkLocation == "NULL" ? 'NULL' : ("'" . $preferredWorkLocation . "'")) . ",
                            " . ($languages == "NULL" ? 'NULL' : ("'" . $languages . "'")) . ",
                            " . ($joiningTimeline == "NULL" ? 'NULL' : ("'" . $joiningTimeline . "'")) . ",
                            " . ($preferredrole == "NULL" ? 'NULL' : ("'" . $preferredrole . "'")) . ",
                            " . ($certiValues == "NULL" ? 'NULL' : ("'" . $certiValues . "'")) . ",
                            " . ($avgTenure == "NULL" ? 'NULL' : ("'" . $avgTenure . "'")) . ",
                            '" . $preInterviewId . "',
                            " . ($resume == "NULL" ? 'NULL' : ("'" . $resume . "'")) . ",
                            " . ($promotionSource == '' ? 'NULL' : ("'" . $promotionSource . "'")) . ",
                            " . ($url == '' ? 'NULL' : ("'" . $url . "'")) . ",
                            " . ($candidateStatus == '' ? 'NULL' : ("'" . $candidateStatus . "'")) . ",
                            " . ($offer == "NULL" ? 'NULL' : ("'" . $offer . "'")) . ",
                            " . ($skillIds == "NULL" ? 'NULL' : "'" . $skillIds . "'") . ",
                            " . ($offeredCTC == "NULL" ? 'NULL' : ("'" . $offeredCTC . "'")) . "
                        )";


                        // echo $queryToInsert;

                        $result = mysqli_query($databaseConnection, $queryToInsert);
                        // var_dump($result);
                        if ($result) {
                            $insertedId = mysqli_insert_id($databaseConnection);
                            $to_encode = array(
                                'status' => 1,
                                'action' => "insert",
                            );

                        } else {
                            $to_encode = array(
                                'status' => 1,
                                'message' => mysqli_error($databaseConnection)
                            );
                        }
                    }


                    if (!empty($json['userAction'])) {
                        if ($json['userAction'] == 'takeInterview') {

                        }
                        else {

                            if ($serviceType == 'RAS') {
                                $emailIdResult = '';
                                $query11 = "SELECT emailId FROM users WHERE id = '" . $jsonUserId . "'";
                                $getData = mysqli_query($databaseConnection, $query11);

                                if (mysqli_num_rows($getData) > 0) {
                                    $result = mysqli_fetch_assoc($getData);
                                    $emailIdResult = $result['emailId'];
                                }
                                $jSkill = "select jobMatch('$emailIdResult', $preInterviewId) AS jobMatchResult";
                                $result1 = mysqli_query($databaseConnection, $jSkill);
                                $jobMatchResult = '';
                                if ($result1) {
                                    $resultData = mysqli_fetch_assoc($result1);
                                    if ($resultData) {
                                        $jobMatchResult = $resultData['jobMatchResult'];

                                    }
                                }
                                // echo $jobMatchResult;
                                // exit();

                                if (!empty($jobMatchResult)) {
                                    mysqli_query($databaseConnection, "update interviewSchedule set jobMatch = '" . $jobMatchResult . "' where candidate_id in(" . $jsonUserId . ") and preInterviewId in(" . $preInterviewId . ")");
                                }

                                if ($jobMatchResult == 'YES') {
                                    $apmStatus = mysqli_query($databaseConnection, "update interviewSchedule set apmStatus=4, candidateStatus='Profile Match' where candidate_id in(" . $jsonUserId . ") and preInterviewId in(" . $preInterviewId . ")");

                                    if ($apmStatus) {
                                        // $to_encode = array(
                                        //     'status' => 1,
                                        //     'action' => "insert with Profile Match",
                                        // );
                                    } else {
                                        $to_encode = array(
                                            'status' => -1,
                                            'message' => mysqli_error($databaseConnection)
                                        );
                                    }

                                } else {
                                    $apmStatus = mysqli_query($databaseConnection, "update interviewSchedule set apmStatus=4, candidateStatus='Profile Mismatch' where candidate_id in(" . $jsonUserId . ") and preInterviewId in(" . $preInterviewId . ")");

                                    if ($apmStatus) {
                                        // $to_encode = array(
                                        //     'status' => 1,
                                        //     'action' => "insert with Profile Mismatch",
                                        // );
                                    } else {
                                        $to_encode = array(
                                            'status' => -1,
                                            'message' => mysqli_error($databaseConnection)
                                        );
                                    }
                                }

                            } else if ($serviceType == 'IAS') {

                                $apmStatus = mysqli_query($databaseConnection, "update interviewSchedule set apmStatus=4, candidateStatus='Interview Scheduled' where candidate_id in(" . $jsonUserId . ") and preInterviewId in(" . $preInterviewId . ")");

                                if ($apmStatus) {
                                    // $to_encode = array(
                                    //     'status' => 1,
                                    //     'action' => "insert with apmStatus 4",
                                    // );
                                } else {
                                    $to_encode = array(
                                        'status' => -1,
                                        'message' => mysqli_error($databaseConnection)
                                    );
                                }

                            }

                            $leadStatus_sql = "UPDATE resume_apm 
                            SET leadStatus = 'Applied' 
                            WHERE emailId = '$emailId' 
                            AND preInterviewId = " . $json['preInterviewId'] . "";

                            $leadStatus_query = mysqli_query($databaseConnection, $leadStatus_sql);



                            $submission_sql = "update interviewSchedule set submissionFlag = 'Y' where  emailId='" . $emailId . "' and preInterviewId=" . $json['preInterviewId'] . "";

                            $submission_query = mysqli_query($databaseConnection, $submission_sql);

                            if ($submission_query) {
                                // $to_encode = array(
                                //     'status' => 1,
                                //     'action' => "update in submissionFlag",
                                // );
                            } else {
                                $to_encode = array(
                                    'status' => 0,
                                    'message' => "updation in submissionFlag failed",
                                );
                            }

                        }
                    }

                    // if ($instituteCode) {
                    //     $instituteCode = mysqli_query($databaseConnection, "update users set instituteCode = '$instituteCode' WHERE id = '" . $jsonUserId . "'");

                    //     if ($instituteCode) {
                    //         // $to_encode = array(
                    //         //     'status' => 1,
                    //         //     'action' => "insert with Profile Match",
                    //         // );
                    //     } else {
                    //         $to_encode = array(
                    //             'status' => -1,
                    //             'message' => mysqli_error($databaseConnection)
                    //         );
                    //     }

                    // }

                    if ($instituteCode || !empty($json['mobileNumber'])) {
                        $updateFields = [];
                        if ($instituteCode) {
                            $updateFields[] = "instituteCode = '" . mysqli_real_escape_string($databaseConnection, $instituteCode) . "'";
                        }
                        if (!empty($json['mobileNumber'])) {
                            $updateFields[] = "mobileNumber = '" . mysqli_real_escape_string($databaseConnection, $json['mobileNumber']) . "'";
                        }
                        $updateQuery = "UPDATE users SET " . implode(', ', $updateFields) . " WHERE id = '" . $jsonUserId . "'";
                        $updateResult = mysqli_query($databaseConnection, $updateQuery);

                        if ($updateResult) {
                            // $to_encode = array(
                            //     'status' => 1,
                            //     'action' => "insert with Profile Match",
                            // );
                        } else {
                            $to_encode = array(
                                'status' => -1,
                                'message' => mysqli_error($databaseConnection)
                            );
                        }
                    }

                }
            } else {
                $to_encode = array(
                    'status' => 0,
                    'message' => "No professional details found for user with ID" . $user_id
                );
            }

        } else {
            $to_encode = array(
                'status' => 0,
                'message' => "Error executing query: " . mysqli_error($databaseConnection)
            );
        }
    }
    echo json_encode($to_encode);
}
else if (isset($_GET['scheduleInterview'])) {
    // this method is added by arun on 31 Jan 2023 to schedule the interviews
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if ($json) {
        $companyId = $json['companyId'];
        //$schedule = $json['scheduled'];
        $schedule = isset($json['scheduled']) ? $json['scheduled'] : null;
        $interviewLink = $json['interviewLink'];
        $candidateName = $json['name'];
        $candidateEmailId = $json['emailId'];
        $candidateMobile = $json['mobile'];
        $recruiterId = "";
        $RecruitingComapanyName = "GoPrac";
        $interviewName = "GoPrac";




        if ($json['preInterviewId'] != '') {
            $Query = mysqli_query($databaseConnection, "select hiringCompanies as name,interviewName from preInterview where id in(" . implode(",", $json['preInterviewId']) . ")");

            $Result = mysqli_fetch_assoc($Query);
            if ($Result['name'] != NULL) {
                $RecruitingComapanyName = $Result['name'];
            }
            if ($Result['interviewName'] != NULL) {
                $interviewName = $Result['interviewName'];
            }
        }


        // mail content

        $scheduledTime = date('h:i A', strtotime($schedule));
        $scheduleDate = date('l, F, d, Y', strtotime($schedule));

        $templateQuery = "select subject,details from candidateEmailTemplate where status = 'Interview Scheduled' ";
        $templateQueryResult = mysqli_query($databaseConnection, $templateQuery);
        $msg = mysqli_fetch_assoc($templateQueryResult);

        $templateQuery1 = "select subject from candidateEmailTemplate where status = 'Interview Scheduled' ";
        $templateQueryResult1 = mysqli_query($databaseConnection, $templateQuery1);
        $msg1 = mysqli_fetch_assoc($templateQueryResult1);

        // Using str_replace
        $placeholders = array('{interview name}', '{student name}', '{time}', '{date}', 'interviewLink', 'interviewLink', '{interview}');
        $values = array($interviewName, $candidateName, $scheduledTime, $scheduleDate, $interviewLink, $interviewLink, $RecruitingComapanyName);
        $template = str_replace($placeholders, $values, $msg);

        $placeholders1 = array('{interview name}');
        $values1 = array($interviewName);
        $template1 = str_replace($placeholders1, $values1, $msg1);

        $dts = $template['details'];
        $dts1 = $template1['subject'];

        $url = $interviewLink;
        $components = explode('/', $url);
        $modifiedUrl = isset($components[3]) ? $components[3] : '';

        $data = array();
        $data["companyname"] = $interviewName;
        $data["candidateName"] = $candidateName;
        $data["scheduledTime"] = $scheduledTime;
        $data["scheduleDate"] = $scheduleDate;
        //modify by shrikant : 18/1/2024
        // $data["interviewLink"] = $modifiedUrl;
        $data["interviewLink"] = $url;

        if ($json['resendMail'] == 1) {
            sendEmailToUser($candidateEmailId, null, $dts1, $dts);
            $to_encode = array(
                'status' => 1,
                'data' => 'Mail sent'
            );
            // calling whatsapp function to send messages
            whatsAppMsg($databaseConnection, $candidateMobile, $data, "scheduled");

        } else if ($json['resendMail'] == 0) {
            $str = "";
            if ($json['tokenfield'] != '') {
                $str = str_replace(', ', ',', $json['tokenfield']);
            }

            $jobType = "";
            $preferedJobType = "";
            $currentProcess = "";
            $processType = "";
            $currentCompany = "";
            $clienttype = "";
            $processPreference = "";
            $shift = "";
            $workLocation = "";
            $convinientTime = "";
            $expectedsalary = "";
            $joiningTimeline = "";
            $noticePeriod = "";
            // $joiningPeriod="";
            $workExperience = "";
            $currentsalary = "";
            $currentLocation = "";
            $languages = "";
            $preferredworkLocation = "";
            $candidateSource = "";
            $levelofInterview = "";
            $comment = "";

            $preferredrole = "";
            $joinstatus = "";

            $skillValues = "";
            $certiValues = "";
            $avgTenure = "";





            if ($json['jobType'] == '') {
                $jobType = NULL;
            }

            if ($json['recruiter'] == '') {
                $recruiterId = NULL;
            }

            if ($json['preferedJobType'] == '') {

                $preferedJobType = NULL;
            }

            if ($json['joiningTimeline'] == '') {

                $joiningTimeline = NULL;
            }

            if ($json['currentProcess'] == '') {

                $currentProcess = NULL;
            }

            if ($json['processType'] == '') {

                $processType = NULL;
            }

            if ($json['currentCompany'] == '') {

                $currentCompany = NULL;
            }

            if ($json['clienttype'] == '') {

                $clienttype = NULL;
            }

            if ($json['processPreference'] == '') {

                $processPreference = NULL;
            }

            if ($json['shift'] == '') {

                $shift = NULL;
            }

            if ($json['workLocation'] == '') {

                $workLocation = NULL;
            }

            if ($json['convinientTime'] == '') {

                $convinientTime = NULL;
            }

            if ($json['expectedsalary'] == '') {

                $expectedsalary = NULL;
            }
            if ($json['workexperience'] == '') {
                $workExperience = NULL;
            }

            if ($json['currentsalary'] == '') {
                $currentsalary = NULL;
            }

            if ($str == '') {
                $preferredworkLocation = NULL;
            }

            if ($json['noticePeriod'] == '') {
                $noticePeriod = NULL;
            }

            // if($json['joiningPeriod']==''){
            //     $joiningPeriod=NULL;
            // }

            if ($json['Language'] == '') {
                $languages = NULL;
            }

            if ($json['currentlocation'] == '') {
                $currentLocation = NULL;
            }

            if ($json['candidateSource'] == '') {
                $candidateSource = NULL;
            }

            if ($json['levelofInterview'] == '') {
                $levelofInterview = NULL;
            }

            if ($json['comment'] == '') {
                $comment = NULL;
            }



            if ($json['preferredrole'] == '') {
                $preferredrole = NULL;
            }

            if ($json['joinstatus'] == '') {
                $joinstatus = NULL;
            }

            if ($json['skillValues'] == '') {
                $skillValues = NULL;
            }
            if ($json['certiValues'] == '') {
                $certiValues = NULL;
            }

            if ($json['avgTenure'] == '') {
                $avgTenure = NULL;
            }


            if (!empty($json['resume'])) {
                if (is_array($json['resume'])) {
                    $resume = implode(',', $json['resume']);
                } else {
                    $resume = $json['resume'];
                }
            } else {
                $resume = null;
            }


            if ($json['id'] != '') {

                $queryToUpdate = "UPDATE `interviewSchedule` SET `company_id`=" . $companyId . ",`candidateName`='" . $candidateName . "',`emailId`='" . $candidateEmailId . "',`mobileNumber`=" . $candidateMobile . ",`url`='" . $interviewLink . "',`scheduleTime`='" . $schedule . "',`emailed`='N',preInterviewId='" . implode(',', $json['preInterviewId']) . "',`scheduleCount`=scheduleCount+1,`recruiterScheduleDate`=now(),";
                // echo $queryToUpdate ;

                if (is_null($jobType)) {
                    $queryToUpdate .= "jobType=NULL, ";
                } else {
                    $queryToUpdate .= " jobType='" . implode(',', $json['jobType']) . "',";
                }

                if (is_null($recruiterId)) {
                    $queryToUpdate .= "recruiterId=NULL, ";
                } else {
                    $queryToUpdate .= " recruiterId='" . implode(',', $json['recruiter']) . "',";
                }

                if (is_null($joiningTimeline)) {
                    $queryToUpdate .= "joiningTimeline=NULL, ";
                } else {
                    $queryToUpdate .= " joiningTimeline='" . implode(',', $json['joiningTimeline']) . "',";
                }

                if (is_null($preferedJobType)) {
                    $queryToUpdate .= "preferedJobType=NULL, ";
                } else {
                    $queryToUpdate .= "preferedJobType='" . implode(',', $json['preferedJobType']) . "',";
                }

                if (is_null($currentProcess)) {
                    $queryToUpdate .= "currentProcess=NULL, ";
                } else {
                    $queryToUpdate .= " currentProcess='" . implode(',', $json['currentProcess']) . "',";
                }

                if (is_null($processType)) {
                    $queryToUpdate .= "processType=NULL, ";
                } else {
                    $queryToUpdate .= " processType='" . implode(',', $json['processType']) . "',";
                }

                if (is_null($currentCompany)) {
                    $queryToUpdate .= "currentCompany=NULL, ";
                } else {
                    $queryToUpdate .= " currentCompany='" . $json['currentCompany'] . "',";
                }

                if (is_null($clienttype)) {
                    $queryToUpdate .= "clienttype=NULL, ";
                } else {
                    $queryToUpdate .= "clienttype='" . implode(',', $json['clienttype']) . "',";
                }

                if (is_null($processPreference)) {
                    $queryToUpdate .= "processPreference=NULL, ";
                } else {
                    $queryToUpdate .= "processPreference='" . implode(',', $json['processPreference']) . "',";
                }

                if (is_null($shift)) {
                    $queryToUpdate .= "shift=NULL, ";
                } else {
                    $queryToUpdate .= " shift='" . implode(',', $json['shift']) . "',";
                }

                if (is_null($workLocation)) {
                    $queryToUpdate .= "workLocationPreference=NULL, ";
                } else {
                    $queryToUpdate .= "workLocationPreference='" . implode(',', $json['workLocation']) . "',";
                }

                if (is_null($convinientTime)) {
                    $queryToUpdate .= "timeToCall=NULL, ";
                } else {
                    $queryToUpdate .= "timeToCall='" . implode(',', $json['convinientTime']) . "',";
                }

                if (is_null($expectedsalary)) {
                    $queryToUpdate .= "expectedsalary=NULL, ";
                } else {
                    $queryToUpdate .= " expectedsalary='" . $json['expectedsalary'] . "',";
                }

                // if(is_null($workExperience)){
                //     $queryToUpdate .="workExperience=NULL, ";
                // }else{
                //     $queryToUpdate .="workExperience = '" . implode(',', $json['workexperience']) . "',";
                // }

                if (is_null($workExperience)) {
                    $queryToUpdate .= "workExperience=NULL, ";
                } else {
                    $queryToUpdate .= "workExperience = '" . $json['workexperience'] . "',";
                }

                if (is_null($currentLocation)) {
                    $queryToUpdate .= "currentLocation=NULL, ";
                } else {
                    $queryToUpdate .= " currentLocation='" . implode(',', $json['currentlocation']) . "',";
                }

                if (is_null($languages)) {
                    $queryToUpdate .= "languages=NULL, ";
                } else {
                    $queryToUpdate .= "languages='" . implode(',', $json['Language']) . "',";
                }

                if (is_null($preferredworkLocation)) {
                    $queryToUpdate .= "preferredworkLocation=NULL, ";
                } else {
                    $queryToUpdate .= " preferredworkLocation='" . $str . "',";
                }

                if (is_null($currentsalary)) {
                    $queryToUpdate .= "currentSalary=NULL, ";
                } else {
                    $queryToUpdate .= " currentSalary='" . $json['currentsalary'] . "',";
                }

                if (is_null($noticePeriod)) {
                    $queryToUpdate .= "noticePeriod=NULL, ";
                } else {
                    $queryToUpdate .= " noticePeriod='" . implode(',', $json['noticePeriod']) . "',";
                }

                // if(is_null($joiningPeriod)){
                //     $queryToUpdate .="joiningPeriod=NULL, ";
                // }else{
                //     $queryToUpdate .=" joiningPeriod='" . implode(',', $json['joiningPeriod']) . "',";
                // }

                if (is_null($candidateSource)) {
                    $queryToUpdate .= "candidateSource=NULL, ";
                } else {
                    $queryToUpdate .= " candidateSource='" . implode(',', $json['candidateSource']) . "',";
                }

                if (is_null($levelofInterview)) {
                    $queryToUpdate .= "levelOfInterview=NULL, ";
                } else {
                    $queryToUpdate .= " levelOfInterview='" . implode(',', $json['levelofInterview']) . "',";
                }

                if (is_null($comment)) {
                    $queryToUpdate .= "comments=NULL, ";
                } else {
                    $queryToUpdate .= " comments='" . $json['comment'] . "',";
                }

                if (is_null($preferredrole)) {
                    $queryToUpdate .= "preferredrole=NULL, ";
                } else {
                    $queryToUpdate .= "preferredrole='" . $json['preferredrole'] . "',";
                }
                if (is_null($joinstatus)) {
                    $queryToUpdate .= "joinstatus=NULL, ";
                } else {
                    $queryToUpdate .= "joinstatus='" . $json['joinstatus'] . "',";
                }


                if (is_null($skillValues)) {
                    $queryToUpdate .= "skillValues=NULL, ";
                } else {
                    $queryToUpdate .= "skillValues='" . $json['skillValues'] . "',";
                }

                if (is_null($certiValues)) {
                    $queryToUpdate .= "certiValues=NULL, ";
                } else {
                    $queryToUpdate .= "certiValues='" . $json['certiValues'] . "',";
                }

                if (is_null($avgTenure)) {
                    $queryToUpdate .= "avgTenure=NULL, ";
                } else {
                    $queryToUpdate .= "avgTenure='" . $json['avgTenure'] . "',";
                }



                if (is_array($json['resume'])) {
                    $resumeString = implode(',', $json['resume']);
                    $queryToUpdate .= "resume='" . $resumeString . "'";
                } else if (is_null($resume)) {
                    $queryToUpdate .= "resume=NULL ";
                } else {
                    $queryToUpdate .= "resume='" . $json['resume'] . "'";
                }

                $queryToUpdate .= " WHERE id=" . $json['id'] . "";

                // echo $queryToUpdate;

                $queryToUpdateData = mysqli_query($databaseConnection, $queryToUpdate);
                if ($queryToUpdateData) {
                    sendEmailToUser($candidateEmailId, null, $dts1, $dts);
                    $to_encode = array(
                        'status' => 2,
                        'data' => 'Update Successfully'
                    );
                    whatsAppMsg($databaseConnection, $candidateMobile, $data, "scheduled");
                } else {
                    $to_encode = array(
                        'status' => -1,
                        'data' => 'Error While Update'
                    );
                }


            } else if ($json['id'] == '') {

                $queryToCheck = "SELECT * FROM `interviewSchedule` WHERE `preInterviewId` = " . implode(',', $json['preInterviewId']) . " AND `emailId` = '" . $candidateEmailId . "'";


                $queryToCheckData = mysqli_query($databaseConnection, $queryToCheck);

                if (mysqli_num_rows($queryToCheckData) > 0) {

                    $queryToUpdate = "UPDATE `interviewSchedule` SET `company_id`=" . $companyId . ",`candidateName`='" . $candidateName . "',`emailId`='" . $candidateEmailId . "',`mobileNumber`=" . $candidateMobile . ",`url`='" . $interviewLink . "',`scheduleTime`='" . $schedule . "',`emailed`='N',preInterviewId='" . implode(',', $json['preInterviewId']) . "',`scheduleCount`=scheduleCount+1,`recruiterScheduleDate`=now(),";

                    if (is_null($jobType)) {
                        $queryToUpdate .= "jobType=NULL, ";
                    } else {
                        $queryToUpdate .= " jobType='" . implode(',', $json['jobType']) . "',";
                    }

                    if (is_null($recruiterId)) {
                        $queryToUpdate .= "recruiterId=NULL, ";
                    } else {
                        $queryToUpdate .= " recruiterId='" . implode(",", $json['recruiter']) . "',";
                    }

                    if (is_null($joiningTimeline)) {
                        $queryToUpdate .= "joiningTimeline=NULL, ";
                    } else {
                        $queryToUpdate .= " joiningTimeline='" . implode(',', $json['joiningTimeline']) . "',";
                    }

                    if (is_null($preferedJobType)) {
                        $queryToUpdate .= "preferedJobType=NULL, ";
                    } else {
                        $queryToUpdate .= "preferedJobType='" . implode(',', $json['preferedJobType']) . "',";
                    }

                    if (is_null($currentProcess)) {
                        $queryToUpdate .= "currentProcess=NULL, ";
                    } else {
                        $queryToUpdate .= " currentProcess='" . implode(',', $json['currentProcess']) . "',";
                    }

                    if (is_null($processType)) {
                        $queryToUpdate .= "processType=NULL, ";
                    } else {
                        $queryToUpdate .= " processType='" . implode(',', $json['processType']) . "',";
                    }

                    if (is_null($currentCompany)) {
                        $queryToUpdate .= "currentCompany=NULL, ";
                    } else {
                        $queryToUpdate .= " currentCompany='" . $json['currentCompany'] . "',";
                    }

                    if (is_null($clienttype)) {
                        $queryToUpdate .= "clienttype=NULL, ";
                    } else {
                        $queryToUpdate .= "clienttype='" . implode(',', $json['clienttype']) . "',";
                    }

                    if (is_null($processPreference)) {
                        $queryToUpdate .= "processPreference=NULL, ";
                    } else {
                        $queryToUpdate .= "processPreference='" . implode(',', $json['processPreference']) . "',";
                    }

                    if (is_null($shift)) {
                        $queryToUpdate .= "shift=NULL, ";
                    } else {
                        $queryToUpdate .= " shift='" . implode(',', $json['shift']) . "',";
                    }

                    if (is_null($workLocation)) {
                        $queryToUpdate .= "workLocationPreference=NULL, ";
                    } else {
                        $queryToUpdate .= "workLocationPreference='" . implode(',', $json['workLocation']) . "',";
                    }

                    if (is_null($convinientTime)) {
                        $queryToUpdate .= "timeToCall=NULL, ";
                    } else {
                        $queryToUpdate .= "timeToCall='" . implode(',', $json['convinientTime']) . "',";
                    }

                    if (is_null($expectedsalary)) {
                        $queryToUpdate .= "expectedsalary=NULL, ";
                    } else {
                        $queryToUpdate .= " expectedsalary='" . $json['expectedsalary'] . "',";
                    }



                    // if(is_null($workExperience)){
                    //     $queryToUpdate .="workExperience=NULL, ";
                    // }else{
                    //     $queryToUpdate .="workExperience = '" . implode(',', $json['workexperience']) . "',";
                    // }

                    if (is_null($workExperience)) {
                        $queryToUpdate .= "workExperience=NULL, ";
                    } else {
                        $queryToUpdate .= "workExperience = '" . $json['workexperience'] . "',";
                    }


                    if (is_null($currentLocation)) {
                        $queryToUpdate .= "currentLocation=NULL, ";
                    } else {
                        $queryToUpdate .= " currentLocation='" . implode(',', $json['currentlocation']) . "',";
                    }

                    if (is_null($languages)) {
                        $queryToUpdate .= "languages=NULL, ";
                    } else {
                        $queryToUpdate .= "languages='" . implode(',', $json['Language']) . "',";
                    }

                    if (is_null($preferredworkLocation)) {
                        $queryToUpdate .= "preferredworkLocation=NULL, ";
                    } else {
                        $queryToUpdate .= " preferredworkLocation='" . $str . "',";
                    }

                    if (is_null($currentsalary)) {
                        $queryToUpdate .= "currentSalary=NULL, ";
                    } else {
                        $queryToUpdate .= " currentSalary='" . $json['currentsalary'] . "',";
                    }

                    if (is_null($noticePeriod)) {
                        $queryToUpdate .= "noticePeriod=NULL, ";
                    } else {
                        $queryToUpdate .= " noticePeriod='" . implode(',', $json['noticePeriod']) . "',";
                    }

                    // if(is_null($joiningPeriod)){
                    //     $queryToUpdate .="joiningPeriod=NULL, ";
                    // }else{
                    //     $queryToUpdate .=" joiningPeriod='" . implode(',', $json['joiningPeriod']) . "',";
                    // }

                    if (is_null($candidateSource)) {
                        $queryToUpdate .= "candidateSource=NULL, ";
                    } else {
                        $queryToUpdate .= " candidateSource='" . implode(',', $json['candidateSource']) . "',";
                    }

                    if (is_null($levelofInterview)) {
                        $queryToUpdate .= "levelOfInterview=NULL, ";
                    } else {
                        $queryToUpdate .= " levelOfInterview='" . implode(',', $json['levelofInterview']) . "',";
                    }

                    if (is_null($comment)) {
                        $queryToUpdate .= "comments=NULL, ";
                    } else {
                        $queryToUpdate .= " comments='" . $json['comment'] . "',";
                    }

                    if (is_null($preferredrole)) {
                        $queryToUpdate .= "preferredrole=NULL, ";
                    } else {
                        $queryToUpdate .= "preferredrole='" . $json['preferredrole'] . "',";
                    }

                    if (is_null($joinstatus)) {
                        $queryToUpdate .= "joinstatus=NULL, ";
                    } else {
                        $queryToUpdate .= "joinstatus='" . $json['joinstatus'] . "',";
                    }

                    if (is_null($skillValues)) {
                        $queryToUpdate .= "skillValues=NULL, ";
                    } else {
                        $queryToUpdate .= "skillValues='" . $json['skillValues'] . "',";
                    }
                    if (is_null($certiValues)) {
                        $queryToUpdate .= "certiValues=NULL, ";
                    } else {
                        $queryToUpdate .= "certiValues='" . $json['certiValues'] . "',";
                    }
                    if (is_null($avgTenure)) {
                        $queryToUpdate .= "avgTenure=NULL, ";
                    } else {
                        $queryToUpdate .= "avgTenure='" . $json['avgTenure'] . ",";
                    }

                    if (is_array($json['resume'])) {
                        $resumeString = implode(',', $json['resume']);
                        $queryToUpdate .= "resume='" . $resumeString . "'";
                    } else if (is_null($resume)) {
                        $queryToUpdate .= "resume=NULL ";
                    } else {
                        $queryToUpdate .= "resume='" . $json['resume'] . "'";
                    }

                    $queryToUpdate .= "WHERE emailId='" . $candidateEmailId . "' and company_id=" . $companyId . "";

                    $queryToUpdateData = mysqli_query($databaseConnection, $queryToUpdate);



                    if ($queryToUpdateData) {
                        sendEmailToUser($candidateEmailId, null, $dts1, $dts);
                        $to_encode = array(
                            'status' => 2,
                            'data' => 'Update Successfully'
                        );
                        whatsAppMsg($databaseConnection, $candidateMobile, $data, "scheduled");
                    } else {
                        $to_encode = array(
                            'status' => -1,
                            'data' => 'Error While Update'
                        );
                    }
                } else {
                    if (is_null($jobType)) {
                        $jobType = "NULL";
                    } else {
                        $jobType = implode(',', $json['jobType']);
                    }

                    if (is_null($recruiterId)) {
                        $recruiterId = "NULL";
                    } else {
                        $recruiterId = implode(',', $json['recruiter']);
                    }

                    if (is_null($joiningTimeline)) {
                        $joiningTimeline = "NULL";
                    } else {
                        $joiningTimeline = implode(',', $json['joiningTimeline']);
                    }

                    if (is_null($preferedJobType)) {
                        $preferedJobType = "NULL";
                    } else {
                        $preferedJobType = implode(',', $json['preferedJobType']);
                    }

                    if (is_null($currentProcess)) {
                        $currentProcess = "NULL";
                    } else {
                        $currentProcess = implode(',', $json['currentProcess']);
                    }

                    if (is_null($processType)) {
                        $processType = "NULL";
                    } else {
                        $processType = implode(',', $json['processType']);
                    }

                    if (is_null($currentCompany)) {
                        $currentCompany = "NULL";
                    } else {
                        $currentCompany = $json['currentCompany'];
                    }

                    if (is_null($clienttype)) {
                        $clienttype = "NULL";
                    } else {
                        $clienttype = implode(',', $json['clienttype']);
                    }

                    if (is_null($processPreference)) {
                        $processPreference = "NULL";
                    } else {
                        $processPreference = implode(',', $json['processPreference']);
                    }

                    if (is_null($shift)) {
                        $shift = "NULL";
                    } else {
                        $shift = implode(',', $json['shift']);
                    }

                    if (is_null($workLocation)) {
                        $workLocation = "NULL";
                    } else {
                        $workLocation = implode(',', $json['workLocation']);
                    }

                    if (is_null($convinientTime)) {
                        $convinientTime = "NULL";
                    } else {
                        $convinientTime = implode(',', $json['convinientTime']);
                    }

                    if (is_null($expectedsalary)) {
                        $expectedsalary = "NULL";
                    } else {
                        $expectedsalary = $json['expectedsalary'];
                    }

                    // if(is_null($workExperience)){
                    //     $workExperience="NULL";
                    // }else{
                    //     $workExperience=implode(',', $json['workexperience']);
                    // }
                    if (is_null($workExperience)) {
                        $workExperience = "NULL";
                    } else {
                        $workExperience = $json['workexperience'];
                    }

                    if (is_null($currentLocation)) {
                        $currentLocation = "NULL";
                    } else {
                        $currentLocation = implode(',', $json['currentlocation']);
                    }

                    if (is_null($languages)) {
                        $languages = "NULL";
                    } else {
                        $languages = implode(',', $json['Language']);
                    }

                    if (is_null($preferredworkLocation)) {
                        $preferredworkLocation = "NULL";
                    } else {
                        $preferredworkLocation = $str;
                    }

                    if (is_null($currentsalary)) {
                        $currentsalary = "NULL";
                    } else {
                        $currentsalary = $json['currentsalary'];
                    }

                    if (is_null($noticePeriod)) {
                        $noticePeriod = "NULL";
                    } else {
                        $noticePeriod = implode(',', $json['noticePeriod']);
                    }

                    // if(is_null($joiningPeriod)){
                    //     $joiningPeriod="NULL";
                    // }else{
                    //     $joiningPeriod=implode(',', $json['joiningPeriod']);
                    // }


                    if (is_null($candidateSource)) {
                        $candidateSource = "NULL";
                    } else {
                        $candidateSource = implode(',', $json['candidateSource']);
                    }


                    if (is_null($levelofInterview)) {
                        $levelofInterview = "NULL";
                    } else {
                        $levelofInterview = implode(',', $json['levelofInterview']);
                    }


                    if (is_null($comment)) {
                        $comment = "NULL";
                    } else {
                        $comment = $json['comment'];
                    }

                    if (is_null($preferredrole)) {
                        $preferredrole = "NULL";
                    } else {
                        $preferredrole = $json['preferredrole'];
                    }

                    if (is_null($joinstatus)) {
                        $joinstatus = "NULL";
                    } else {
                        $joinstatus = $json['joinstatus'];
                    }

                    if (is_null($skillValues)) {
                        $skillValues = "NULL";
                    } else {
                        $skillValues = $json['skillValues'];
                    }

                    if (is_null($certiValues)) {
                        $certiValues = "NULL";
                    } else {
                        $certiValues = $json['certiValues'];
                    }

                    if (is_null($avgTenure)) {
                        $avgTenure = "NULL";
                    } else {
                        $avgTenure = $json['avgTenure'];
                    }

                    if (is_null($resume)) {
                        $resume = "NULL ";
                    } else {
                        $resume = $json['resume'];
                    }
                    //Akash  
                    $q6 = "INSERT INTO `interviewSchedule`(`company_id`,`candidateName`,`emailId`,`mobileNumber`,`url`,`scheduleTime`,`firstScheduleDate`,`sectorId`,`jobType`,`currentCompany`, `currentProcess`, `processType`, `clientType`, `workExperience`, `currentSalary`, `expectedSalary`, `noticePeriod`, `processPreference`, `shift`, `workLocationPreference`, `timeToCall`, `preferedJobType`, `currentLocation`, `preferredWorkLocation`, `languages`,`joiningTimeline`,`recruiterId`,`preInterviewId`,`candidateSource`,`levelOfInterview`,`comments`,`preferredrole`,`joinstatus`,`skillValues`,`certiValues`,`avgTenure`,`resume`,`recruiterScheduleDate`) VALUES (" . $companyId . ",'" . $candidateName . "','" . $candidateEmailId . "'," . $candidateMobile . ",'" . $interviewLink . "','" . $schedule . "','" . $schedule . "',0," . ($jobType == "NULL" ? 'NULL' : ("'" . $jobType . "'")) . "," . ($currentCompany == "NULL" ? 'NULL' : ("'" . $currentCompany . "'")) . "," . ($currentProcess == "NULL" ? 'NULL' : ("'" . $currentProcess . "'")) . "," . ($processType == "NULL" ? 'NULL' : ("'" . $processType . "'")) . "," . ($clienttype == "NULL" ? 'NULL' : ("'" . $clienttype . "'")) . "," . ($workExperience == "NULL" ? 'NULL' : ("'" . $workExperience . "'")) . ",'" . $currentsalary . "','" . $expectedsalary . "'," . ($noticePeriod == "NULL" ? 'NULL' : ("'" . $noticePeriod . "'")) . "," . ($processPreference == "NULL" ? 'NULL' : ("'" . $processPreference . "'")) . "," . ($shift == "NULL" ? 'NULL' : ("'" . $shift . "'")) . "," . ($workLocation == "NULL" ? 'NULL' : ("'" . $workLocation . "'")) . "," . ($convinientTime == "NULL" ? 'NULL' : ("'" . $convinientTime . "'")) . "," . ($preferedJobType == "NULL" ? 'NULL' : ("'" . $preferedJobType . "'")) . "," . ($currentLocation == "NULL" ? 'NULL' : ("'" . $currentLocation . "'")) . ",'" . $preferredworkLocation . "'," . ($languages == "NULL" ? 'NULL' : ("'" . $languages . "'")) . "," . ($joiningTimeline == "NULL" ? 'NULL' : ("'" . $joiningTimeline . "'")) . "," . ($recruiterId == "NULL" ? 'NULL' : ("'" . $recruiterId . "'")) . ",'" . implode(',', $json['preInterviewId']) . "'," . ($candidateSource == "NULL" ? 'NULL' : ("'" . $candidateSource . "'")) . "," . ($levelofInterview == "NULL" ? 'NULL' : ("'" . $levelofInterview . "'")) . "," . ($comment == "NULL" ? 'NULL' : ("'" . $comment . "'")) . "," . ($preferredrole == "NULL" ? 'NULL' : ("'" . $preferredrole . "'")) . "," . ($joinstatus == "NULL" ? 'NULL' : ("'" . $joinstatus . "'")) . "," . ($skillValues == "NULL" ? 'NULL' : ("'" . $skillValues . "'")) . "," . ($certiValues == "NULL" ? 'NULL' : ("'" . $certiValues . "'")) . "," . ($avgTenure == "NULL" ? 'NULL' : ("'" . $avgTenure . "'")) . "," . ($resume == "NULL" ? 'NULL' : ("'" . $resume . "'")) . ",now())";

                    //    echo $q6;
                    // $queryToInsert = "INSERT INTO `interviewSchedule`(`company_id`,`candidateName`,`emailId`,`mobileNumber`,`url`,`scheduleTime`,`firstScheduleDate`,`sectorId`,`jobType`,`currentCompany`, `currentProcess`, `processType`, `clientType`, `workExperience`, `currentSalary`, `expectedSalary`, `noticePeriod`, `processPreference`, `shift`, `workLocationPreference`, `timeToCall`, `preferedJobType`, `currentLocation`, `preferredWorkLocation`, `languages`,`joiningTimeline`,`recruiterId`,`preInterviewId`,`candidateSource`,`levelOfInterview`,`comments`,`preferredrole`,`joinstatus`,`skillValues`,`certiValues`,`avgTenure`,`resume`,`recruiterScheduleDate`) VALUES (".$companyId.",'".$candidateName."','".$candidateEmailId."',".$candidateMobile.",'".$interviewLink."','".$schedule."','".$schedule."',0,".($jobType=="NULL"?'NULL':("'".$jobType."'")).",".($currentCompany=="NULL"?'NULL':("'".$currentCompany."'")).",".($currentProcess=="NULL"?'NULL':("'".$currentProcess."'")).",".($processType=="NULL"?'NULL':("'".$processType."'")).",".($clienttype=="NULL"?'NULL':("'".$clienttype."'"))."," .($workExperience=="NULL"?'NULL':("'".$workExperience."'")).",'".$currentsalary."','".$expectedsalary."',".($noticePeriod=="NULL"?'NULL':("'".$noticePeriod."'")).",".($processPreference=="NULL"?'NULL':("'".$processPreference."'")).",".($shift=="NULL"?'NULL':("'".$shift."'")).",".($workLocation=="NULL"?'NULL':("'".$workLocation."'")).",".($convinientTime=="NULL"?'NULL':("'".$convinientTime."'")).",".($preferedJobType=="NULL"?'NULL':("'".$preferedJobType."'")).",".($currentLocation=="NULL"?'NULL':("'".$currentLocation."'")).",'".$preferredworkLocation."',".($languages=="NULL"?'NULL':("'".$languages."'")).",".($joiningTimeline=="NULL"?'NULL':("'".$joiningTimeline."'")).",".($recruiterId=="NULL"?'NULL':("'".$recruiterId."'")).",'".implode(',',$json['preInterviewId'])."',".($candidateSource=="NULL"?'NULL':("'".$candidateSource."'")).",".($levelofInterview=="NULL"?'NULL':("'".$levelofInterview."'")).",".($comment=="NULL"?'NULL':("'".$comment."'")).",".($preferredrole=="NULL"?'NULL':("'".$preferredrole."'")).",".($joinstatus=="NULL"?'NULL':("'".$joinstatus."'")).",".($skillValues=="NULL"?'NULL':("'".$skillValues."'")).",".($certiValues=="NULL"?'NULL':("'".$certiValues."'")).",".($avgTenure=="NULL"?'NULL':("'".$avgTenure."'")).",".($resume=="NULL"?'NULL':("'".$resume."'")).",now())";


                    $queryToInsertData = mysqli_query($databaseConnection, $q6);
                    if ($queryToInsertData) {


                        sendEmailToUser($candidateEmailId, null, $dts1, $dts);
                        $to_encode = array(
                            'status' => 1,
                            'data' => 'Schedule Successfully'
                        );
                        whatsAppMsg($databaseConnection, $candidateMobile, $data, "scheduled");
                    } else {
                        $to_encode = array(
                            'status' => -1,
                            'data' => 'Error While Schedule' . mysqli_error($databaseConnection)
                        );
                    }
                }
            }
        }
    }
    echo json_encode($to_encode);
} else if (isset($_GET['deleteScheduleInterview'])) {
    // this method is added by arun on 31 Jan 2023 to delete the schedule interview
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if ($json) {

        if ($json['id'] != '') {

            $queryToUpdate = "DELETE FROM `interviewSchedule` WHERE id=" . $json['id'] . "";

            $queryToUpdateData = mysqli_query($databaseConnection, $queryToUpdate);
            if ($queryToUpdateData) {
                $to_encode = array(
                    'status' => 1,
                    'data' => 'Deleted Successfully'
                );
            } else {
                $to_encode = array(
                    'status' => -1,
                    'data' => 'Error While Update'
                );
            }
        }
    }
    echo json_encode($to_encode);
} else if (isset($_GET['getPreInterviewId'])) {
    // this method is added by arun on 8 Feb 2023 to fetch PreInterview Id
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if ($json) {

        $companyId = $json['companyId'];
        $sectorId = $json['sectorId'];
        $productId = $json['productId'];

        $queryToFetch = "SELECT min(id) as preId FROM `preInterview` WHERE company_id=" . $companyId . " AND productId=" . $productId . " AND sectorId=" . $sectorId . "";

        $queryToFetchData = mysqli_query($databaseConnection, $queryToFetch);
        if ($queryToFetchData) {
            $details = mysqli_fetch_all($queryToFetchData, MYSQLI_ASSOC);
            $to_encode = array(
                'status' => 1,
                'data' => $details
            );
        } else {
            $to_encode = array(
                'status' => -1,
                'data' => 'Error While Fetch'
            );
        }

    }
    echo json_encode($to_encode);
} else if (isset($_GET['getInterviewDetails'])) {
    // this method is added by arun on 8 Feb 2023 to fetch companyId,sectorId,productId
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if ($json) {

        $id = $json['preInterviewId'];

        $queryToFetch = "SELECT  id,company_id,sectorId,productId,vendorId, createdAt,interviewType,serviceType,practiceType FROM `preInterview` WHERE id=" . $id . "";

        $queryToFetchData = mysqli_query($databaseConnection, $queryToFetch);
        if ($queryToFetchData) {
            $details = mysqli_fetch_all($queryToFetchData, MYSQLI_ASSOC);
            $to_encode = array(
                'status' => 1,
                'data' => $details
            );
        } else {
            $to_encode = array(
                'status' => -1,
                'data' => 'Error While Fetch'
            );
        }

    }
    echo json_encode($to_encode);
} else if (isset($_GET['getPreInterviewDetails'])) {
    // this method is added by sourabh on 4 Dec 2023 to fetch preInterview details
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if ($json) {

        $id = $json['id'];

        $queryToFetch = "SELECT id,interviewType FROM `preInterview` WHERE id=" . $id . "";

        $queryToFetchData = mysqli_query($databaseConnection, $queryToFetch);
        if ($queryToFetchData) {
            $details = mysqli_fetch_all($queryToFetchData, MYSQLI_ASSOC);
            $to_encode = array(
                'status' => 1,
                'data' => $details
            );
        } else {
            $to_encode = array(
                'status' => -1,
                'data' => 'Error While Fetch'
            );
        }

    }
    echo json_encode($to_encode);
} else if (isset($_GET['getPreInterviewDetailsByInterviewId'])) {
    // sourabh - 9 Jan 2024 : to fetch preInterview id for given interview id
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if ($json) {

        $id = $json['id'];
        $preId = $json['preId'];
        $values = array();
        if ($id != null && $preId == null) {

            $queryToFetch = "SELECT i.preinterviewId,pr.* FROM interview i left join preInterview pr  on i.preInterviewId= pr.id WHERE i.id=" . $id . "";
            $queryToFetchData = mysqli_query($databaseConnection, $queryToFetch);
            $values['queryToFetchData'] = mysqli_fetch_all($queryToFetchData, MYSQLI_ASSOC);
            $filter9 = "select * from profilePreferences where preInterviewId = (select preInterviewId from interview where id=" . $id . ") ";
            $filter9Result = mysqli_query($databaseConnection, $filter9);
            $values['profilePrefFields'] = mysqli_fetch_all($filter9Result, MYSQLI_ASSOC);
            $filter1 = "SELECT id, cityName FROM locations WHERE ID NOT IN(512,518,513,516,514,515,517,519,525) ORDER BY 
        CASE 
        WHEN cityName LIKE '%Any%' THEN 0
        WHEN cityName LIKE '%Remote%' THEN 1
        ELSE 2
        END,
        cityName ASC";
            $filter1Result = mysqli_query($databaseConnection, $filter1);

            $values['locationList'] = mysqli_fetch_all($filter1Result, MYSQLI_ASSOC);
            if ($queryToFetchData) {
                // $details=mysqli_fetch_all($queryToFetchData,MYSQLI_ASSOC);
                $to_encode = array(
                    'status' => 1,
                    'data' => $values
                );
            } else {
                $to_encode = array(
                    'status' => -1,
                    'data' => 'Error While Fetch'
                );
            }
        } else if ($id == null && $preId != null) {
            $queryToFetch = "SELECT pr.id as preInterviewId,pr.* from  preInterview pr  WHERE pr.id=" . $preId . "";
            // echo   $queryToFetch ;
            $queryToFetchData = mysqli_query($databaseConnection, $queryToFetch);
            $values['queryToFetchData'] = mysqli_fetch_all($queryToFetchData, MYSQLI_ASSOC);
            $filter9 = "select * from profilePreferences where preInterviewId = " . $preId . " ";
            $filter9Result = mysqli_query($databaseConnection, $filter9);
            $values['profilePrefFields'] = mysqli_fetch_all($filter9Result, MYSQLI_ASSOC);
            $filter1 = "SELECT id, cityName FROM locations WHERE ID NOT IN(512,518,513,516,514,515,517,519,525) ORDER BY 
            CASE 
            WHEN cityName LIKE '%Any%' THEN 0
            WHEN cityName LIKE '%Remote%' THEN 1
            ELSE 2
            END,
            cityName ASC";
            $filter1Result = mysqli_query($databaseConnection, $filter1);

            $values['locationList'] = mysqli_fetch_all($filter1Result, MYSQLI_ASSOC);


            if ($queryToFetchData) {
                // $details=mysqli_fetch_all($queryToFetchData,MYSQLI_ASSOC);
                // $profilePrefFields =mysqli_fetch_all($filter9Result,MYSQLI_ASSOC);
                $to_encode = array(
                    'status' => 1,
                    'data' => $values
                );
            } else {
                $to_encode = array(
                    'status' => -1,
                    'data' => 'Error While Fetch'
                );
            }
        } else {
            $to_encode = array(
                'status' => -1,
                'data' => 'Invalid Input'
            );
        }

        // echo $queryToFetch



    }
    echo json_encode($to_encode);
} else if (isset($_GET['getScheduleInterviewData'])) {
    // this method is added by arun on 31 Jan 2023 to fetch the schedule interview data
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if ($json) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $filterQry = '';
        $filterQry2 = '';
        $condition = '';
        $condition2 = '';
        $havingQry = '';
        $values = array();
        $limit = $json['limit'];
        $start = ($json['page'] - 1) * $limit;
        $limit_query = $limit == 0 ? "" : " limit " . $start . "," . $limit;
        $preInterviewId = '';
        $emailId = '';
        $profileMatchResult = '';


        $preId = "SELECT MAX(preinterviewId) AS maxPreinterviewId FROM interviewSchedule WHERE candidate_id = $userId";
        $preInterviewIdResult = mysqli_query($databaseConnection, $preId);

        if ($preInterviewIdResult) {
            $row = mysqli_fetch_assoc($preInterviewIdResult);
            if ($row) {
                $preInterviewId = $row['maxPreinterviewId'];
            }
        }

        $eId = "SELECT MAX(EmailId) AS eId FROM interviewSchedule WHERE candidate_id = $userId ";
        $emailIdResult = mysqli_query($databaseConnection, $eId);

        if ($emailIdResult) {
            $row = mysqli_fetch_assoc($emailIdResult);
            if ($row) {
                $emailId = $row['eId'];
            }
        }

        //changed by shrikant : 11/1/2024
        $pSkill = "select jobMatch('$emailId', $preInterviewId) AS jobMatchResult";
        $result1 = mysqli_query($databaseConnection, $pSkill);

        if ($result1) {
            $row = mysqli_fetch_assoc($result1);
            if ($row) {
                $profileMatchResult = $row['jobMatchResult'];
                // echo $profileMatchResult;
            }
        }

        // echo $json['candidate_search'] ;


        if ($json['candidate_search'] != "") {
            //Akash 10/13/2023
            if (preg_match('/^[0-9]{10}+$/', $json['candidate_search'])) {
                $filterQry .= " and isc.mobileNumber=" . $json['candidate_search'] . "";
                $condition .= " and pr.id IN (SELECT preinterviewId FROM interviewSchedule WHERE mobileNumber='" . $json['candidate_search'] . "')";
            } else if (filter_var($json['candidate_search'], FILTER_VALIDATE_EMAIL)) {
                $filterQry .= " and isc.emailId='" . $json['candidate_search'] . "'";

                $condition .= " and pr.id IN (SELECT preinterviewId FROM interviewSchedule WHERE emailId like '%" . $json['candidate_search'] . "%')";
            } else {
                $filterQry .= " and isc.candidateName like '%" . $json['candidate_search'] . "%'";
                $condition .= " and pr.id IN (SELECT preinterviewId FROM interviewSchedule WHERE candidateName like '%" . $json['candidate_search'] . "%')";
            }

        }


        // if ($json['interviewStatusFrom'] != "" && $json['interviewStatusTo'] == "")
        // {
        //  $filterQry2 .= " and (date_format(interviewStatusDate,'%Y-%m-%d')) >= '" . $json['interviewStatusFrom'] . "'";

        // }

        // if ($json['interviewStatusFrom'] == "" && $json['interviewStatusTo'] != "")
        // { 
        //  $filterQry2 .= " and (date_format(interviewStatusDate,'%Y-%m-%d')) <= '" .$json['interviewStatusTo']. "'";
        // }

        // if ($json['interviewStatusFrom'] != "" && $json['interviewStatusTo'] != "")
        // {
        //  $filterQry2 .= " and (date_format(interviewStatusDate,'%Y-%m-%d')) >= '" . $json['interviewStatusFrom'] . "' and (date_format(interviewStatusDate,'%Y-%m-%d')) <= '" . $json['interviewStatusTo'] . "'";
        // }

        // This code is added by Vijay on May 8 2023

        if ($json['interviewScheduleFrom'] != "" && $json['interviewScheduleTo'] == "") {
            $filterQry .= " and (date_format(isc.scheduleTime,'%Y-%m-%d')) >= '" . $json['interviewScheduleFrom'] . "'";

        }

        if ($json['interviewScheduleFrom'] == "" && $json['interviewScheduleTo'] != "") {
            $filterQry .= " and (date_format(isc.scheduleTime,'%Y-%m-%d')) <= '" . $json['interviewScheduleTo'] . "'";
        }

        if ($json['interviewScheduleFrom'] != "" && $json['interviewScheduleTo'] != "") {
            $filterQry .= " and (date_format(isc.scheduleTime,'%Y-%m-%d')) >= '" . $json['interviewScheduleFrom'] . "' and (date_format(isc.scheduleTime,'%Y-%m-%d')) <= '" . $json['interviewScheduleTo'] . "'";
        }

        //redirection


        if ($json['preId'] != '') {

            $condition .= " and pr.id=" . $json['preId'] . "";
        }


        if ($json['recruiterId'] != '') {

            $condition2 .= " and isc.recruiterId=" . $json['recruiterId'] . "";
        }


        if ($json['field'] != '' && $json['field'] == 'scheduledToday') {

            // $condition2 .=" and date_format(isc.recruiterScheduleDate,'%Y-%c-%d')=CURDATE()";

            $havingQry .= " and interviewStatus in ('Future Scheduled','Scheduled Today')";
        }

        if ($json['field'] != '' && $json['field'] == 'totalMissed') {

            $havingQry .= " and interviewStatus in ('Missed Schedule')";
        }

        if ($json['field'] != '' && $json['field'] == 'missedToday') {

            $condition2 .= " and date_format(isc.scheduleTime,'%Y-%c-%d')=CURDATE()";

            $havingQry .= " and interviewStatus in ('Missed Schedule')";
        }

        if ($json['field'] != '' && $json['field'] == 'Rejected') {

            $havingQry .= " and interviewStatus in ('Incomplete','Technical Issue','Rejected')";
        }

        if ($json['field'] != '' && $json['field'] == 'assessmentPending') {

            $havingQry .= " and interviewStatus in ('Assessment in Progress','Internal Review')";
        }

        if ($json['field'] != '' && $json['field'] == 'Assessed') {

            $havingQry .= " and interviewStatus in ('Completed')";
        }

        if ($json['field'] != '' && $json['field'] == 'unAttended') {

            $condition2 .= " and (fr.id is not null and fr.review_status=2) and (isc.candidateStatus in('RNR') or isc.candidateStatus is null) ";

        }
        if ($json['field'] != '' && $json['field'] == 'dropOut') {
            //shrikant changed : 6/3/2024 Client Screen Reject
            $condition2 .= " and (fr.id is not null and fr.review_status=2) and (isc.candidateStatus in('Client Screen Reject','Not interested','Internal Reject'))";
        }
        if ($json['field'] != '' && $json['field'] == 'shared') {

            $condition2 .= " and (fr.id is not null and fr.review_status=2) and (isc.candidateStatus in('Profile Shared'))";

        }
        if ($json['field'] != '' && $json['field'] == 'clientShortlisted') {

            $condition2 .= " and (fr.id is not null and fr.review_status=2) and (isc.candidateStatus in('Client Shortlisted'))";

        }
        if ($json['field'] != '' && $json['field'] == 'Offered') {

            $condition2 .= " and (fr.id is not null and fr.review_status=2) and (isc.candidateStatus in('Offered'))";

        }
        if ($json['field'] != '' && $json['field'] == 'Joined') {

            $condition2 .= " and (fr.id is not null and fr.review_status=2) and (isc.candidateStatus in('Joined'))";

        }

        if ($json['interviewStatus'] != '') {
            if (in_array("Future Scheduled", $json['interviewStatus'])) {
                $havingQry .= " and interviewStatus in ('" . implode("','", $json['interviewStatus']) . "','Scheduled Today')";
            } else {

                $havingQry .= " and interviewStatus in ('" . implode("','", $json['interviewStatus']) . "')";
            }
        }

        if ($json['candidateStatus'] != '') {

            $condition2 .= " and isc.candidateStatus in ('" . implode("','", $json['candidateStatus']) . "')";
        }

        if ($userType == 'corporate') {
            // $filterQry .=" inner join preInterview pr on pr.company_id=isc.company_id ";
            // $condition .=" and pr.userId=".$userId."";
            $condition .= " and pr.id IN (SELECT preinterviewId FROM preInterview_corporate WHERE userId=" . $userId . ")";

            $filterQry .= " and isc.recruiterId IN (select id from recruiterList where corporateId=" . $userId . ")";
        }
        $companyId = "select distinct(pr.id) as preInterviewId,pr.company_id,CASE When pr.interviewName is null then ac.name else pr.interviewName End as interviewName,pr.hiringCompanies,pr.salaryRage,pr.jobLocation,pr.jdDocument from preInterview pr inner join aspiration_company ac on ac.id=pr.company_id inner join interviewSchedule isc on isc.preInterviewId=pr.id where 1 and pr.jobCategory='interview' " . $condition . " order by pr.id desc";

        //  echo $companyId;
        //  exit();

        // $query1=mysqli_query($databaseConnection,$companyId .$limit_query);

        $query1 = mysqli_query($databaseConnection, $companyId . $limit_query);

        if (mysqli_num_rows($query1) > 0) {
            $count_query = mysqli_query($databaseConnection, $companyId);
            $no_of_rows = mysqli_num_rows($count_query);


            while ($row = mysqli_fetch_assoc($query1)) {

                // $query = " select isc.*,rl.name as recruiterName,concat(rl.name,'(',u.firstName,')') as recruiter from interviewSchedule isc  inner join preInterview pr on pr.id=isc.preInterviewId left join recruiterList rl on rl.id=isc.recruiterId left join users u on u.id=rl.corporateId where 1 and isc.emailId is not null ".$condition . $filterQry." and isc.preInterviewId=".$row['preInterviewId']." order by isc.scheduleTime desc";

                // this query is taking more time to execute

                // $query="select * from (select null as aptitudeScore,null as interviewSessionId,null as interviewId,null as candidateId,isc.id,isc.company_id,isc.recruiterId,isc.preInterviewId,isc.candidateName,isc.emailId,isc.mobileNumber,isc.url,isc.scheduleTime,rl.name as recruiterName,concat(rl.name,'(',u.firstName,')') as recruiter,case when isc.scheduleTime>=now() then 'Future Schedule' when isc.scheduleTime<now() then 'Missed Schedule'  end as interviewStatus from interviewSchedule isc inner join preInterview pr on pr.id=isc.preInterviewId left join recruiterList rl on rl.id=isc.recruiterId left join users u on u.id=rl.corporateId where 1 and isc.emailId is not null and isc.emailId not in (select u.emailId from users u inner join interview i on i.createdBy=u.id inner join feedback_request fr on fr.interviewId=i.id inner join preInterview pr on pr.id=i.preInterviewId where i.preInterviewId=".$row['preInterviewId'].") ".$condition . $filterQry." and isc.preInterviewId=".$row['preInterviewId']." 

                // union

                // select fbr.aptitudeScore,fr.interviewSessionId,fr.interviewId,fr.candidateId,isc.id,isc.company_id,isc.recruiterId,isc.preInterviewId,isc.candidateName,isc.emailId,isc.mobileNumber,isc.url,isc.scheduleTime,(select rl.name from recruiterList rl left join users u on u.id=rl.corporateId where rl.id=isc.recruiterId) as recruiterName,(select concat(rl.name,'(',u.firstName,')') from recruiterList rl left join users u on u.id=rl.corporateId where rl.id=isc.recruiterId) as recruiter,case when cit.completion_status is null then 'Incomplete' when cit.completion_status is not null and fr.review_status=-2 then 'Attempted' when cit.completion_status is not null and fr.review_status=1 then 'In Progress' when cit.completion_status is not null and fr.review_status=-4 then 'Rejected'  when cit.completion_status is not null and fr.review_status=2 then 'Completed' when cit.completion_status is not null and fr.review_status=0 then 'Open Assessment' end as interviewStatus from interviewSchedule isc inner join preInterview pr on pr.id=isc.preInterviewId inner join users u on u.emailId=isc.emailId inner join interview i on i.preInterviewId=pr.id and i.createdBy=u.id inner join feedback_request fr on fr.interviewId=i.id left join candidate_interview_transection cit on cit.interviewId=i.id left join feedback_report fbr on fbr.feedbackRequestId=fr.id where 1 and isc.emailId is not null ".$condition . $filterQry." and isc.preInterviewId=".$row['preInterviewId'].") as t order by t.scheduleTime desc";

                // $query="select *,case when t.candidateStatus is null and t.interviewStatus in ('Missed Schedule','Scheduled Today','Future Scheduled','Re-Scheduled') then t.interviewStatus when t.candidateStatus is null and t.interviewStatus in ('duplicateAttempt','limitedFreeAssessment','unauthorizedUser','Incomplete','Technical Issue','Rejected') then 'Assessment Rejected' when t.candidateStatus is null and t.interviewStatus in ('Assessment in Progress','Internal Review') then 'Assessment Awaited' when t.candidateStatus is null and t.interviewStatus in ('Best Fit','Possible Fit','Not Fit') then 'Assessment Completed'when t.candidateStatus is null and t.interviewStatus in ('nullscore') then 'Applied' else t.candidateStatus end as newcandidStatus from (select fbr.aptitudeScore,fr.interviewSessionId,fr.candidateId,fr.id as feedbackRequestId,fr.review_status,fr.interviewId as interId,isc.*,(select rl.name from recruiterList rl left join users u on u.id=rl.corporateId where rl.id=isc.recruiterId) as recruiterName,(select concat(rl.name,'(',u.firstName,')') from recruiterList rl left join users u on u.id=rl.corporateId where rl.id=isc.recruiterId) as recruiter,case when (fr.id is not null and (fr.review_status=-4 and fr.reasonOfRejection='incompleteInterview')) then 'Incomplete' 
                // when (fr.id is not null and (fr.review_status=-4 and fr.reasonOfRejection='technicalIssue')) then 'Technical Issue' 
                // when (fr.id is not null and (fr.review_status=-4 and fr.reasonOfRejection not in ('technicalIssue','incompleteInterview'))) then 'Rejected' 
                // when (fr.id is not null and cit.completion_status is not null and fr.review_status in (0,1)) then 'Assessment in Progress' 
                // when (fr.id is not null and cit.completion_status is not null and fr.review_status=-2) then 'Internal Review'  
                // when (fr.id is null and (isc.scheduleTime!=isc.firstScheduleDate) and (DATEDIFF(isc.scheduleTime,now()))>=1) then 'Re-Scheduled' 
                // when (fr.id is null and isc.scheduleTime<now()) then 'Missed Schedule' 
                // when (fr.id is null and (DATEDIFF(isc.scheduleTime,now()))=0) then 'Scheduled Today' 
                // when (fr.id is null and isc.firstScheduleDate is null and (DATEDIFF(isc.scheduleTime,now()))>=1) then 'Future Scheduled' 
                // when (fr.id is null and (isc.scheduleTime=isc.firstScheduleDate) and (DATEDIFF(isc.scheduleTime,now()))>=1) then 'Future Scheduled' when (fr.id is not null and (fr.review_status=-4 and fr.reasonOfRejection='duplicateAttempt')) then 'duplicateAttempt' when (fr.id is not null and (fr.review_status=-4 and fr.reasonOfRejection='limitedFreeAssessment')) then 'limitedFreeAssessment' when (fr.id is not null and (fr.review_status=-4 and fr.reasonOfRejection='unauthorizedUser')) then 'unauthorizedUser' when (fr.id is not null and (fbr.aptitudeScore<=4)) then 'Not Fit' when (fr.id is not null and (fbr.aptitudeScore>4 and fbr.aptitudeScore <7)) then 'Possible Fit' when (fr.id is not null and (fbr.aptitudeScore>=7)) then 'Best Fit' when fbr.aptitudeScore is null then 'nullscore' end as interviewStatus,
                // case when fr.id is not null then fr.updatedAt else isc.scheduleTime end as 'interviewStatusDate',
                // pr.postedBy 
                // from interviewSchedule isc inner join preInterview pr on pr.id=isc.preInterviewId left join users u on u.emailId=isc.emailId left join interview i on i.preInterviewId=pr.id and i.createdBy=u.id left join feedback_request fr on fr.interviewId=i.id and fr.candidateId=u.id left join candidate_interview_transection cit on cit.interviewId=i.id left join feedback_report fbr on fbr.feedbackRequestId=fr.id where 1 and isc.emailId is not null ".$condition . $condition2 . $filterQry ." and isc.preInterviewId=".$row['preInterviewId']." group by isc.emailId,fr.id desc) as t where 1 ".$filterQry2." group by t.emailId,t.interviewId having 1".$havingQry." order by t.scheduleTime desc ";

                $query = "select *,case  when t.candidateStatus is null and t.interviewStatus in ('Assessment Completed') then 'Assessment Completed' when t.interviewStatus in ('Assessment in Progress', 'Internal Review') then 'Assessment Awaited' when t.candidateStatus is null and t.interviewStatus in ('duplicateAttempt', 'limitedFreeAssessment', 'unauthorizedUser', 'Incomplete', 'Technical Issue', 'Rejected') then 'Assessment Rejected' when t.candidateStatus is null and t.interviewStatus in ('Missed Schedule', 'Scheduled Today', 'Future Scheduled', 'Re-Scheduled') then 'Scheduled' when t.candidateStatus is null and t.scheduleTime is null then 'Applied' when t.interviewStatus in ('Not Attempted') then 'Not Attempted' else t.candidateStatus end as newcandidStatus from (select fbr.aptitudeScore,fr.interviewSessionId,fr.candidateId,fr.id as feedbackRequestId,fr.review_status,fr.interviewId as interId,isc.*,(select rl.name from recruiterList rl left join users u on u.id=rl.corporateId where rl.id=isc.recruiterId) as recruiterName,(select concat(rl.name,'(',u.firstName,')') from recruiterList rl left join users u on u.id=rl.corporateId where rl.id=isc.recruiterId) as recruiter,
                case when (fr.id is not null and (fr.review_status=2)) then 'Assessment Completed'
                when (fr.id is not null and cit.completion_status is not null and fr.review_status in (0,1)) then 'Assessment in Progress' 
                when (fr.id is not null and cit.completion_status is not null and fr.review_status=-2) then 'Internal Review'  
                when (fr.id is not null and (fr.review_status=-4 and fr.reasonOfRejection='incompleteInterview')) then 'Incomplete' 
                when (fr.id is not null and (fr.review_status=-4 and fr.reasonOfRejection='technicalIssue')) then 'Technical Issue' 
                when (fr.id is not null and (fr.review_status=-4 and fr.reasonOfRejection not in ('technicalIssue','incompleteInterview'))) then 'Rejected'
                when (fr.id is not null and (fr.review_status=-4 and fr.reasonOfRejection='duplicateAttempt')) then 'duplicateAttempt'
                when (fr.id is not null and (fr.review_status=-4 and fr.reasonOfRejection='limitedFreeAssessment')) then 'limitedFreeAssessment' 
                when (fr.id is not null and (fr.review_status=-4 and fr.reasonOfRejection='unauthorizedUser')) then 'unauthorizedUser'
                when (fr.id is null and (isc.scheduleTime!=isc.firstScheduleDate) and (DATEDIFF(isc.scheduleTime,now()))>=1) then 'Re-Scheduled' 
                when (fr.id is null and isc.scheduleTime<now()) then 'Missed Schedule' 
                when (fr.id is null and (DATEDIFF(isc.scheduleTime,now()))=0) then 'Scheduled Today' 
                when (fr.id is null and isc.firstScheduleDate is null and (DATEDIFF(isc.scheduleTime,now()))>=1) then 'Future Scheduled' 
                when (fr.id is null and (isc.scheduleTime=isc.firstScheduleDate) and (DATEDIFF(isc.scheduleTime,now()))>=1) then 'Future Scheduled'
                when (fr.id is null and fr.review_status is null) then 'Not Attempted'
                end as interviewStatus,
                case when fr.id is not null then fr.updatedAt else isc.scheduleTime end as 'interviewStatusDate',
                pr.postedBy 
                from interviewSchedule isc inner join preInterview pr on pr.id=isc.preInterviewId left join users u on u.emailId=isc.emailId left join interview i on i.id = isc.interviewId left join feedback_request fr on fr.interviewId=i.id left join candidate_interview_transection cit on cit.interviewId=i.id left join feedback_report fbr on fbr.feedbackRequestId=fr.id where 1 and isc.emailId is not null " . $condition . $condition2 . $filterQry . " and isc.preInterviewId=" . $row['preInterviewId'] . " group by isc.emailId,fr.id desc) as t where 1 " . $filterQry2 . " order by t.scheduleTime desc ";

                // echo $query;
                // exit();

                $queryData = mysqli_query($databaseConnection, $query);
                // $result=mysqli_fetch_all($queryData,MYSQLI_ASSOC);
                // $row['candidates']=$result;
                $candidates = array();
                if (mysqli_num_rows($queryData) > 0) {

                    while ($row1 = mysqli_fetch_assoc($queryData)) {
                        if ($row1['feedbackRequestId'] != null) {
                            $mcount = mysqli_query($databaseConnection, "select count(er.feedback_request_id) as malpractcount from expert_review er inner join expert_review_observation_details erod on erod.expertReviewId=er.id inner join observation_values ov on ov.id=erod.observationValueId where erod.observationValueId in (308,442,443) and er.feedback_request_id = " . $row1['feedbackRequestId'] . " group by er.candidateId");
                            if (mysqli_num_rows($mcount) >= 1) {
                                $row1['malpracticeCount'] = mysqli_fetch_assoc($mcount)['malpractcount'];
                            } else {
                                $row1['malpracticeCount'] = null;
                            }
                            if ($row1['interviewId'] != null) {
                                $rcq = "SELECT
                             COUNT(DISTINCT CASE WHEN sectionName IN ('BehavioralStart', 'BehavioralEnd') THEN sectionName END) AS distinctSectionCount,
                             SUM(CASE WHEN sectionName IN ('BehavioralStart', 'BehavioralEnd') AND followUp = 'Parent' AND (attemptStatus = 'Respond' or attemptStatus='Skip') THEN 1 ELSE 0 END) AS respondCount
                                 FROM interview_questions_transection iqt
                                 INNER JOIN questions q ON q.id = iqt.questionId
                                 WHERE interviewId = " . $row1['interviewId'] . "";


                                $rc = mysqli_query($databaseConnection, $rcq);
                                if ($r = mysqli_fetch_assoc($rc)) {
                                    $row1['respondCount'] = ($r['respondCount'] / 8) * 100;
                                } else {
                                    $row1['respondCount'] = 0;
                                }
                            } else {
                                $row1['respondCount'] = 0;
                            }
                        } else {
                            $row1['malpracticeCount'] = null;
                        }



                        array_push($candidates, $row1);

                    }
                }

                $row['candidates'] = $candidates;
                array_push($values, $row);
                $total_data['data'] = $values;
                $total_data['status'] = 1;
                $total_data['count'] = $no_of_rows;
                $total_data['profileMatch'] = $profileMatchResult;
                $to_encode = $total_data;
            }
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "in Error while retrieving Student information."
            );
        }

    }
    echo json_encode($to_encode);
} else if (isset($_GET['getWorkReportData'])) {
    // this method is added by arun on 23 Mar 2023 to fetch the work Report data
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if ($json) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $filterQry = '';
        $condition = '';
        $condition2 = '';
        $values = array();
        $limit = $json['limit'];
        $start = ($json['page'] - 1) * $limit;
        $limit_query = $limit == 0 ? "" : " limit " . $start . "," . $limit;


        if ($json['interview'] != '') {

            $condition .= " and pr.id in ('" . implode("','", $json['interview']) . "')";

        }

        if ($json['postedOn'] != '') {

            $condition .= " and (date_format(pr.interviewStartDate,'%Y-%m-%d'))='" . $json['postedOn'] . "'";

        }

        if ($json['recruiter'] != '') {

            $condition .= " and isc.recruiterId in (" . implode(',', $json['recruiter']) . ")";

        }

        if ($json['scheduleFrom'] != "" && $json['scheduleTo'] == "") {
            $condition .= " and (date_format(isc.recruiterScheduleDate,'%Y-%m-%d')) >= '" . $json['scheduleFrom'] . "'";

        }

        if ($json['scheduleFrom'] == "" && $json['scheduleTo'] != "") {
            $condition .= " and (date_format(isc.recruiterScheduleDate,'%Y-%m-%d')) <= '" . $json['scheduleTo'] . "'";
        }

        if ($json['scheduleFrom'] != "" && $json['scheduleTo'] != "") {
            $condition .= " and (date_format(isc.recruiterScheduleDate,'%Y-%m-%d')) >= '" . $json['scheduleFrom'] . "' and (date_format(isc.recruiterScheduleDate,'%Y-%m-%d')) <= '" . $json['scheduleTo'] . "'";
        }


        if ($userType == 'corporate') {

            // $condition .=" and pr.userId=".$userId."";
            $condition .= " and pr.id IN (SELECT preinterviewId FROM preInterview_corporate WHERE userId=" . $userId . ") ";
            $condition2 .= " and isc.recruiterId IN (select id from recruiterList where corporateId=" . $userId . ") ";
        }


        // $query="select fr.candidateId as candidateId,(select rl.name from recruiterList rl left join users u on u.id=rl.corporateId where rl.id=isc.recruiterId) as recruiterName,isc.recruiterId,pr.id as preInterviewId,pr.interviewName,date_format(pr.interviewStartDate,'%Y-%c-%d') as 'postedOn',group_concat(isc.amplifier) as amplifier,count(distinct(isc.emailId)) as 'totalSchedule',count(distinct(case when (fr.id is not null and (fr.review_status=-4 and fr.reasonOfRejection in ('technicalIssue','incompleteInterview'))) then isc.emailId end )) as 'Rejected',count(distinct(case when (fr.id is not null and fr.review_status=2 ) then isc.emailId end )) as 'Assessed',count(distinct(case when (fr.id is not null and (fr.review_status in (-2,1,0))) then isc.emailId end )) as 'assessmentPending',count(distinct(case when (fr.id is not null and (isc.candidateStatus in('Profile Shared'))) then isc.emailId end )) as 'shared',count(distinct(case when (fr.id is not null and (isc.candidateStatus in('Joined'))) then isc.emailId end )) as 'Joined',count(distinct(case when (fr.id is not null and (isc.candidateStatus in('Offered'))) then isc.emailId end )) as 'Offered',count(distinct(case when (fr.id is not null and (isc.candidateStatus in('Client Shortlisted'))) then isc.emailId end )) as 'clientShortlisted',count(distinct(case when (fr.id is not null and (isc.candidateStatus in('Client Rejected','Not interested','Internal Reject'))) then isc.emailId end )) as 'dropOut',count(distinct(case when (fr.id is not null and (isc.candidateStatus in('RNR') or isc.candidateStatus is null)) then isc.emailId end )) as 'unAttended',count(distinct(case when (fr.id is null and (isc.scheduleTime<now())) then isc.emailId end )) as'totalMissed',count(distinct(case when (fr.id is null and (date_format(scheduleTime,'%Y-%c-%d')=CURDATE() and (isc.scheduleTime<now()))) then isc.emailId end )) as'missedToday',count(distinct(case when (fr.id is null and (DATEDIFF(isc.scheduleTime,now()))=0) then isc.emailId end )) as'scheduledToday',pr.postedBy from interviewSchedule isc inner join preInterview pr on pr.id=isc.preInterviewId left join users u on u.emailId=isc.emailId left join interview i on i.preInterviewId=pr.id and i.createdBy=u.id left join feedback_request fr on fr.interviewId=i.id and fr.candidateId=u.id left join candidate_interview_transection cit on cit.interviewId=i.id left join feedback_report fbr on fbr.feedbackRequestId=fr.id where 1 and isc.emailId is not null and isc.preInterviewId is not null and isc.recruiterId is not null ".$condition . $filterQry." group by isc.preInterviewId,isc.recruiterId order by pr.id desc";

        $companyId = mysqli_query($databaseConnection, "select distinct(pr.id) as preInterviewId,pr.company_id,CASE When pr.interviewName is null then ac.name else pr.interviewName End as interviewName,pr.hiringCompanies,pr.salaryRage,pr.jobLocation,pr.jdDocument from preInterview pr inner join aspiration_company ac on ac.id=pr.company_id inner join interviewSchedule isc on isc.preInterviewId=pr.id where isc.recruiterId is not null and isc.emailId is not null and pr.interviewStatus='Active' " . $condition . " order by pr.id desc");



        while ($row = mysqli_fetch_assoc($companyId)) {


            //shrikant changed : 6/3/2024 Client Screen Reject
            // $query="
            // select t3.*,round(((t3.Assessed+t3.assessmentPending+t3.Rejected)*100)/(t3.totalSchedule-t3.scheduledToday),2) as interviewTakers,
            // round((t3.Assessed*100)/(t3.totalSchedule-t3.scheduledToday),2) as assessmentcompletion,round(((t3.clientShortlisted+t3.shared+t3.forshared+t3.Joined)*100)/(t3.totalSchedule-t3.scheduledToday),2) as resumesharedpercent,round(((t3.offered)*100)/(t3.clientShortlisted+t3.shared+t3.forshared+t3.Joined),2) as Offerconversion,round(((t3.joined)*100)/(t3.offered),2) as joiningconversion,round(((t3.totalMissed)*100)/(t3.totalSchedule-t3.scheduledToday),1) as missedconversion,round(((t3.Rejected)*100)/(t3.totalSchedule-t3.scheduledToday),1) as rejectedconversion,round(((t3.assessmentPending)*100)/(t3.totalSchedule-t3.scheduledToday-t3.totalMissed),1) as assessmentconversion from (select (select group_concat(distinct(amplifier)) from interviewSchedule where preInterviewId=t2.preInterviewId and recruiterId=t2.recruiterId) as amplifier,t2.preInterviewId,t2.recruiterId,t2.headcount,t2.targetResumeShared,t2.interviewName,t2.postedOn,t2.JobExpiryDate,count(distinct t2.emailId)as totalSchedule,t2.postedBy,t2.recruiterName,
            // count(distinct case when t2.futureScheduled is not null then t2.emailId end) as scheduledToday,
            // count(distinct case when t2.totalMissed is not null then t2.emailId end) as totalMissed,
            // count(distinct case when t2.todayMissed is not null then t2.emailId end) as missedToday,
            // count(distinct case when t2.interviewStatus in('Incomplete') then t2.emailId end ) as Rejected,
            // count(distinct case when t2.interviewStatus in('Assessment in Progress') then t2.emailId end) as assessmentPending,
            // count(distinct case when t2.interviewStatus in('Completed') then t2.emailId end) as Assessed,
            // count(distinct case when t2.shared is not null then t2.emailId end) as shared,
            // count(distinct case when t2.Joined is not null then t2.emailId end) as Joined,
            // count(distinct case when t2.Offered is not null then t2.emailId end) as Offered,
            // count(distinct case when t2.clientShortlisted is not null then t2.emailId end) as clientShortlisted,
            // count(distinct case when t2.dropOut is not null then t2.emailId end) as dropOut,
            // count(distinct case when t2.clientreject is not null then t2.emailId end) as clientreject,
            // count(distinct case when t2.unAttended is not null then t2.emailId end) as unAttended,
            // count(distinct case when t2.forshared is not null then t2.emailId end) as forshared,
            // count(distinct case when t2.MisseddeadLead is not null then t2.emailId end) as MisseddeadLead,
            // count(distinct case when t2.IncompletedeadLead is not null then t2.emailId end) as IncompletedeadLead,
            // count(distinct case when t2.recruiterreject is not null then t2.emailId end) as recruiterreject
            //  from (
            //     select t.* from (
            //     select fr.candidateId,fr.id as feedbackRequestId,isc.emailId,isc.scheduleTime,pr.id as preInterviewId,isc.recruiterId,(select rl.name from recruiterList rl left join users u on u.id=rl.corporateId where rl.id=isc.recruiterId) as recruiterName,(select concat(rl.name,'(',u.firstName,')') from recruiterList rl left join users u on u.id=rl.corporateId where rl.id=isc.recruiterId) as recruiter,
            //     case when pr.interviewName is null then (select name from aspiration_company where id=pr.company_id) else pr.interviewName end as interviewName,date_format(pr.interviewStartDate,'%Y-%c-%d') as 'postedOn', date_format(pr.interviewExpireDate,'%Y-%c-%d') as 'JobExpiryDate',
            //     case when (fr.id is not null and (fr.review_status=-4)) then 'Incomplete'  
            //     when (fr.id is not null and cit.completion_status is not null and fr.review_status in (0,1,-2)) then 'Assessment in Progress' 
            //     when (fr.id is not null and cit.completion_status is not null and fr.review_status=2) then 'Completed' 
            //     end as interviewStatus,
            //     case when (fr.id is not null and cit.completion_status is not null and fr.review_status=2) then fr.id end as 'Completed',
            //     case when (fr.id is null and (date_format(isc.recruiterScheduleDate,'%Y-%c-%d')=CURDATE())) then isc.emailId end as todaySchedule,   
            //     case when (fr.id is null and isc.scheduleTime>=now()) then isc.emailId end as futureScheduled,       
            //     case when ((fr.id is not null) and (isc.candidateStatus in('Profile Shared'))) then isc.emailId end  as 'shared',
            //     case when ((fr.id is not null) and (isc.candidateStatus in('Joined'))) then isc.emailId end as 'Joined',
            //     case when ((fr.id is not null) and (isc.candidateStatus in('Offered','Offer Dropped','Offer Accepted'))) then isc.emailId end as 'Offered',
            //     case when ((fr.id is not null) and (isc.candidateStatus in('Client Shortlisted'))) then isc.emailId end as 'clientShortlisted', 
            //     case when ((fr.id is not null) and (isc.candidateStatus in('Client Rejected','No Show','Offer Dropped','RNR','Recruiter Reject'))) then isc.emailId end  as 'dropOut',
            //     case when ((fr.id is not null) and (isc.candidateStatus in('Client Rejected'))) then isc.emailId end  as 'clientreject',
            //     case when ((fr.id is not null) and (isc.candidateStatus in('Recruiter Reject'))) then isc.emailId end  as 'recruiterreject',
            //     case when ((fr.id is not null and fr.review_status=2) and (isc.candidateStatus in('Client Rejected','No Show','Offer Dropped','Offer Accepted'))) then isc.emailId end  as 'forshared',
            //     case when ((fr.id is not null and fr.review_status=2) and (isc.candidateStatus in('UnAttended','Not Attended') or isc.candidateStatus is null)) then isc.emailId end  as 'unAttended',
            //     case when (fr.id is null and isc.scheduleTime<now()) then isc.emailId end as totalMissed,           
            //     case when (fr.id is null and (date_format(isc.scheduleTime,'%Y-%c-%d')=CURDATE() and (isc.scheduleTime<now()))) then isc.emailId end as todayMissed,  
            //     case when (isc.candidateStatus is not null and isc.candidateStatusDate is not null and TIMESTAMPDIFF(DAY,isc.candidateStatusDate,now())>5 and fr.id is null and isc.scheduleTime<now()) then isc.emailId when (isc.candidateStatus is null and isc.candidateStatusDate is null and TIMESTAMPDIFF(DAY,isc.scheduleTime,now())>5 and fr.id is null and isc.scheduleTime<now()) then isc.emailId end as MisseddeadLead,                  
            //     case when (isc.candidateStatus is not null and isc.candidateStatusDate is not null and TIMESTAMPDIFF(DAY,isc.candidateStatusDate,now())>5 and fr.id is not null and (fr.review_status=-4)) then isc.emailId when (isc.candidateStatus is null and isc.candidateStatusDate is null and TIMESTAMPDIFF(DAY,fr.updatedAt,now())>5 and fr.id is not null and (fr.review_status=-4)) then isc.emailId end as IncompletedeadLead,                  
            //     pr.postedBy,pr.headcount,pr.targetResumeShared from interviewSchedule isc inner join preInterview pr on pr.id=isc.preInterviewId left join users u on u.emailId=isc.emailId left join interview i on i.preInterviewId=pr.id and i.createdBy=u.id left join feedback_request fr on fr.interviewId=i.id and fr.candidateId=u.id left join candidate_interview_transection cit on cit.interviewId=i.id where 1 and isc.emailId is not null and isc.recruiterId is not null  and isc.preInterviewId=".$row['preInterviewId']." ".$condition. $condition2." group by isc.emailId,fr.id desc order by isc.emailId,fr.review_status desc
            //     ) as t group by t.emailId) as t2 group by t2.preInterviewId desc,t2.recruiterId with rollup) as t3 group by t3.preInterviewId desc,t3.recruiterId  ";

            $query = "
                select t3.*,round(((t3.Assessed+t3.assessmentPending+t3.Rejected)*100)/(t3.totalSchedule-t3.scheduledToday),2) as interviewTakers,
                round((t3.Assessed*100)/(t3.totalSchedule-t3.scheduledToday),2) as assessmentcompletion,round(((t3.clientShortlisted+t3.shared+t3.forshared+t3.Joined)*100)/(t3.totalSchedule-t3.scheduledToday),2) as resumesharedpercent,round(((t3.offered)*100)/(t3.clientShortlisted+t3.shared+t3.forshared+t3.Joined),2) as Offerconversion,round(((t3.joined)*100)/(t3.offered),2) as joiningconversion,round(((t3.totalMissed)*100)/(t3.totalSchedule-t3.scheduledToday),1) as missedconversion,round(((t3.Rejected)*100)/(t3.totalSchedule-t3.scheduledToday),1) as rejectedconversion,round(((t3.assessmentPending)*100)/(t3.totalSchedule-t3.scheduledToday-t3.totalMissed),1) as assessmentconversion from (select (select group_concat(distinct(amplifier)) from interviewSchedule where preInterviewId=t2.preInterviewId and recruiterId=t2.recruiterId) as amplifier,t2.preInterviewId,t2.recruiterId,t2.headcount,t2.targetResumeShared,t2.interviewName,t2.postedOn,t2.JobExpiryDate,count(distinct t2.emailId)as totalSchedule,t2.postedBy,t2.recruiterName,
                count(distinct case when t2.futureScheduled is not null then t2.emailId end) as scheduledToday,
                count(distinct case when t2.totalMissed is not null then t2.emailId end) as totalMissed,
                count(distinct case when t2.todayMissed is not null then t2.emailId end) as missedToday,
                count(distinct case when t2.interviewStatus in('Incomplete') then t2.emailId end ) as Rejected,
                count(distinct case when t2.interviewStatus in('Assessment in Progress') then t2.emailId end) as assessmentPending,
                count(distinct case when t2.interviewStatus in('Completed') then t2.emailId end) as Assessed,
                count(distinct case when t2.shared is not null then t2.emailId end) as shared,
                count(distinct case when t2.Joined is not null then t2.emailId end) as Joined,
                count(distinct case when t2.Offered is not null then t2.emailId end) as Offered,
                count(distinct case when t2.clientShortlisted is not null then t2.emailId end) as clientShortlisted,
                count(distinct case when t2.dropOut is not null then t2.emailId end) as dropOut,
                count(distinct case when t2.clientreject is not null then t2.emailId end) as clientreject,
                count(distinct case when t2.unAttended is not null then t2.emailId end) as unAttended,
                count(distinct case when t2.forshared is not null then t2.emailId end) as forshared,
                count(distinct case when t2.MisseddeadLead is not null then t2.emailId end) as MisseddeadLead,
                count(distinct case when t2.IncompletedeadLead is not null then t2.emailId end) as IncompletedeadLead,
                count(distinct case when t2.recruiterreject is not null then t2.emailId end) as recruiterreject
                 from (
                    select t.* from (
                    select fr.candidateId,fr.id as feedbackRequestId,isc.emailId,isc.scheduleTime,pr.id as preInterviewId,isc.recruiterId,(select rl.name from recruiterList rl left join users u on u.id=rl.corporateId where rl.id=isc.recruiterId) as recruiterName,(select concat(rl.name,'(',u.firstName,')') from recruiterList rl left join users u on u.id=rl.corporateId where rl.id=isc.recruiterId) as recruiter,
                    case when pr.interviewName is null then (select name from aspiration_company where id=pr.company_id) else pr.interviewName end as interviewName,date_format(pr.interviewStartDate,'%Y-%c-%d') as 'postedOn', date_format(pr.interviewExpireDate,'%Y-%c-%d') as 'JobExpiryDate',
                    case when (fr.id is not null and (fr.review_status=-4)) then 'Incomplete'  
                    when (fr.id is not null and cit.completion_status is not null and fr.review_status in (0,1,-2)) then 'Assessment in Progress' 
                    when (fr.id is not null and cit.completion_status is not null and fr.review_status=2) then 'Completed' 
                    end as interviewStatus,
                    case when (fr.id is not null and cit.completion_status is not null and fr.review_status=2) then fr.id end as 'Completed',
                    case when (fr.id is null and (date_format(isc.recruiterScheduleDate,'%Y-%c-%d')=CURDATE())) then isc.emailId end as todaySchedule,   
                    case when (fr.id is null and isc.scheduleTime>=now()) then isc.emailId end as futureScheduled,       
                    case when ((fr.id is not null) and (isc.candidateStatus in('Profile Shared'))) then isc.emailId end  as 'shared',
                    case when ((fr.id is not null) and (isc.candidateStatus in('Joined'))) then isc.emailId end as 'Joined',
                    case when ((fr.id is not null) and (isc.candidateStatus in('Offered','Offer Dropped','Offer Accepted'))) then isc.emailId end as 'Offered',
                    case when ((fr.id is not null) and (isc.candidateStatus in('Client Shortlisted'))) then isc.emailId end as 'clientShortlisted', 
                    case when ((fr.id is not null) and (isc.candidateStatus in('Client Screen Reject','Client Duplicate Reject','Client Interview Reject','Candidate Withdrawal','No Show','Offer Dropped','RNR','Recruiter Reject'))) then isc.emailId end  as 'dropOut',
                    case when ((fr.id is not null) and (isc.candidateStatus in('Client Screen Reject','Client Duplicate Reject','Client Interview Reject','Candidate Withdrawal'))) then isc.emailId end  as 'clientreject',
                    case when ((fr.id is not null) and (isc.candidateStatus in('Recruiter Reject'))) then isc.emailId end  as 'recruiterreject',
                    case when ((fr.id is not null and fr.review_status=2) and (isc.candidateStatus in('Client Screen Reject','Client Duplicate Reject','Client Interview Reject','Candidate Withdrawal','No Show','Offer Dropped','Offer Accepted'))) then isc.emailId end  as 'forshared',
                    case when ((fr.id is not null and fr.review_status=2) and (isc.candidateStatus in('UnAttended','Not Attended') or isc.candidateStatus is null)) then isc.emailId end  as 'unAttended',
                    case when (fr.id is null and isc.scheduleTime<now()) then isc.emailId end as totalMissed,           
                    case when (fr.id is null and (date_format(isc.scheduleTime,'%Y-%c-%d')=CURDATE() and (isc.scheduleTime<now()))) then isc.emailId end as todayMissed,  
                    case when (isc.candidateStatus is not null and isc.candidateStatusDate is not null and TIMESTAMPDIFF(DAY,isc.candidateStatusDate,now())>5 and fr.id is null and isc.scheduleTime<now()) then isc.emailId when (isc.candidateStatus is null and isc.candidateStatusDate is null and TIMESTAMPDIFF(DAY,isc.scheduleTime,now())>5 and fr.id is null and isc.scheduleTime<now()) then isc.emailId end as MisseddeadLead,                  
                    case when (isc.candidateStatus is not null and isc.candidateStatusDate is not null and TIMESTAMPDIFF(DAY,isc.candidateStatusDate,now())>5 and fr.id is not null and (fr.review_status=-4)) then isc.emailId when (isc.candidateStatus is null and isc.candidateStatusDate is null and TIMESTAMPDIFF(DAY,fr.updatedAt,now())>5 and fr.id is not null and (fr.review_status=-4)) then isc.emailId end as IncompletedeadLead,                  
                    pr.postedBy,pr.headcount,pr.targetResumeShared from interviewSchedule isc inner join preInterview pr on pr.id=isc.preInterviewId left join users u on u.emailId=isc.emailId left join interview i on i.preInterviewId=pr.id and i.createdBy=u.id left join feedback_request fr on fr.interviewId=i.id and fr.candidateId=u.id left join candidate_interview_transection cit on cit.interviewId=i.id where 1 and isc.emailId is not null and isc.recruiterId is not null  and isc.preInterviewId=" . $row['preInterviewId'] . " " . $condition . $condition2 . " group by isc.emailId,fr.id desc order by isc.emailId,fr.review_status desc
                    ) as t group by t.emailId) as t2 group by t2.preInterviewId desc,t2.recruiterId with rollup) as t3 group by t3.preInterviewId desc,t3.recruiterId  ";

            $queryData = mysqli_query($databaseConnection, $query);
            $queryResult = mysqli_fetch_all($queryData, MYSQLI_ASSOC);
            array_pop($queryResult);
            array_push($values, ...$queryResult);

        }

        if (mysqli_num_rows($companyId) > 0) {
            $total_data['data'] = $values;
            $total_data['count'] = mysqli_num_rows($queryData);
            $total_data['status'] = 1;
            $to_encode = $total_data;
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "in Error while retrieving Student information."
            );
        }


    } else {
        $to_encode = array(
            'result' => "error",
            'status' => 0,
            'errorCode' => "in Error while retrieving Student information."
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['getWorkReport'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if ($json) {
        $userId = $json['userId'];
        $userType = $json['userType'];

        if ($json['preInterviewId'] != null && $json['preInterviewId'] != '') {
            $interviewnameString = implode("','", $json['preInterviewId']);
            $interviewnameString = "'" . $interviewnameString . "'";

            $query = "SELECT 
                pr.interviewName as jobname,
                DATE_FORMAT(pr.interviewStartDate, '%Y-%c-%d') as dateofSourcing,
                (
                    (SELECT COUNT(id) FROM marketing 
                     WHERE invited = 'Y' AND promotionType = 'Naukri' 
                     AND preInterviewId IN ($interviewnameString)) +
                    (SELECT COUNT(id) FROM resume_apm 
                     WHERE resumeLocation IS NOT NULL 
                     AND preInterviewId IN ($interviewnameString)) +
                    (SELECT COUNT(id) FROM internalInvitations 
                     WHERE invited IN ('Y', 'RE') 
                     AND preId IN ($interviewnameString))
                ) as candidateInvited,
                (
                 SELECT COUNT(*) 
                 FROM interviewSchedule isc_sub 
                 WHERE isc_sub.preInterviewId IN ($interviewnameString)
                 AND isc_sub.submissionFlag = 'Y'
                ) as aiScreened,
                (
                 SELECT COUNT(*) 
                 FROM interviewSchedule isc_sub1 
                 WHERE isc_sub1.preInterviewId IN ($interviewnameString)
                 AND isc_sub1.promotionSource = 'lin'
                ) as linInvCount,
                (
                 SELECT COUNT(*) 
                 FROM interviewSchedule isc_sub2 
                 WHERE isc_sub2.preInterviewId IN ($interviewnameString)
                 AND isc_sub2.promotionSource = 'soc'
                ) as socInvCount,
                (
                 SELECT COUNT(*) 
                 FROM interviewSchedule isc_sub3 
                 WHERE isc_sub3.preInterviewId IN ($interviewnameString)
                 AND isc_sub3.candidateStatus = 'Profile Shared'
                ) as resumeShared,
                (
                 SELECT COUNT(*) 
                 FROM interviewSchedule isc_sub4 
                 WHERE isc_sub4.preInterviewId IN ($interviewnameString)
                 AND isc_sub4.candidateStatus = 'Client Shortlisted'
                ) as clientShortlisted,
                (
                 SELECT COUNT(*) 
                 FROM interviewSchedule isc_sub5 
                 WHERE isc_sub5.preInterviewId IN ($interviewnameString)
                 AND  isc_sub5.candidateStatus = 'Offered'
                ) as offered,
                (
                 SELECT COUNT(*) 
                 FROM interviewSchedule isc_sub6 
                 WHERE isc_sub6.preInterviewId IN ($interviewnameString)
                 AND  isc_sub6.candidateStatus IN ('Profile Match','Interview Scheduled','Recruiter Reject','Profile Shared','Client Shortlisted',
                 'Client Screen Reject',' Client Interview Reject','Client Duplicate Reject','Candidate Withdrawal','Offered','Joined','Offer Drop')
                ) as profileMatchTotal,
                (
                 SELECT COUNT(*) 
                 FROM interviewSchedule isc_sub7 
                 WHERE isc_sub7.preInterviewId IN ($interviewnameString)
                 AND  isc_sub7.candidateStatus IN ('Profile Shared','Client Shortlisted',
                 'Client Screen Reject',' Client Interview Reject','Client Duplicate Reject','Candidate Withdrawal','Offered','Joined','Offer Drop')
                ) as resumeSharedTotal,
                (
                 SELECT COUNT(*) 
                 FROM feedback_request fr_sub 
                 WHERE fr_sub.preInterviewId IN ($interviewnameString)
                 AND  fr_sub.review_status IN (2, 3)
                ) as aiInterviewed,
                GROUP_CONCAT(distinct p.jobpromotion SEPARATOR ', ') as jobPromotionList
            FROM 
                interviewSchedule isc
                INNER JOIN preInterview pr ON pr.id = isc.preInterviewId
                LEFT JOIN promotion p ON pr.id = p.preInterviewId
            WHERE 
                isc.emailId IS NOT NULL 
                AND isc.preInterviewId IN ($interviewnameString)
            GROUP BY 
                isc.preInterviewId
            ORDER BY 
                isc.preInterviewId;";

            $queryData = mysqli_query($databaseConnection, $query);
            if (mysqli_num_rows($queryData) > 0) {
                $total_data['data'] = mysqli_fetch_all($queryData, MYSQLI_ASSOC);
                $total_data['status'] = 1;
                $to_encode = $total_data;
            } else {
                $to_encode = array(
                    'result' => "error",
                    'status' => 0,
                    'errorCode' => "No data found."
                );
            }
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "preInterviewId is empty or null."
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'status' => 0,
            'errorCode' => "Error while retrieving information."
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['getJobMatchCount'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    if ($json) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $workexperienceMinSelect = $json['workexperienceMinSelect'];
        $workexperienceMaxSelect = $json['workexperienceMaxSelect'];
        $salaryMaxSelect = $json['salaryMaxSelect'];
        $requiredSkill = $json['requiredSkill'];

        if ((!empty($json['workexperienceMinSelect']) || $json['workexperienceMinSelect'] == '0') && !empty($json['workexperienceMaxSelect']) && !empty($json['salaryMaxSelect']) && !empty($json['requiredSkill'])) {

            $requiredSkillConditions = array_map(function ($skill) {
                return "FIND_IN_SET($skill, pd.skills) > 0";
            }, $requiredSkill);
            $requiredSkillConditionStr = implode(" OR ", $requiredSkillConditions);

            $requiredSkillConditions1 = array_map(function ($skill) {
                return "FIND_IN_SET($skill, m.skills) > 0";
            }, $requiredSkill);

            $requiredSkillConditionStr1 = implode(" OR ", $requiredSkillConditions1);

            // Correct usage of date intervals
            $dateIntDB3Month = "NOW() - INTERVAL 3 MONTH";
            $dateIntDB6Month = "NOW() - INTERVAL 6 MONTH";
            $dateIntDB12Month = "NOW() - INTERVAL 12 MONTH";

            $dateMarketingDB3Month = "DATE(NOW()) - INTERVAL 3 MONTH";
            $dateMarketingDB6Month = "DATE(NOW()) - INTERVAL 6 MONTH";
            $dateMarketingDB12Month = "DATE(NOW()) - INTERVAL 12 MONTH";

            // SQL query for fetching candidate log data
            $queryIntDB3Month = "SELECT 
            cl.userId AS candidateId, 
            cl.logTime AS actionTime
        FROM candidate_log cl
        INNER JOIN (
            SELECT userId, MAX(id) AS maxId
            FROM candidate_log
            WHERE userId != 0 
            GROUP BY userId
        ) AS latestLogs ON cl.id = latestLogs.maxId
        INNER JOIN professionaldetails pd ON pd.candidateId = cl.userId
        INNER JOIN users u ON u.id = cl.userId
        WHERE pd.salary IS NOT NULL 
            AND pd.skills IS NOT NULL
            AND pd.skills != '' 
            AND pd.workExperience IS NOT NULL 
            AND pd.salary < $salaryMaxSelect
            AND pd.workExperience > $workexperienceMinSelect AND pd.workExperience < $workexperienceMaxSelect
            AND (
                $requiredSkillConditionStr
            )
            AND cl.logTime >= $dateIntDB3Month;";

            $queryIntDB6Month = "SELECT 
            cl.userId AS candidateId, 
            cl.logTime AS actionTime
        FROM candidate_log cl
        INNER JOIN (
            SELECT userId, MAX(id) AS maxId
            FROM candidate_log
            WHERE userId != 0 
            GROUP BY userId
        ) AS latestLogs ON cl.id = latestLogs.maxId
        INNER JOIN professionaldetails pd ON pd.candidateId = cl.userId
        INNER JOIN users u ON u.id = cl.userId
        WHERE pd.salary IS NOT NULL 
            AND pd.skills IS NOT NULL
            AND pd.skills != '' 
            AND pd.workExperience IS NOT NULL 
            AND pd.salary < $salaryMaxSelect
            AND pd.workExperience > $workexperienceMinSelect AND pd.workExperience < $workexperienceMaxSelect
            AND (
                $requiredSkillConditionStr
            )
            AND cl.logTime >= $dateIntDB6Month;";

            $queryIntDB12Month = "SELECT 
            cl.userId AS candidateId, 
            cl.logTime AS actionTime
        FROM candidate_log cl
        INNER JOIN (
            SELECT userId, MAX(id) AS maxId
            FROM candidate_log
            WHERE userId != 0 
            GROUP BY userId
        ) AS latestLogs ON cl.id = latestLogs.maxId
        INNER JOIN professionaldetails pd ON pd.candidateId = cl.userId
        INNER JOIN users u ON u.id = cl.userId
        WHERE pd.salary IS NOT NULL 
            AND pd.skills IS NOT NULL
            AND pd.skills != '' 
            AND pd.workExperience IS NOT NULL 
            AND pd.salary < $salaryMaxSelect
            AND pd.workExperience > $workexperienceMinSelect AND pd.workExperience < $workexperienceMaxSelect
            AND (
                $requiredSkillConditionStr
            )
            AND cl.logTime >= $dateIntDB12Month;";

            $queryMarketingDB3Month = " SELECT DISTINCT m.emailId 
            FROM marketing m
            WHERE m.skills IS NOT NULL
              AND m.skills != '' 
              AND m.currentSalary IS NOT NULL 
              AND m.workExperience IS NOT NULL
              AND m.currentSalary < $salaryMaxSelect
              AND m.workExperience > $workexperienceMinSelect AND m.workExperience < $workexperienceMaxSelect
              AND (
                $requiredSkillConditionStr1
               )
              AND m.uploadAt >= $dateMarketingDB3Month;";

            $queryMarketingDB6Month = " SELECT DISTINCT m.emailId 
            FROM marketing m
            WHERE m.skills IS NOT NULL
              AND m.skills != '' 
              AND m.currentSalary IS NOT NULL 
              AND m.workExperience IS NOT NULL
              AND m.currentSalary < $salaryMaxSelect
              AND m.workExperience > $workexperienceMinSelect AND m.workExperience < $workexperienceMaxSelect
              AND (
                $requiredSkillConditionStr1
               )
              AND m.uploadAt >= $dateMarketingDB6Month;";

            $queryMarketingDB12Month = " SELECT DISTINCT m.emailId 
            FROM marketing m
            WHERE m.skills IS NOT NULL
              AND m.skills != '' 
              AND m.currentSalary IS NOT NULL 
              AND m.workExperience IS NOT NULL
              AND m.currentSalary < $salaryMaxSelect
              AND m.workExperience > $workexperienceMinSelect AND m.workExperience < $workexperienceMaxSelect
              AND (
                $requiredSkillConditionStr1
               )
              AND m.uploadAt >= $dateMarketingDB12Month;";

            // Fetch query results
            $queryData1 = mysqli_query($databaseConnection, $queryIntDB3Month);
            $queryData2 = mysqli_query($databaseConnection, $queryIntDB6Month);
            $queryData3 = mysqli_query($databaseConnection, $queryIntDB12Month);
            $queryData4 = mysqli_query($databaseConnection, $queryMarketingDB3Month);
            $queryData5 = mysqli_query($databaseConnection, $queryMarketingDB6Month);
            $queryData6 = mysqli_query($databaseConnection, $queryMarketingDB12Month);

            $total_data = [];

            // Check for data existence and store counts
            if (
                mysqli_num_rows($queryData1) > 0 || mysqli_num_rows($queryData2) > 0 || mysqli_num_rows($queryData3) > 0 ||
                mysqli_num_rows($queryData4) > 0 || mysqli_num_rows($queryData5) > 0 || mysqli_num_rows($queryData6) > 0
            ) {
                $total_data['intDBJobMatch3monthCount'] = (mysqli_num_rows($queryData1) > 0) ? mysqli_num_rows($queryData1) : 0;
                $total_data['intDBJobMatch6monthCount'] = (mysqli_num_rows($queryData2) > 0) ? mysqli_num_rows($queryData2) : 0;
                $total_data['intDBJobMatch12monthCount'] = (mysqli_num_rows($queryData3) > 0) ? mysqli_num_rows($queryData3) : 0;
                $total_data['marketingdata3Month'] = (mysqli_num_rows($queryData4) > 0) ? mysqli_num_rows($queryData4) : 0;
                $total_data['marketingdata6Month'] = (mysqli_num_rows($queryData5) > 0) ? mysqli_num_rows($queryData5) : 0;
                $total_data['marketingdata12Month'] = (mysqli_num_rows($queryData6) > 0) ? mysqli_num_rows($queryData6) : 0;
                $total_data['status'] = 1;
            } else {
                $total_data = [
                    'result' => "error",
                    'status' => 0,
                    'errorCode' => "No data found."
                ];
            }

            echo json_encode($total_data);
        } else {
            echo json_encode(['result' => "error", 'status' => 0, 'errorCode' => "preInterviewId is empty or null."]);
        }
    } else {
        echo json_encode(['result' => "error", 'status' => 0, 'errorCode' => "Error while retrieving information."]);
    }
} else if (isset($_GET['getServiceReportData'])) {
    // this method is added by arun on 23 Mar 2023 to fetch the work Report data
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if ($json) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $filterQry = '';
        $condition = '';
        $condition2 = '';
        $condition3 = '';
        $condition4 = '';
        $condition6 = ' and pr.interviewType!="Practice" ';
        $values = array();
        $limit = $json['limit'];
        $start = ($json['page'] - 1) * $limit;
        $limit_query = $limit == 0 ? "" : " limit " . $start . "," . $limit;
        $servicetypefilter = '';
        $interviewStatusCondition = '';

        if ($json['hiringCompanyName'] != '') {

            $condition .= " and pr.company_id in ('" . $json['hiringCompanyName'] . "') ";
        }


        if ($userType != 'corporate') {
            $servicetypefilter = "and pr.serviceType != 'IAS' ";
            $servicetypeArray = $json['serviceType'];
            if ($servicetypeArray !== null) {

                $servicetypeConditions = array_map(function ($type) {
                    return "pr.serviceType = '$type'";
                }, $servicetypeArray);

                $servicetypefilter = " AND (" . implode(" OR ", $servicetypeConditions) . ")";
            }
        }
        if ($json['jobName'] != '' && $json['jobName'] != null && $json['jobName'] != ['0']) {

            $condition .= " and pr.id IN (" . implode(',', $json['jobName']) . ")";
        }

        if ($json['source'] != '' && $json['source'] != null && $json['source'] != "") {

            if ($json['source'] == "GopracDB") {
                $condition3 .= " and isc.promotionSource IS NULL";
            } else {
                $condition3 .= " and (isc.promotionSource='" . $json['source'] . "' )";
            }

            // $condition .=" and pr.id IN (".implode(',',$json['jobName']).")";
        }


        if ($json['jobName'] != '' && $json['jobName'] != null && $json['jobName'] != ['0']) {
        } else {
            if ($json['scheduleFrom'] != "" && $json['scheduleTo'] != "") {
                $condition .= " and (date_format(pr.interviewStartDate,'%Y-%m-%d')) >= '" . $json['scheduleFrom'] . "' and (date_format(pr.interviewStartDate,'%Y-%m-%d')) <= '" . $json['scheduleTo'] . "'";
            } else if ($json['scheduleFrom'] != "") {
                $condition .= " AND pr.interviewStartDate >= '" . $json['scheduleFrom'] . "' ";
            }

            if ($json['resumeSharedFrom'] != "" && $json['resumeSharedTo'] != "") {
                $condition .= " and (date_format(isc.resumeSharedDate,'%Y-%m-%d')) >= '" . $json['resumeSharedFrom'] . "' and (date_format(isc.resumeSharedDate,'%Y-%m-%d')) <= '" . $json['resumeSharedTo'] . "'";
            } else if ($json['resumeSharedFrom'] != "") {
                $condition .= " AND isc.resumeSharedDate >= '" . $json['resumeSharedFrom'] . "' ";
            }
        }



        if ($userType == 'corporate') {
            $servicetypefilter = "and pr.serviceType = 'IAS' ";
            // $condition .=" and pr.userId=" .$userId."";
            $condition .= " and pr.id IN (SELECT preinterviewId FROM preInterview_corporate WHERE userId=" . $userId . ") ";
            // $condition2 .=" and isc.recruiterId IN (select id from recruiterList where corporateId=".$userId." ) ";
        }
        if ($json['includeArchive'] != "" && $json['includeArchive'] == "Y") {
        } else {
            $interviewStatusCondition .= " and pr.interviewStatus='Active'";
        }



        $companyIdquery = "select distinct(pr.id) as preInterviewId,pr.company_id,pr.hiringCompanies,pr.salaryRage,pr.jobLocation,pr.jdDocument from preInterview pr inner join interviewSchedule isc on isc.preInterviewId=pr.id where 1 " . $interviewStatusCondition . " " . $condition . " " . $servicetypefilter . $condition3 . " " . $condition6 . " order by pr.id desc ";
        // sourabh removed this
        // AND isc.recruiterId IS NOT NULL

        // echo $companyIdquery;
        // exit();




        $companyId_count = mysqli_query($databaseConnection, $companyIdquery);
        $companyId = mysqli_query($databaseConnection, $companyIdquery . $limit_query);

        // echo $companyIdquery. $limit_query;
        // exit();
        // while($row=mysqli_fetch_assoc($companyId)){
        // echo $row['preInterviewId'] . " \n";
        // }
        // exit();

        $promotionCount = [];

        while ($row = mysqli_fetch_assoc($companyId)) {
            $query = "select t3.*,CASE WHEN t3.Source = 'Goprac DB' THEN t3.gopraccount
                        WHEN t3.Source = 'Naukri' THEN t3.naucount
                        WHEN t3.Source = 'Internal Sourcing Team' THEN t3.isccount
                        WHEN t3.Source = 'Social Media' THEN t3.socCount
                        WHEN t3.Source = 'LinkedIn' THEN t3.linCount
                        ELSE 0 END AS invitedcount
                        FROM (
                        SELECT t2.companyNoticePeriod, t2.companySalaryRange, t2.publish,t2.preInterviewStatus, t2.pendingInterviews, t2.preInterviewId,t2.pr_id,t2.recruiterId,t2.headcount,t2.targetResumeShared,t2.interviewName,t2.postedOn,t2.JobExpiryDate,count(distinct t2.emailId)as totalSchedule,t2.postedBy,
                        count(distinct case when t2.eligible is not null then t2.emailId end) as eligible,
                        count(distinct case when t2.futureScheduled is not null then t2.emailId end) as scheduledToday,
                        count(distinct case when t2.totalMissed is not null then t2.emailId end) as totalMissed,
                        count(distinct case when t2.todayMissed is not null then t2.emailId end) as missedToday,
                        count(distinct case when t2.interviewStatus in('Incomplete') then t2.emailId end ) as Rejected,
                        count(distinct case when t2.interviewStatus in('Assessment in Progress') then t2.emailId end) as assessmentPending,
                        count(distinct case when t2.interviewStatus in('Completed') then t2.emailId end) as Assessed,
                        count(distinct case when t2.shared is not null then t2.emailId end) as shared,
                        count(distinct case when t2.Joined is not null then t2.emailId end) as Joined,
                        count(distinct case when t2.Offered is not null then t2.emailId end) as Offered,
                        count(distinct case when t2.totalOffered is not null then t2.emailId end) as totalOffered,
                        count(distinct case when t2.OfferedDropped is not null then t2.emailId end) as OfferedDropped,
                        count(distinct case when t2.OfferedAccepted is not null then t2.emailId end) as OfferedAccepted,
                        count(distinct case when t2.clientShortlisted is not null then t2.emailId end) as clientShortlisted,
                        count(distinct case when t2.dropOut is not null then t2.emailId end) as dropOut,
                        count(distinct case when t2.candidateWithdrow is not null then t2.emailId end) as candidateWithdrow,
                        count(distinct case when t2.clientreject is not null then t2.emailId end) as clientreject,
                        count(distinct case when t2.clientScreenreject is not null then t2.emailId end) as clientScreenreject,
                        count(distinct case when t2.clientIntreject is not null then t2.emailId end) as clientIntreject,
                        count(distinct case when t2.unAttended is not null then t2.emailId end) as unAttended,
                        count(distinct case when t2.forshared is not null then t2.emailId end) as forshared,
                        count(distinct case when t2.recruiterreject is not null then t2.emailId end) as recruiterreject,t2.jobInvited,count(distinct case when t2.nactionscheduled is not null then t2.emailId end) as nactionscheduled,
                        count(distinct case when t2.applied is not null then t2.emailId end) as applied,
                        count(distinct case when t2.applyTotal is not null then t2.emailId end) as applyTotal,
                        count(distinct case when t2.totalClientShort is not null then t2.emailId end) as totalClientShort,
                        count(distinct case when t2.totalSharedSum is not null then t2.emailId end) as totalSharedSum,
                        count(distinct case when t2.totalEligibalCount is not null then t2.emailId end) as totalEligibalCount,
                        count(distinct case when t2.socCount is not null then t2.emailId end) as socCount,
                        count(distinct case when t2.linCount is not null then t2.emailId end) as linCount,
                        max(distinct case when t2.profileAge is not null then t2.profileAge end) as profilemaxAge,
                        max(distinct case when t2.jobAge is not null then t2.jobAge end) as jobmaxAge,
                        max(distinct case when t2.clientShortlistedAge is not null then t2.clientShortlistedAge end) as clientShortlistedmaxAge,
                        t2.promotionSource, count(distinct case when t2.fjobinvited is not null then t2.emailId end) as fjobinvited,
                        CASE
                            WHEN t2.promotionSource = 'lin' THEN 'LinkedIn'
                            WHEN t2.promotionSource = 'nau' THEN 'Naukri'
                            WHEN t2.promotionSource = 'soc' THEN 'Social Media'
                            WHEN t2.promotionSource = 'ist' THEN 'Internal Sourcing Team'
                            ELSE 'Goprac DB'
                        END AS Source,
                        (select count(id) from marketing where invited='Y' and promotionType='Naukri'and preInterviewId=" . $row['preInterviewId'] . ") as naucount,
        (select count(id) from resume_apm where resumeLocation is not null and preInterviewId=" . $row['preInterviewId'] . " ) as isccount,
        (select count(id) from internalInvitations where invited in ('Y','RE') and preId=" . $row['preInterviewId'] . " ) as gopraccount
        from (
        select t.* from (
        select  pp1.fieldValue as companyNoticePeriod, pp2.fieldValue as companySalaryRange, fr.candidateId,fr.id as feedbackRequestId,isc.emailId,isc.interviewId,isc.scheduleTime,isc.submissionFlag,pr.id as preInterviewId,pr.id as pr_id,isc.recruiterId,pr.pendingInterviews,pr.interviewStatus as preInterviewStatus,
        case when pr.interviewName is null then (select name from aspiration_company where id=pr.company_id) else pr.interviewName end as interviewName,date_format(pr.interviewStartDate,'%Y-%c-%d') as 'postedOn' , date_format(pr.interviewExpireDate,'%Y-%c-%d') as 'JobExpiryDate' ,
        case when (fr.id is not null and (fr.review_status=-4)) then 'Incomplete'
        when (fr.id is not null and cit.completion_status is not null and fr.review_status in (0,1,-2)) then 'Assessment in Progress'
        when (fr.id is not null and fr.review_status=2) then 'Completed'
        end as interviewStatus,
        case when (1 and (isc.promotionSource='lin' )) then isc.emailId end as 'linCount' ,
        case when (1 and (isc.promotionSource='soc' )) then isc.emailId end as 'socCount' ,
        case when (1 and (isc.candidateStatus in('Interview Scheduled','Profile Match'))) then isc.emailId end as 'eligible' ,
        case when (fr.id is not null and cit.completion_status is not null and fr.review_status=2) then fr.id end as 'Completed' ,
        case when (fr.id is null and (date_format(isc.recruiterScheduleDate,'%Y-%c-%d')=CURDATE())) then isc.emailId end as todaySchedule,
        case when (fr.id is null and isc.scheduleTime>=now()) then isc.emailId end as futureScheduled,
        case when (1 and (isc.candidateStatus in('Profile Shared'))) then isc.emailId end as 'shared',
        case when (1 and (isc.candidateStatus in('Joined'))) then isc.emailId end as 'Joined',
        case when (1 and (isc.candidateStatus in('Offered'))) then isc.emailId end as 'Offered',
        case when (1 and (isc.candidateStatus in('Offered','Offer Drop','Offer Accepted','Joined'))) then isc.emailId end as 'totalOffered',
        case when (1 and (isc.candidateStatus in('Offer Drop'))) then isc.emailId end as 'OfferedDropped',
        case when (1 and (isc.candidateStatus in('Offer Accepted'))) then isc.emailId end as 'OfferedAccepted',
        case when (1 and (isc.candidateStatus in('Client Shortlisted'))) then isc.emailId end as 'clientShortlisted',
        case when (1 and (isc.candidateStatus in('Client Screen Reject','Client Duplicate Reject','Client Interview Reject','Candidate Withdrawal','No Show','Offer Dropped','RNR','Recruiter Reject'))) then isc.emailId end as 'dropOut',
        case when (1 and (isc.candidateStatus in('Client Screen Reject','Client Duplicate Reject','Client Interview Reject','Candidate Withdrawal'))) then isc.emailId end as 'clientreject',
        case when (1 and (isc.candidateStatus in('Client Screen Reject','Client Duplicate Reject'))) then isc.emailId end as 'clientScreenreject',
        case when (1 and (isc.candidateStatus in('Client Interview Reject'))) then isc.emailId end as 'clientIntreject',
        case when (1 and (isc.candidateStatus in('Client Interview Reject','Client Shortlisted','Candidate Withdrawal','Offered','Offer Drop','Offer Accepted','Joined'))) then isc.emailId end as 'totalClientShort',
        case when (1 and (isc.candidateStatus in('Profile Shared','Client Screen Reject','Client Duplicate Reject','Client Interview Reject','Client Shortlisted','Candidate Withdrawal','Offered','Offer Drop','Offer Accepted','Joined'))) then isc.emailId end as 'totalSharedSum',
        case when (1 and (isc.candidateStatus in('Interview Scheduled','Profile Match','Recruiter Reject','Profile Shared','Client Screen Reject','Client Duplicate Reject','Client Interview Reject','Client Shortlisted','Candidate Withdrawal','Offered','Offer Drop','Offer Accepted','Joined'))) then isc.emailId end as 'totalEligibalCount',
        case when (1 and (isc.candidateStatus in('Candidate Withdrawal','No Show','RNR'))) then isc.emailId end as 'candidateWithdrow',
        case when (1 and (isc.candidateStatus in('Recruiter Reject'))) then isc.emailId end as 'recruiterreject',case when (fr.id IS NULL AND fr.review_status IS NULL AND isc.scheduleTime is null) then isc.emailId end as 'fjobinvited',case WHEN (isc.candidateStatus is null and fr.id IS NULL AND fr.review_status IS NULL AND isc.scheduleTime is not null) THEN isc.emailId WHEN(isc.candidateStatus is null and fr.id IS NULL AND( isc.scheduleTime != isc.firstScheduleDate ) AND(DATEDIFF(isc.scheduleTime, NOW())) >= 1) THEN isc.emailId WHEN(isc.candidateStatus is null and fr.id IS NULL AND isc.scheduleTime = 1) THEN isc.emailId WHEN(isc.candidateStatus is null and fr.id IS NULL AND( isc.scheduleTime = isc.firstScheduleDate) AND(DATEDIFF(isc.scheduleTime, NOW())) >= 1) THEN isc.emailId end as nactionscheduled,case when ((fr.id is not null and fr.review_status=2) and (isc.candidateStatus in('Client Screen Reject','Client Duplicate Reject','Client Interview Reject','Candidate Withdrawal','No Show','Offer Dropped','Offer Accepted'))) then isc.emailId end as 'forshared',
        case when ((fr.id is not null and fr.review_status=2) and (isc.candidateStatus in('UnAttended','Not Attended','Assessment Awaited','Under Process') or isc.candidateStatus is null)) then isc.emailId end as 'unAttended',
        case when (fr.id is null and isc.scheduleTime < now()) then isc.emailId end as totalMissed,
            case when (fr.id is null and (date_format(isc.scheduleTime,'%Y-%c-%d')=CURDATE() and (isc.scheduleTime < now()))) then isc.emailId end as todayMissed,
            case when (isc.candidateStatus is not null and isc.candidateStatus in('Profile Shared'))
            then TIMESTAMPDIFF(DAY, isc.candidateStatusDate, NOW()) end as profileAge,
            case when (isc.candidateStatus is not null and isc.candidateStatus in('Client Shortlisted') and fr.id is not null )
            then TIMESTAMPDIFF(DAY, isc.candidateStatusDate, NOW()) end as clientShortlistedAge,
            case when (pr.interviewStartDate is not null )
            then TIMESTAMPDIFF(DAY, pr.interviewStartDate, NOW()) end as jobAge,
            case when (1 and (isc.candidateStatus in('applied'))) then isc.emailId end as 'applied' ,
            case when (1 and (isc.submissionFlag IN('Y','WA'))) then isc.emailId end as 'applyTotal' ,
            pr.postedBy, pr.IHeadCount as headcount,pr.targetResumeShared,CASE WHEN MAX(p.jobInvited) IS NULL THEN 0 ELSE SUBSTRING_INDEX(MAX(p.jobInvited), '/' , 1) END AS jobInvited,isc.promotionSource , pr.publish
            from interviewSchedule isc
            inner join preInterview pr on pr.id=isc.preInterviewId
            LEFT JOIN profilePreferences pp1 ON
            pp1.preInterviewId = pr.id
            and pp1.fieldName = 'noticePeriod'
            LEFT JOIN profilePreferences pp2 ON
            pp2.preInterviewId = pr.id
            and pp2.fieldName = 'currentSalary'
            left join users u on u.emailId=isc.emailId
            left join interview i on i.id=isc.interviewId
            left join feedback_request fr on fr.interviewId=i.id and fr.candidateId=u.id
            left join candidate_interview_transection cit on cit.interviewId=i.id
            left join promotion p on pr.id=p.preInterviewId
            where 1 and isc.emailId is not null and isc.preInterviewId=" . $row['preInterviewId'] . " " . $condition . $condition2 . $condition3 . "" . $servicetypefilter . "
            GROUP by isc.emailId,isc.candidateStatus
            ORDER BY
					isc.emailId,
					CASE 
					    WHEN isc.candidateStatus IS NOT NULL AND isc.candidateStatus <> 'Profile Mismatch' THEN 1
					    WHEN isc.candidateStatus IN ('Profile Match', 'Interview Scheduled') THEN 2
					    ELSE 3
					END,
				  	isc.id desc
            ) as t
            group by t.emailId) as t2
            group by t2.pr_id,t2.promotionSource) as t3
            group by t3.pr_id ,t3.promotionSource";


            // echo $query;
            // exit();
            // sourabh remove
            // and isc.recruiterId is not null
            // AND ((fr.id IS not NULL and fr.review_Status !=-4) || isc.scheduleTime is not null)

            $queryData = mysqli_query($databaseConnection, $query);
            // if (!$queryData) {
            // // If there's an error, print the error message
            // echo "Error: " . mysqli_error($databaseConnection);
            // }
            $queryResult = mysqli_fetch_all($queryData, MYSQLI_ASSOC);
            // array_pop($queryResult);
            array_push($values, ...$queryResult);



            $promotionQuery = "SELECT COUNT(*) as pCount FROM promotion WHERE preInterviewId = " . $row['preInterviewId'] . " ";
            $promotionArchivedQuery = "SELECT COUNT(*) as aCount FROM promotion WHERE preInterviewId = " . $row['preInterviewId'] . " and archiveDate is not null ";
            $promotionResult = mysqli_query($databaseConnection, $promotionQuery);
            $promotionArchivedResult = mysqli_query($databaseConnection, $promotionArchivedQuery);
            // Fetch the count
            $promotionCountRow = mysqli_fetch_assoc($promotionResult);
            $promotionArchivedCountRow = mysqli_fetch_assoc($promotionArchivedResult);
            $promotion = $promotionCountRow['pCount'];
            $promotionArchived = $promotionArchivedCountRow['aCount'];

            // Store the preInterviewId and its corresponding promotion count
            $promotionCount[] = [
                'preInterviewId' => $row['preInterviewId'],
                'promotionCount' => $promotion,
                'archiveCount' => $promotionArchived,
            ];
        }

        if (mysqli_num_rows($companyId) > 0) {
            $total_data['data'] = $values;
            $total_data['count'] = mysqli_num_rows($companyId_count);
            $total_data['status'] = 1;
            $total_data['promotionCount'] = $promotionCount;
            $to_encode = $total_data;
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "in Error while retrieving Student information."
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'status' => 0,
            'errorCode' => "in Error while retrieving Student information. invalid request"
        );
    }
    echo json_encode($to_encode);

} else if (isset($_GET['archiveJobPromotionData'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);


    if ($json) {
        $userId = $json['userId'];
        $userType = $json['userType'];


        if (isset($json['preInterviewId'])) {

            if ($json['flag'] == 1) {
                $updateQuery = "UPDATE promotion SET archiveDate = CURDATE() WHERE preInterviewId=" . $json['preInterviewId'] . " ";
            } else if ($json['flag'] == 2) {
                $updateQuery = "UPDATE promotion SET archiveDate = null WHERE preInterviewId=" . $json['preInterviewId'] . " ";
            }
            // echo $updateQuery ;

        } else {
            $archivedJobs = $json['archivedJobs'];
            $archivedJobsString = implode(',', $archivedJobs);
            $archivedJobsString = mysqli_real_escape_string($databaseConnection, $archivedJobsString);
            $updateQuery = "UPDATE promotion SET archiveDate = CURDATE() WHERE id IN ($archivedJobsString)";
            // echo $updateQuery ;

        }

        $updateResult = mysqli_query($databaseConnection, $updateQuery);
        if (!$updateResult) {
            // Handle the error if the query fails
            echo "Error updating records: " . mysqli_error($databaseConnection);
        }

        if ($updateResult) {
            $to_encode = array(
                'result' => "success",
                'status' => 1,
                'Code' => "success while inserting"
            );
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "in Error while inserting."
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'status' => 0,
            'errorCode' => "in Error while inserting."
        );
    }
    echo json_encode($to_encode);



} else if (isset($_GET['JobPostingStatus'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if ($json) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $id = $json['id'];
        $preId = $json['preId'];
        $val = $json['val'];
        $jobpromotion = $json['jobpromotion'];

        if ($val == 'Work in Progress') {
            $updateQuery = "UPDATE promotion SET JobPostingStatus ='$val' , JobPostingDate = now() WHERE id IN ($id)";
        } else if ($val == 'Closed') {
            $updateQuery = "UPDATE promotion SET JobPostingStatus ='$val' , JobPostingDate = now() WHERE id IN ($id)";
        } else if ($val == 'Open') {
            $updateQuery = "UPDATE promotion SET JobPostingStatus ='$val'  WHERE id IN ($id)";
        }
        // echo $updateQuery ;
        $updateResult = mysqli_query($databaseConnection, $updateQuery);

        if (!$updateResult) {
            // Handle the error if the query fails
            echo "Error updating records: " . mysqli_error($databaseConnection);
        }

        if ($updateResult) {
            $to_encode = array(
                'result' => "success",
                'status' => 1,
                'Code' => "success while inserting"
            );
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "in Error while inserting."
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'status' => 0,
            'errorCode' => "in Error while inserting."
        );
    }
    echo json_encode($to_encode);


} else if (isset($_GET['PracticePostingStatus'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if ($json) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $id = $json['id'];
        $candidateId = $json['candidateId'];
        $preId = $json['preId'];
        $val = $json['val'];

        if ($json['val'] != '') {
            $updateQuery = "UPDATE candidateInterviewMapping SET practiceStatus ='$val' WHERE id = '" . $json['id'] . "' and candidateId = '" . $json['candidateId'] . "' and preInterviewId = '" . $json['preId'] . "'";
        }

        $updateResult = mysqli_query($databaseConnection, $updateQuery);

        if (!$updateResult) {
            // Handle the error if the query fails
            echo "Error updating records: " . mysqli_error($databaseConnection);
        }

        if ($updateResult) {
            $to_encode = array(
                'result' => "success",
                'status' => 1,
                'Code' => "success while updating"
            );
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "in Error while updating."
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'status' => 0,
            'errorCode' => "in Error while updating."
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['getPromotionData'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if ($json) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $flag = $json['flag'];


        $jobPostingCondition = '';
        $jobPromotionSourceCondition = '';
        $jobpreId = '';


        if (isset($json['JobPostingFilter']) && $json['JobPostingFilter'] !== null) {

            if (is_array($json['JobPostingFilter'])) {

                $JobPostingFilter = implode("', '", $json['JobPostingFilter']);
                $jobPostingCondition = " AND JobPostingStatus in ('$JobPostingFilter') ";

            } else {

                $JobPostingFilter = $json['JobPostingFilter'];
                $jobPostingCondition = " AND JobPostingStatus in ('$JobPostingFilter') ";
            }
        } else {

            $JobPostingFilter = '';
            $jobPostingCondition = "";

        }

        if (isset($json['JobPromotionSourceFilter']) && $json['JobPromotionSourceFilter'] !== null) {

            if (is_array($json['JobPromotionSourceFilter'])) {

                $JobPromotionSourceFilter = implode("', '", $json['JobPromotionSourceFilter']);
                $jobPromotionSourceCondition = " AND p.jobpromotion in ('$JobPromotionSourceFilter') ";

            } else {

                $JobPromotionSourceFilter = $json['JobPromotionSourceFilter'];
                $jobPromotionSourceCondition = " AND p.jobpromotion in ('$JobPromotionSourceFilter') ";
            }
        } else {

            $JobPromotionSourceFilter = '';
            $jobPromotionSourceCondition = "";

        }
        //   echo  $jobPostingCondition;

        if (!empty($json['jobid'])) {

            if (is_array($json['jobid'])) {
                $preId = implode(',', $json['jobid']);
                $jobpreId = "  and pr.id in ('$preId') ";
            } else {
                $preId = $json['jobid'];
                $jobpreId = "  and pr.id in ('$preId') ";
            }

        }

        $values = array();

        if ($flag == 1) {
            $query1 = "SELECT
            p.id AS id,
            pr.id AS preId,
            p.jobpromotion,
            pr.interviewStartDate,
            pr.interviewName AS JobName,
            ac.name AS CompanyName,
            pr.serviceType,
            pr.publish as publish,
            p.uploadFlag,
            case when now() > (p.JobPostingDate + INTERVAL 24 HOUR) then 1 else 0 end as olderFlag,
            CASE 
            WHEN p.uploadFlag = 1 AND p.JobPostingStatus = 'Work in Progress' AND pr.publish = 'Y' THEN 1
            ELSE 0
            END AS excelFlag,
            CASE
                WHEN (p.JobPostingStatus='Work in Progress' and p.archiveDate IS NULL) THEN TIMESTAMPDIFF(DAY, p.JobPostingDate, NOW())
                WHEN (p.JobPostingStatus='Closed' and p.archiveDate IS NULL) THEN TIMESTAMPDIFF(DAY, p.JobPostingDate, NOW())
                WHEN p.archiveDate IS NOT NULL THEN p.archiveDate
                ELSE ''
            END AS JobPostingAge,
            p.JobPostingStatus AS JobPostingStatus,
            CASE
                WHEN p.jobpromotion = 'S'   THEN 'Social Media'
                WHEN p.jobpromotion = 'N'   THEN 'Naukri'
                WHEN p.jobpromotion = 'L'   THEN 'LinkedIn'
                ELSE ''
            END AS PromotionType,
            (SELECT COUNT(*) FROM marketing WHERE uploadAt = CURDATE() AND preInterviewId = pr.id AND promotionType=CASE WHEN p.jobpromotion = 'S' THEN 'Social Media'WHEN p.jobpromotion = 'N' THEN 'Naukri'WHEN p.jobpromotion = 'L' THEN 'Linkedin'ELSE ''END) AS upcount,
            (SELECT jobInvitedDate FROM marketing WHERE preInterviewId = pr.id order by id desc limit 1) as jobInvitedDate
            FROM
            promotion p
            JOIN
            preInterview pr ON p.preInterviewId = pr.id
            JOIN
            aspiration_company ac ON ac.id = pr.company_Id
            WHERE
            1
            AND pr.publish = 'Y'
            AND p.jobpromotion NOT IN ('G','I') 
            " . $jobPostingCondition . " " . $jobpreId . " " . $jobPromotionSourceCondition . "
            ORDER BY
            pr.id DESC;
            ";
        } elseif ($flag == 0) {
            $query1 = "SELECT
            p.id AS id,
            pr.id AS preId,
            p.jobpromotion,
            pr.interviewStartDate,
            pr.interviewName AS JobName,
            ac.name AS CompanyName,
            pr.serviceType,
            p.uploadFlag,
            case when now() > (p.JobPostingDate + INTERVAL 24 HOUR) then 1 else 0 end as olderFlag,
            CASE 
                        WHEN p.uploadFlag = 1 AND p.JobPostingStatus = 'Work in Progress' AND pr.publish = 'Y' THEN 1
                        ELSE 0
                        END AS excelFlag,
            CASE
                        WHEN (p.JobPostingStatus='Work in Progress' and p.archiveDate IS NULL) THEN TIMESTAMPDIFF(DAY, p.JobPostingDate, NOW())
                        WHEN (p.JobPostingStatus='Closed' and p.archiveDate IS NULL) THEN TIMESTAMPDIFF(DAY, p.JobPostingDate, NOW())
                            WHEN p.archiveDate IS NOT NULL THEN p.archiveDate
                            ELSE ''
                        END AS JobPostingAge,
            p.JobPostingStatus AS JobPostingStatus,
            pr.publish as publish,
            CASE
                            WHEN p.jobpromotion = 'S'   THEN 'Social Media'
                            WHEN p.jobpromotion = 'N'   THEN 'Naukri'
                            WHEN p.jobpromotion = 'L'   THEN 'LinkedIn'
                            ELSE ''
            END AS PromotionType,
            (SELECT COUNT(*) FROM marketing WHERE uploadAt = CURDATE() AND preInterviewId = pr.id AND promotionType=CASE WHEN p.jobpromotion = 'S' THEN 'Social Media'WHEN p.jobpromotion = 'N' THEN 'Naukri'WHEN p.jobpromotion = 'L' THEN 'Linkedin'ELSE ''END) AS upcount,
            (SELECT jobInvitedDate FROM marketing WHERE preInterviewId = pr.id order by id desc limit 1) as jobInvitedDate
            FROM
            promotion p
            JOIN
            preInterview pr ON p.preInterviewId = pr.id
            JOIN
            aspiration_company ac ON ac.id = pr.company_Id
            WHERE
            1
            AND p.archiveDate IS NULL
            AND pr.publish = 'Y'
            AND p.jobpromotion NOT IN ('G','I')  " . $jobPostingCondition . " " . $jobpreId . " " . $jobPromotionSourceCondition . "
            ORDER BY
            pr.id DESC;
            ";
        } else {
            $query1 = "SELECT
            p.id AS id,
            pr.id AS preId,
            p.jobpromotion,
            pr.interviewStartDate,
            pr.interviewName AS JobName,
            ac.name AS CompanyName,
            pr.serviceType,
            p.uploadFlag,
            case when now() > (p.JobPostingDate + INTERVAL 24 HOUR) then 1 else 0 end as olderFlag,
            CASE 
                        WHEN p.uploadFlag = 1 AND p.JobPostingStatus = 'Work in Progress' AND pr.publish = 'Y' THEN 1
                        ELSE 0
                        END AS excelFlag,
            CASE
                            WHEN (p.JobPostingStatus='Work in Progress' and p.archiveDate IS NULL) THEN TIMESTAMPDIFF(DAY, p.JobPostingDate, NOW())
                            WHEN (p.JobPostingStatus='Closed' and p.archiveDate IS NULL) THEN TIMESTAMPDIFF(DAY, p.JobPostingDate, NOW())
                            WHEN p.archiveDate IS NOT NULL THEN p.archiveDate
                            ELSE ''
                        END AS JobPostingAge,
            p.JobPostingStatus AS JobPostingStatus,
            pr.publish as publish,
            CASE
                            WHEN p.jobpromotion = 'S'   THEN 'Social Media'
                            WHEN p.jobpromotion = 'N'   THEN 'Naukri'
                            WHEN p.jobpromotion = 'L'   THEN 'LinkedIn'
                            ELSE ''
            END AS PromotionType
            FROM
            promotion p
            JOIN
            preInterview pr ON p.preInterviewId = pr.id
            JOIN
            aspiration_company ac ON ac.id = pr.company_Id
            WHERE
            p.archiveDate IS NULL
            AND pr.publish = 'Y'
            AND p.jobpromotion NOT IN ('G','I')
            " . $jobPostingCondition . " " . $jobpreId . " " . $jobPromotionSourceCondition . "
            ORDER BY
            pr.id DESC;
            ";

        }

        // echo $query1;

        $queryData = mysqli_query($databaseConnection, $query1);
        $queryResult = mysqli_fetch_all($queryData, MYSQLI_ASSOC);

        foreach ($queryResult as $key => $row) {
            $preId = $row['preId'];

            // Prepare and execute the SQL query
            $sql = "SELECT
                        pr.id,
                        pr.interviewName,
                        pr.interviewExpireDate,
                        rr.name AS roleName,
                        ac.name AS companyName,
                        d.name AS departmentName,
                        sd.name AS subDepartmentName,
                        GROUP_CONCAT(l.cityName ORDER BY l.cityName ASC SEPARATOR ', ') AS currentLocations,
                        MAX(CASE WHEN pp.fieldName = 'currentSalary' THEN pp.fieldValue END) AS currentSalary,
                        MAX(CASE WHEN pp.fieldName = 'workExperience' THEN pp.fieldValue END) AS workExperience
                    FROM
                        preInterview pr
                    INNER JOIN
                        profilePreferences pp ON pr.id = pp.preInterviewId
                    LEFT JOIN role_department_subdepartment rds ON rds.id=pr.roleDepSubDepId   
                    LEFT JOIN departments d ON d.id=rds.departmentId 
                    LEFT JOIN sub_departments sd ON sd.id=rds.subDepId 
                    LEFT JOIN aspiration_company ac ON ac.id = pr.company_id
                    LEFT JOIN relavant_role rr ON rr.id = pr.roleId
                    LEFT JOIN locations l ON FIND_IN_SET(l.id, pp.fieldValue)
                    WHERE
                        pr.id = $preId";

            $result = mysqli_query($databaseConnection, $sql);

            if (mysqli_num_rows($result) > 0) {
                // Fetch the row from the SQL query
                $queryRow = mysqli_fetch_assoc($result);

                // Merge the data into $queryResult
                $queryResult[$key]['roleName'] = $queryRow['roleName'];
                $queryResult[$key]['jobLocations'] = $queryRow['currentLocations'];
                $queryResult[$key]['jobSalary'] = $queryRow['currentSalary'];
                $queryResult[$key]['jobExperience'] = $queryRow['workExperience'];
                $queryResult[$key]['jobExpireDate'] = $queryRow['interviewExpireDate'];
                $queryResult[$key]['departmentName'] = $queryRow['departmentName'];
                $queryResult[$key]['subDepartmentName'] = $queryRow['subDepartmentName'];
            }
        }

        $query2 = "SELECT
        p.id AS id,
        pr.id AS preId,
        p.jobpromotion,
        pr.interviewStartDate,
        pr.interviewName AS JobName,
        ac.name AS CompanyName,
        pr.serviceType,
        p.jobInvitedDate,
        CASE
                WHEN (p.JobPostingStatus='Work in Progress' and p.archiveDate IS NULL) THEN TIMESTAMPDIFF(DAY, p.JobPostingDate, NOW())
                WHEN (p.JobPostingStatus='Closed' and p.archiveDate IS NULL) THEN TIMESTAMPDIFF(DAY, p.JobPostingDate, NOW())
            WHEN p.archiveDate IS NOT NULL THEN p.archiveDate
            ELSE ''
        END AS JobPostingAge,
        p.JobPostingStatus AS JobPostingStatus,
        pr.publish as publish,
        CASE
            WHEN p.jobpromotion = 'S'  and pr.publish='Y' THEN 'Social Media'
            WHEN p.jobpromotion = 'N'  and pr.publish='Y' THEN 'Naukri'
            WHEN p.jobpromotion = 'L'  and pr.publish='Y' THEN 'Linkedin'
            ELSE ''
        END AS PromotionType
        FROM
        promotion p
        JOIN
        preInterview pr ON p.preInterviewId = pr.id
        JOIN
        aspiration_company ac ON ac.id = pr.company_Id
        WHERE
        p.archiveDate IS NULL
        AND pr.publish = 'Y'
        AND p.jobpromotion NOT IN ('G','I')
        ORDER BY
        pr.id DESC;
        ";

        $queryData2 = mysqli_query($databaseConnection, $query2);
        $query2Result = mysqli_fetch_all($queryData2, MYSQLI_ASSOC);

        if (mysqli_num_rows($queryData) > 0) {
            $total_data['data'] = $queryResult;
            // $total_data['count'] = mysqli_num_rows($queryData);
            $total_data['data2'] = $query2Result;
            $total_data['status'] = 1;
            $to_encode = $total_data;
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "in Error while retrieving promotion data."
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'status' => 0,
            'errorCode' => "in Error while retrieving promotion data."
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['insertHeadCountAndTargetResume'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if ($json) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $head = mysqli_real_escape_string($databaseConnection, $json['head']);
        $resume = mysqli_real_escape_string($databaseConnection, $json['resume']);
        $preInterviewId = $json['preInterviewId'];
        // $limit_query = $limit == 0 ? "" : " LIMIT " . $start . "," . $limit;
        // $queryToCheck = "UPDATE `preInterview` set headcount = " .$head .", targetResumeShared=". $resume ." where id= " . $preInterviewId ."";


        if (!isset($json['resume']) || $json['resume'] === null || $json['resume'] === '') {
            $queryToCheck = "UPDATE `preInterview` set iHeadcount = " . $head . " where id= " . $preInterviewId . "";
        } else {
            $queryToCheck = "UPDATE `preInterview` set iHeadcount = " . $head . ", targetResumeShared=" . $resume . " where id= " . $preInterviewId . "";
        }


        // echo $queryToCheck;
        // exit();

        $queryToCheckData = mysqli_query($databaseConnection, $queryToCheck);

        if ($queryToCheckData) {
            $to_encode = array(
                'result' => "success",
                'status' => 1,
                'Code' => "success"
            );
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "in Error while inserting."
            );
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'status' => 0,
            'errorCode' => "in Error while inserting."
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['getRecruiterReportData'])) {
    // this method is added by vijay on 24 May 2023 to fetch the Recruiter Report data
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if ($json) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $filterQry = '';
        $condition = '';
        $values = array();
        $limit = $json['limit'];
        $start = ($json['page'] - 1) * $limit;
        $limit_query = $limit == 0 ? "" : " limit " . $start . "," . $limit;



        if ($json['recruiter'] != '') {
            $condition .= " and isc.recruiterId in (" . implode(',', $json['recruiter']) . ")";

        }

        if ($json['scheduleFrom'] != "" && $json['scheduleTo'] == "") {
            $condition .= " and (date_format(isc.scheduleTime,'%Y-%m-%d')) >= '" . $json['scheduleFrom'] . "'";

        }

        if ($json['scheduleFrom'] == "" && $json['scheduleTo'] != "") {
            $condition .= " and (date_format(isc.scheduleTime,'%Y-%m-%d')) <= '" . $json['scheduleTo'] . "'";
        }

        if ($json['scheduleFrom'] != "" && $json['scheduleTo'] != "") {
            $condition .= " and (date_format(isc.scheduleTime,'%Y-%m-%d')) >= '" . $json['scheduleFrom'] . "' and (date_format(isc.scheduleTime,'%Y-%m-%d')) <= '" . $json['scheduleTo'] . "'";
        }


        if ($userType == 'corporate') {

            $condition .= " and pr.userId=" . $userId . "";
        }


        // $query="select fr.candidateId as candidateId,(select rl.name from recruiterList rl left join users u on u.id=rl.corporateId where rl.id=isc.recruiterId) as recruiterName,isc.recruiterId,pr.id as preInterviewId,pr.interviewName,date_format(pr.interviewStartDate,'%Y-%c-%d') as 'postedOn',group_concat(isc.amplifier) as amplifier,count(distinct(isc.emailId)) as 'totalSchedule',count(distinct(case when (fr.id is not null and (fr.review_status=-4 and fr.reasonOfRejection in ('technicalIssue','incompleteInterview'))) then isc.emailId end )) as 'Rejected',count(distinct(case when (fr.id is not null and fr.review_status=2 ) then isc.emailId end )) as 'Assessed',count(distinct(case when (fr.id is not null and (fr.review_status in (-2,1,0))) then isc.emailId end )) as 'assessmentPending',count(distinct(case when (fr.id is not null and (isc.candidateStatus in('Resume Shared'))) then isc.emailId end )) as 'shared',count(distinct(case when (fr.id is not null and (isc.candidateStatus in('Joined'))) then isc.emailId end )) as 'Joined',count(distinct(case when (fr.id is not null and (isc.candidateStatus in('Offered'))) then isc.emailId end )) as 'Offered',count(distinct(case when (fr.id is not null and (isc.candidateStatus in('Client Shortlisted'))) then isc.emailId end )) as 'clientShortlisted',count(distinct(case when (fr.id is not null and (isc.candidateStatus in('Client Rejected','Not interested','Internal Reject'))) then isc.emailId end )) as 'dropOut',count(distinct(case when (fr.id is not null and (isc.candidateStatus in('RNR') or isc.candidateStatus is null)) then isc.emailId end )) as 'unAttended',count(distinct(case when (fr.id is null and (isc.scheduleTime<now())) then isc.emailId end )) as'totalMissed',count(distinct(case when (fr.id is null and (date_format(scheduleTime,'%Y-%c-%d')=CURDATE() and (isc.scheduleTime<now()))) then isc.emailId end )) as'missedToday',count(distinct(case when (fr.id is null and (DATEDIFF(isc.scheduleTime,now()))=0) then isc.emailId end )) as'scheduledToday',pr.postedBy from interviewSchedule isc inner join preInterview pr on pr.id=isc.preInterviewId left join users u on u.emailId=isc.emailId left join interview i on i.preInterviewId=pr.id and i.createdBy=u.id left join feedback_request fr on fr.interviewId=i.id and fr.candidateId=u.id left join candidate_interview_transection cit on cit.interviewId=i.id left join feedback_report fbr on fbr.feedbackRequestId=fr.id where 1 and isc.emailId is not null and isc.preInterviewId is not null and isc.recruiterId is not null ".$condition . $filterQry." group by isc.preInterviewId,isc.recruiterId order by pr.id desc";

        // $companyId=mysqli_query($databaseConnection,"select distinct(pr.id) as preInterviewId,pr.company_id,CASE When pr.interviewName is null then ac.name else pr.interviewName End as interviewName,pr.hiringCompanies,pr.salaryRage,pr.jobLocation,pr.jdDocument from preInterview pr inner join aspiration_company ac on ac.id=pr.company_id inner join interviewSchedule isc on isc.preInterviewId=pr.id where isc.recruiterId is not null and isc.emailId is not null ".$condition." order by pr.id desc");

        //shrikant changed : 6/3/2024 Client Screen Reject
        // $query="
        // select t3.*,round(((t3.Assessed+t3.assessmentPending+t3.Rejected)*100)/(t3.totalSchedule-t3.scheduledToday),2) as interviewTakers,
        // round((t3.Assessed*100)/(t3.totalSchedule-t3.scheduledToday),2) as assessmentcompletion,round(((t3.clientShortlisted+t3.shared+t3.forshared+t3.Joined)*100)/(t3.totalSchedule-t3.scheduledToday),2) as resumesharedpercent,round(((t3.offered)*100)/(t3.clientShortlisted+t3.shared+t3.forshared+t3.Joined),2) as Offerconversion,round(((t3.joined)*100)/(t3.offered),2) as joiningconversion,round(((t3.totalMissed)*100)/(t3.totalSchedule-t3.scheduledToday),1) as missedconversion,round(((t3.Rejected)*100)/(t3.totalSchedule-t3.scheduledToday),1) as rejectedconversion,round(((t3.assessmentPending)*100)/(t3.totalSchedule-t3.scheduledToday-t3.totalMissed),1) as assessmentconversion,CASE
        //     WHEN totalSchedule = 0 OR work_days = 0 THEN 0
        //     ELSE ROUND(totalSchedule / work_days, 2)
        // END AS avg_rec,(shared+clientShortlisted+dropOut+Offered+Joined) as totalResumeShared from (select (select group_concat(distinct(amplifier)) from interviewSchedule where preInterviewId=t2.preInterviewId and recruiterId=t2.recruiterId) as amplifier,t2.preInterviewId,t2.recruiterId,t2.interviewName,t2.postedOn,count(distinct t2.emailId)as totalSchedule,t2.postedBy,t2.recruiterName, CASE
        // WHEN MAX(t2.scheduleTime) = MIN(t2.scheduleTime) THEN 1
        // ELSE DATEDIFF(MAX(t2.scheduleTime), MIN(t2.scheduleTime))
        // END AS work_days,
        // count(distinct case when t2.futureScheduled is not null then t2.emailId end) as scheduledToday,
        // count(distinct case when t2.totalMissed is not null then t2.emailId end) as totalMissed,
        // count(distinct case when t2.todayMissed is not null then t2.emailId end) as missedToday,
        // count(distinct case when t2.interviewStatus in('Incomplete') then t2.emailId end ) as Rejected,
        // count(distinct case when t2.interviewStatus in('Assessment in Progress') then t2.emailId end) as assessmentPending,
        // count(distinct case when t2.interviewStatus in('Completed') then t2.emailId end) as Assessed,
        // count(distinct case when t2.shared is not null then t2.emailId end) as shared,
        // count(distinct case when t2.Joined is not null then t2.emailId end) as Joined,
        // count(distinct case when t2.Offered is not null then t2.emailId end) as Offered,
        // count(distinct case when t2.clientShortlisted is not null then t2.emailId end) as clientShortlisted,
        // count(distinct case when t2.dropOut is not null then t2.emailId end) as dropOut,
        // count(distinct case when t2.unAttended is not null then t2.emailId end) as unAttended,
        // count(distinct case when t2.forshared is not null then t2.emailId end) as forshared
        //     from (
        //     select t.* from (
        //     select fr.candidateId,fr.id as feedbackRequestId,isc.emailId,isc.scheduleTime,pr.id as preInterviewId,isc.recruiterId,(select rl.name from recruiterList rl left join users u on u.id=rl.corporateId where rl.id=isc.recruiterId) as recruiterName,(select concat(rl.name,'(',u.firstName,')') from recruiterList rl left join users u on u.id=rl.corporateId where rl.id=isc.recruiterId) as recruiter,
        //     case when pr.interviewName is null then (select name from aspiration_company where id=pr.company_id) else pr.interviewName end as interviewName,date_format(pr.interviewStartDate,'%Y-%c-%d') as 'postedOn',
        //     case when (fr.id is not null and (fr.review_status=-4)) then 'Incomplete'  
        //     when (fr.id is not null and cit.completion_status is not null and fr.review_status in (0,1,-2)) then 'Assessment in Progress' 
        //     when (fr.id is not null and cit.completion_status is not null and fr.review_status=2) then 'Completed' 
        //     end as interviewStatus,
        //     case when (fr.id is not null and cit.completion_status is not null and fr.review_status=2) then fr.id end as 'Completed',                    
        //     case when (fr.id is null and (date_format(isc.recruiterScheduleDate,'%Y-%c-%d')=CURDATE())) then isc.emailId end as todaySchedule,   
        //     case when (fr.id is null and isc.scheduleTime>=now()) then isc.emailId end as futureScheduled,       
        //     case when ((fr.id is not null and fr.review_status=2) and (isc.candidateStatus in('Resume Shared'))) then isc.emailId end  as 'shared',
        //     case when ((fr.id is not null and fr.review_status=2) and (isc.candidateStatus in('Joined'))) then isc.emailId end as 'Joined',
        //     case when ((fr.id is not null and fr.review_status=2) and (isc.candidateStatus in('Offered','Offer Drop','Offer Accepted','Joined'))) then isc.emailId end as 'Offered',
        //     case when ((fr.id is not null and fr.review_status=2) and (isc.candidateStatus in('Client Shortlisted'))) then isc.emailId end as 'clientShortlisted', 
        //     case when ((fr.id is not null and fr.review_status=2) and (isc.candidateStatus in('Client Rejected','No Show','Recruiter Reject'))) then isc.emailId end  as 'dropOut',
        //     case when ((fr.id is not null and fr.review_status=2) and (isc.candidateStatus in('Client Rejected','No Show','Offer Drop','Offer Accepted'))) then isc.emailId end  as 'forshared',
        //     case when ((fr.id is not null and fr.review_status=2) and (isc.candidateStatus in('RNR','UnAttended','Not Attended') or isc.candidateStatus is null)) then isc.emailId end  as 'unAttended',case when (fr.id is null and isc.scheduleTime<now()) then isc.emailId end as 'totalMissed',           
        //     case when (fr.id is null and (date_format(isc.scheduleTime,'%Y-%c-%d')=CURDATE() and (isc.scheduleTime<now()))) then isc.emailId end as todayMissed,
        //     pr.postedBy from interviewSchedule isc inner join preInterview pr on pr.id=isc.preInterviewId left join users u on u.emailId=isc.emailId left join interview i on i.preInterviewId=pr.id and i.createdBy=u.id left join feedback_request fr on fr.interviewId=i.id and fr.candidateId=u.id left join candidate_interview_transection cit on cit.interviewId=i.id left join feedback_report fbr on fbr.feedbackRequestId=fr.id where 1 and isc.emailId is not null and isc.recruiterId is not null ".$condition." group by isc.emailId,fr.id desc
        //     ) as t group by t.emailId) as t2 group by t2.recruiter) as t3";

        $query = "
                select t3.*,round(((t3.Assessed+t3.assessmentPending+t3.Rejected)*100)/(t3.totalSchedule-t3.scheduledToday),2) as interviewTakers,
                round((t3.Assessed*100)/(t3.totalSchedule-t3.scheduledToday),2) as assessmentcompletion,round(((t3.clientShortlisted+t3.shared+t3.forshared+t3.Joined)*100)/(t3.totalSchedule-t3.scheduledToday),2) as resumesharedpercent,round(((t3.offered)*100)/(t3.clientShortlisted+t3.shared+t3.forshared+t3.Joined),2) as Offerconversion,round(((t3.joined)*100)/(t3.offered),2) as joiningconversion,round(((t3.totalMissed)*100)/(t3.totalSchedule-t3.scheduledToday),1) as missedconversion,round(((t3.Rejected)*100)/(t3.totalSchedule-t3.scheduledToday),1) as rejectedconversion,round(((t3.assessmentPending)*100)/(t3.totalSchedule-t3.scheduledToday-t3.totalMissed),1) as assessmentconversion,CASE
                    WHEN totalSchedule = 0 OR work_days = 0 THEN 0
                    ELSE ROUND(totalSchedule / work_days, 2)
                END AS avg_rec,(shared+clientShortlisted+dropOut+Offered+Joined) as totalResumeShared from (select (select group_concat(distinct(amplifier)) from interviewSchedule where preInterviewId=t2.preInterviewId and recruiterId=t2.recruiterId) as amplifier,t2.preInterviewId,t2.recruiterId,t2.interviewName,t2.postedOn,count(distinct t2.emailId)as totalSchedule,t2.postedBy,t2.recruiterName, CASE
                WHEN MAX(t2.scheduleTime) = MIN(t2.scheduleTime) THEN 1
                ELSE DATEDIFF(MAX(t2.scheduleTime), MIN(t2.scheduleTime))
                END AS work_days,
                count(distinct case when t2.futureScheduled is not null then t2.emailId end) as scheduledToday,
                count(distinct case when t2.totalMissed is not null then t2.emailId end) as totalMissed,
                count(distinct case when t2.todayMissed is not null then t2.emailId end) as missedToday,
                count(distinct case when t2.interviewStatus in('Incomplete') then t2.emailId end ) as Rejected,
                count(distinct case when t2.interviewStatus in('Assessment in Progress') then t2.emailId end) as assessmentPending,
                count(distinct case when t2.interviewStatus in('Completed') then t2.emailId end) as Assessed,
                count(distinct case when t2.shared is not null then t2.emailId end) as shared,
                count(distinct case when t2.Joined is not null then t2.emailId end) as Joined,
                count(distinct case when t2.Offered is not null then t2.emailId end) as Offered,
                count(distinct case when t2.clientShortlisted is not null then t2.emailId end) as clientShortlisted,
                count(distinct case when t2.dropOut is not null then t2.emailId end) as dropOut,
                count(distinct case when t2.unAttended is not null then t2.emailId end) as unAttended,
                count(distinct case when t2.forshared is not null then t2.emailId end) as forshared
                    from (
                    select t.* from (
                    select fr.candidateId,fr.id as feedbackRequestId,isc.emailId,isc.scheduleTime,pr.id as preInterviewId,isc.recruiterId,(select rl.name from recruiterList rl left join users u on u.id=rl.corporateId where rl.id=isc.recruiterId) as recruiterName,(select concat(rl.name,'(',u.firstName,')') from recruiterList rl left join users u on u.id=rl.corporateId where rl.id=isc.recruiterId) as recruiter,
                    case when pr.interviewName is null then (select name from aspiration_company where id=pr.company_id) else pr.interviewName end as interviewName,date_format(pr.interviewStartDate,'%Y-%c-%d') as 'postedOn',
                    case when (fr.id is not null and (fr.review_status=-4)) then 'Incomplete'  
                    when (fr.id is not null and cit.completion_status is not null and fr.review_status in (0,1,-2)) then 'Assessment in Progress' 
                    when (fr.id is not null and cit.completion_status is not null and fr.review_status=2) then 'Completed' 
                    end as interviewStatus,
                    case when (fr.id is not null and cit.completion_status is not null and fr.review_status=2) then fr.id end as 'Completed',                    
                    case when (fr.id is null and (date_format(isc.recruiterScheduleDate,'%Y-%c-%d')=CURDATE())) then isc.emailId end as todaySchedule,   
                    case when (fr.id is null and isc.scheduleTime>=now()) then isc.emailId end as futureScheduled,       
                    case when ((fr.id is not null and fr.review_status=2) and (isc.candidateStatus in('Resume Shared'))) then isc.emailId end  as 'shared',
                    case when ((fr.id is not null and fr.review_status=2) and (isc.candidateStatus in('Joined'))) then isc.emailId end as 'Joined',
                    case when ((fr.id is not null and fr.review_status=2) and (isc.candidateStatus in('Offered','Offer Drop','Offer Accepted','Joined'))) then isc.emailId end as 'Offered',
                    case when ((fr.id is not null and fr.review_status=2) and (isc.candidateStatus in('Client Shortlisted'))) then isc.emailId end as 'clientShortlisted', 
                    case when ((fr.id is not null and fr.review_status=2) and (isc.candidateStatus in('Client Screen Reject','Client Duplicate Reject','Client Interview Reject','Candidate Withdrawal','No Show','Recruiter Reject'))) then isc.emailId end  as 'dropOut',
                    case when ((fr.id is not null and fr.review_status=2) and (isc.candidateStatus in('Client Screen Reject','Client Duplicate Reject','Client Interview Reject','Candidate Withdrawal','No Show','Offer Drop','Offer Accepted'))) then isc.emailId end  as 'forshared',
                    case when ((fr.id is not null and fr.review_status=2) and (isc.candidateStatus in('RNR','UnAttended','Not Attended') or isc.candidateStatus is null)) then isc.emailId end  as 'unAttended',case when (fr.id is null and isc.scheduleTime<now()) then isc.emailId end as 'totalMissed',           
                    case when (fr.id is null and (date_format(isc.scheduleTime,'%Y-%c-%d')=CURDATE() and (isc.scheduleTime<now()))) then isc.emailId end as todayMissed,
                    pr.postedBy from interviewSchedule isc inner join preInterview pr on pr.id=isc.preInterviewId left join users u on u.emailId=isc.emailId left join interview i on i.preInterviewId=pr.id and i.createdBy=u.id left join feedback_request fr on fr.interviewId=i.id and fr.candidateId=u.id left join candidate_interview_transection cit on cit.interviewId=i.id left join feedback_report fbr on fbr.feedbackRequestId=fr.id where 1 and isc.emailId is not null and isc.recruiterId is not null " . $condition . " group by isc.emailId,fr.id desc
                    ) as t group by t.emailId) as t2 group by t2.recruiter) as t3";



        $queryData = mysqli_query($databaseConnection, $query);
        $queryResult = mysqli_fetch_all($queryData, MYSQLI_ASSOC);
        // array_pop($queryResult);
        // array_push($values,...$queryResult);


        if (mysqli_num_rows($queryData) > 0) {
            $total_data['data'] = $queryResult;
            // $total_data['count'] = mysqli_num_rows($queryData);
            $total_data['status'] = 1;
            $to_encode = $total_data;
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "in Error while retrieving Student information."
            );
        }


    } else {
        $to_encode = array(
            'result' => "error",
            'status' => 0,
            'errorCode' => "in Error while retrieving Student information."
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['getexpertCalculationData'])) {
    // this method is added by arun on 15 May 2023 to fetch the expert Calculation Data
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if ($json) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $filterQry = '';
        $condition = '';
        $values = array();
        $limit = $json['limit'];
        $start = ($json['page'] - 1) * $limit;
        $limit_query = $limit == 0 ? "" : " limit " . $start . "," . $limit;

        if ($json['interview'] != '') {

            $condition .= " and pr.id in ('" . implode("','", $json['interview']) . "')";

        }


        if ($json['subjectId'] != '') {

            $filterQry .= " and q.subjectId in (" . implode(',', $json['subjectId']) . ")";
            $condition .= " and scps.subject in (" . implode(',', $json['subjectId']) . ")";

        }

        if ($json['interviewFromDate'] != "" && $json['interviewToDate'] == "") {
            $condition .= " and (date_format(fr.requestDate,'%Y-%m-%d')) >= '" . $json['interviewFromDate'] . "'";

        }

        if ($json['interviewFromDate'] == "" && $json['interviewToDate'] != "") {
            $condition .= " and (date_format(fr.requestDate,'%Y-%m-%d')) <= '" . $json['interviewToDate'] . "'";
        }

        if ($json['interviewFromDate'] != "" && $json['interviewToDate'] != "") {
            $condition .= " and (date_format(fr.requestDate,'%Y-%m-%d')) >= '" . $json['interviewFromDate'] . "' and (date_format(fr.requestDate,'%Y-%m-%d')) <= '" . $json['interviewToDate'] . "'";
        }


        $companyId = "select pr.id as preInterviewId,case when pr.interviewName is not null then pr.interviewName else (select name from aspiration_company where id=pr.company_id) end as interviewName,
                count(distinct(scps.subject)) as totalSubjects,
                count(distinct(case when fr.id is not null and fr.review_status=-2 then fr.id end)) as 'adminReview',
                count(distinct(case when fr.id is not null and (fr.review_status=-4 and fr.reasonOfRejection in ('technicalIssue','incompleteInterview')) then fr.id end)) as 'interviewIssue',
                count(distinct(case when fr.id is not null and (fr.review_status=-4 and fr.reasonOfRejection in ('duplicateAttempt','unauthorizedUser','limitedFreeAssessment')) then fr.id end)) as 'deadInterviews',
                count(distinct(case when (fr.review_status=2 and TIMESTAMPDIFF(HOUR,fr.requestDate,fr.updatedAt)<=11 )then fr.id end)) as assessmentComplete12,count(distinct(case when (fr.review_status=2 and (TIMESTAMPDIFF(HOUR,fr.requestDate,fr.updatedAt)>11 and TIMESTAMPDIFF(HOUR,fr.requestDate,fr.updatedAt)<=24 ) )then fr.id end)) as assessmentComplete24,
                count(distinct(case when (fr.review_status=2 and TIMESTAMPDIFF(HOUR,fr.requestDate,fr.updatedAt)>24 )then fr.id end)) as assessmentCompleteMore24,
                count(distinct(case when (fr.review_status=1 and TIMESTAMPDIFF(HOUR,fsq.createdAt,now())<=11 )then fr.id end)) as assessmentInprogress12,
                count(distinct(case when (fr.review_status=1 and (TIMESTAMPDIFF(HOUR,fsq.createdAt,now())>11 and TIMESTAMPDIFF(HOUR,fsq.createdAt,now())<=24) )then fr.id end)) as assessmentInprogress24,
                count(distinct(case when (fr.review_status=1 and TIMESTAMPDIFF(HOUR,fsq.createdAt,now())>24 )then fr.id end)) as assessmentInprogressMore24,
                count(distinct(case when (fr.review_status=0 and TIMESTAMPDIFF(HOUR,fr.requestDate,now())<=11 )then fr.id end)) as assessmentOpen12,
                count(distinct(case when (fr.review_status=0 and (TIMESTAMPDIFF(HOUR,fr.requestDate,now())>11 and TIMESTAMPDIFF(HOUR,fr.requestDate,now())<=24 ) )then fr.id end)) as assessmentOpen24,
                count(distinct(case when (fr.review_status=0 and TIMESTAMPDIFF(HOUR,fr.requestDate,now())>24 )then fr.id end)) as assessmentOpenMore24 from feedback_request fr inner join interview i on i.id=fr.interviewId left join feedback_status_question fsq on fsq.feedbackRequestId=fr.id left join preInterview pr on pr.id=i.preInterviewId left join scps_transaction scps on scps.preInterviewId=pr.id where i.preInterviewId is not null and pr.interviewStatus in('Active') " . $condition . " group by pr.id Desc";

        $data = $companyId . $limit_query;

        $companyResult = mysqli_query($databaseConnection, $data);
        $countQuery = mysqli_query($databaseConnection, $companyId);
        if (mysqli_num_rows($companyResult) > 0) {
            while ($row = mysqli_fetch_assoc($companyResult)) {


                // $query="SELECT COUNT(DISTINCT case when fsq.review_status in(0,1) then fsq.id end) as pendingQuestion,".$row['preInterviewId']." as preInterviewId,
                // fs.id as subjectId,CASE WHEN fs.favourite_subject IS NULL THEN 'Others' ELSE fs.favourite_subject END as subjectName, 
                // COUNT(DISTINCT CASE WHEN (p.isAssessmentApproved = 'Y' AND p.expertStatus = 1 AND p.deleted_at IS null AND p.lastActiveOnAssessment IS NOT NULL) THEN p.id END) as noOfWorkingExpert,
                // COUNT(DISTINCT CASE WHEN (p.isAssessmentApproved = 'Y' AND p.expertStatus = 1 AND p.deleted_at IS null AND p.lastActiveOnAssessment IS NOT NULL AND TIMESTAMPDIFF(DAY,lastActiveOnAssessment,now()) <= 15 ) THEN p.id END) as weeklyActiveExperts,
                // COUNT(DISTINCT CASE WHEN (p.expertStatus IN (1)) THEN p.id END) as VerifiedExperts,
                // COUNT(DISTINCT CASE WHEN (p.expertStatus = 0) THEN p.id END) as unVerifiedExpert,
                // count(distinct(case when (fsq.review_status=0 and (TIME_FORMAT(TIMEDIFF(now(),fsq.createdAt),'%H'))<=11 )then fsq.feedbackRequestId end)) as assessmentOpen12,
                // count(distinct(case when (fsq.review_status=0 and ((TIME_FORMAT(TIMEDIFF(now(),fsq.createdAt),'%H'))>11 and (TIME_FORMAT(TIMEDIFF(now(),fsq.createdAt),'%H'))<=24 ) )then fsq.feedbackRequestId end)) as assessmentOpen24,
                // count(distinct(case when (fsq.review_status=0 and (TIME_FORMAT(TIMEDIFF(now(),fsq.createdAt),'%H'))>24 )then fsq.feedbackRequestId end)) as assessmentOpenMore24,
                // count(distinct(case when (fsq.review_status=1 and (TIME_FORMAT(TIMEDIFF(now(),fsq.createdAt),'%H'))<=11 )then fsq.feedbackRequestId end)) as assessmentInprogress12,
                // count(distinct(case when (fsq.review_status=1 and ((TIME_FORMAT(TIMEDIFF(now(),fsq.createdAt),'%H'))>11 and (TIME_FORMAT(TIMEDIFF(now(),fsq.createdAt),'%H'))<=24 ) )then fsq.feedbackRequestId end)) as assessmentInprogress24,
                // count(distinct(case when (fsq.review_status=1 and (TIME_FORMAT(TIMEDIFF(now(),fsq.createdAt),'%H'))>24)then fsq.feedbackRequestId end)) as assessmentInprogressMore24,
                // count(distinct(case when (fsq.review_status=2 and (TIME_FORMAT(TIMEDIFF(now(),fr.updatedAt),'%H'))<=11 )then fr.id end)) as assessmentComplete12,
                // count(distinct(case when (fsq.review_status=2 and (TIME_FORMAT(TIMEDIFF(now(),fr.updatedAt),'%H'))>11 and (TIME_FORMAT(TIMEDIFF(now(),fr.updatedAt),'%H'))<=24 ) then fr.id end)) as assessmentComplete24,
                // count(distinct(case when (fsq.review_status=2 and (TIME_FORMAT(TIMEDIFF(now(),fr.updatedAt),'%H'))>24 )then fr.id end)) as assessmentCompletedMore24
                // FROM feedback_status_question fsq INNER JOIN questions q ON q.id = fsq.questionId LEFT JOIN favourite_subject fs ON fs.id = q.subjectId LEFT JOIN panel p ON FIND_IN_SET(q.subjectId,p.areaOfExpertiseId) left join feedback_request fr on fr.id=fsq.feedbackRequestId left join interview i on i.id=fr.interviewId left join preInterview pr on i.preInterviewId=pr.id WHERE pr.id=".$row['preInterviewId'] . $filterQry." GROUP BY q.subjectId  ORDER BY fs.favourite_subject ASC";

                $query = "select t.*,(t.assessmentOpen12+t.assessmentOpen24+t.assessmentOpenMore24+t.assessmentInprogress12+t.assessmentInprogress24+t.assessmentInprogressMore24+t.assessmentComplete12+t.assessmentComplete24+t.assessmentCompletedMore24) as totalQuestionsAttempted,0 as pipeLineQuestions from (SELECT
                    COUNT(Distinct case when fr.review_status=-2 then mv.questionId  end) as questionLoad," . $row['preInterviewId'] . " as preInterviewId,
                    fs.id as subjectId,CASE WHEN fs.favourite_subject IS NULL THEN 'Others' ELSE fs.favourite_subject END as subjectName, 
                    COUNT(DISTINCT CASE WHEN (p.isAssessmentApproved = 'Y' AND p.expertStatus = 1 AND p.deleted_at IS null AND p.lastActiveOnAssessment IS NOT NULL) THEN p.id END) as noOfWorkingExpert,
                    COUNT(DISTINCT CASE WHEN (p.isAssessmentApproved = 'Y' AND p.expertStatus = 1 AND p.deleted_at IS null AND p.lastActiveOnAssessment IS NOT NULL AND TIMESTAMPDIFF(DAY,lastActiveOnAssessment,now()) <= 15 ) THEN p.id END) as weeklyActiveExperts,
                    COUNT(DISTINCT CASE WHEN (p.expertStatus IN (1) AND p.deleted_at IS null) THEN p.id END) as VerifiedExperts,
                    COUNT(DISTINCT CASE WHEN (p.expertStatus = 0) THEN p.id END) as unVerifiedExpert,

                    count(distinct(case when (fsq.review_status=0 and TIMESTAMPDIFF(HOUR,fr.requestDate,now())<=11 )then mv.questionId end)) as assessmentOpen12,

                    count(distinct(case when (fsq.review_status=0 and (TIMESTAMPDIFF(HOUR,fr.requestDate,now())>11 and TIMESTAMPDIFF(HOUR,fr.requestDate,now())<=24 ) )then mv.questionId end)) as assessmentOpen24,

                    count(distinct(case when (fsq.review_status=0 and TIMESTAMPDIFF(HOUR,fr.requestDate,now())>24 )then mv.questionId end)) as assessmentOpenMore24,

                    count(distinct(case when (fsq.review_status=1 and TIMESTAMPDIFF(HOUR,fsq.createdAt,now())<=11 )then mv.questionId end)) as assessmentInprogress12,

                    count(distinct(case when (fsq.review_status=1 and (TIMESTAMPDIFF(HOUR,fsq.createdAt,now())>11 and TIMESTAMPDIFF(HOUR,fsq.createdAt,now())<=24 ) )then mv.questionId end)) as assessmentInprogress24,

                    count(distinct(case when (fsq.review_status=1 and TIMESTAMPDIFF(HOUR,fsq.createdAt,now())>24)then mv.questionId end)) as assessmentInprogressMore24,

                    count(distinct(case when (fsq.review_status=2 and TIMESTAMPDIFF(HOUR,fr.requestDate,fr.updatedAt)<=11 and fr.review_status!=-4 )then mv.questionId end)) as assessmentComplete12,

                    count(distinct(case when (fsq.review_status=2 and (TIMESTAMPDIFF(HOUR,fr.requestDate,fr.updatedAt)>11 and TIMESTAMPDIFF(HOUR,fr.requestDate,fr.updatedAt)<=24 ) and fr.review_status!=-4) then mv.questionId end)) as assessmentComplete24,

                    count(distinct(case when (fsq.review_status=2 and TIMESTAMPDIFF(HOUR,fr.requestDate,fr.updatedAt)>24 and fr.review_status!=-4 )then mv.questionId end)) as assessmentCompletedMore24

                    FROM feedback_request fr inner join  mergedVideos mv on mv.interviewSessionId=fr.interviewSessionId inner join interview i on i.id=mv.interviewId left join feedback_status_question fsq on fsq.feedbackRequestId=fr.id left join questions q on q.id=mv.questionId  left join favourite_subject fs on fs.id=q.subjectId left join panel p ON FIND_IN_SET(q.subjectId,p.areaOfExpertiseId) where i.preInterviewId=" . $row['preInterviewId'] . $filterQry . " group by fs.id order by fs.favourite_subject ASC) as t";

                $queryData = mysqli_query($databaseConnection, $query);
                $queryResult = mysqli_fetch_all($queryData, MYSQLI_ASSOC);
                if (mysqli_num_rows($queryData) > 0) {
                    $row['details'] = $queryResult;
                } else {
                    $row['details'] = [];
                }

                // $pipeLineCount=mysqli_query($databaseConnection,"select count(distinct ivs.emailId) as pipeline from interviewSchedule ivs left join users u on u.emailId=ivs.emailId where ivs.emailId is not null and u.id not in(select i.createdBy from interview i inner join feedback_request fr on fr.interviewId=i.id and fr.candidateId=i.createdBy where i.companyId is not null and i.preInterviewId is not null and i.preInterviewId=".$row['preInterviewId'].") and ivs.preInterviewId=".$row['preInterviewId'] ."");

                $pipeLineCount = mysqli_query($databaseConnection, "select count(distinct isc.emailId) as pipeline from interviewSchedule isc where isc.preInterviewId=" . $row['preInterviewId'] . " and isc.emailId is not null");

                $row['pipeLine'] = mysqli_fetch_assoc($pipeLineCount)['pipeline'];

                array_push($values, $row);

            }

            $total_data['data'] = $values;
            $total_data['status'] = 1;
            $total_data['count'] = mysqli_num_rows($countQuery);
            $to_encode = $total_data;


        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "in Error while retrieving Student information."
            );
        }


    } else {
        $to_encode = array(
            'result' => "error",
            'status' => 0,
            'errorCode' => "in Error while retrieving Student information."
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['getProfileSummaryData'])) {
    // this method is added by arun on 14 Apr 2024 to fetch the profile Summary Report data
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if ($json) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $filterQry = '';
        $having_query = '';
        $having_query1 = '';
        $having_query2 = '';
        $having_query3 = '';
        $condition = '';
        $values = array();
        $experience = array();
        $noticePeriod = array();
        $salaryRange = array();
        if ($userType == 'corporate') {

            $filterQry .= " and pr.userId=" . $userId . "";
        }

        if ($json['roleId'] != '') {

            $filterQry .= " and scps.position in (" . implode(',', $json['roleId']) . ")";
        }

        if ($json['workExperience'] != '') {
            if ($json['workExperience'] != '' && in_array("Fresher", $json['workExperience'])) {
                array_push($experience, "'Fresher'");
            }

            if ($json['workExperience'] != '' && in_array("0-3 Years", $json['workExperience'])) {

                array_push($experience, "'1 Yr','2 Yrs','0 Yr'");

            }

            if ($json['workExperience'] != '' && in_array("3-6 Years", $json['workExperience'])) {

                array_push($experience, "'3 Yrs','4 Yrs','5 Yrs'");

            }

            if ($json['workExperience'] != '' && in_array("6+ Years", $json['workExperience'])) {

                array_push($experience, "'6 Yrs','7 Yrs','8 Yrs','9 Yrs','10+ Yrs'");
            }

            $filterQry .= " and pd.workExperience in (" . implode(',', $experience) . ")";

        }

        if ($json['notice_Period'] != '') {
            if ($json['notice_Period'] != '' && in_array("15 Days or Less", $json['notice_Period'])) {
                array_push($noticePeriod, "'15 Days or Less'");
            }

            if ($json['notice_Period'] != '' && in_array("30 Days", $json['notice_Period'])) {

                array_push($noticePeriod, "'1 Month','30 Days'");

            }

            if ($json['notice_Period'] != '' && in_array("45 Days", $json['notice_Period'])) {

                array_push($noticePeriod, "'45 Days'");

            }

            if ($json['notice_Period'] != '' && in_array("60 Days", $json['notice_Period'])) {

                array_push($noticePeriod, "'2 Months','60 Days'");
            }

            if ($json['notice_Period'] != '' && in_array("90 Days", $json['notice_Period'])) {

                array_push($noticePeriod, "'3 Months','90 Days'");
            }

            if ($json['notice_Period'] != '' && in_array("More than 90 Days", $json['notice_Period'])) {

                array_push($noticePeriod, "'More than 3 Months'");
            }

            if ($json['notice_Period'] != '' && in_array("Immediate", $json['notice_Period'])) {

                array_push($noticePeriod, "'Immediate','Serving Notice Period','Pursuing UG/PG'");
            }

            $filterQry .= " and pd.noticePeriod in (" . implode(',', $noticePeriod) . ")";

        }


        if ($json['salary'] != '' && in_array("0-5 LPA", $json['salary'])) {
            $filterQry .= " and pd.salary between '0' and '4,99,999'";
        }

        if ($json['salary'] != '' && in_array("5-10 LPA", $json['salary'])) {

            $filterQry .= " and pd.salary between '5,00,000' and '9,99,999'";

        }

        if ($json['salary'] != '' && in_array("10-15 LPA", $json['salary'])) {

            $filterQry .= " and pd.salary between '10,00,000' and '14,99,999'";

        }

        if ($json['salary'] != '' && in_array("15+ LPA", $json['salary'])) {

            $filterQry .= " and pd.salary between '15,00,000' and '100,00,000'";
        }


        if ($json['currentLocation'] != '') {

            $filterQry .= " and pd.currentLocation in (" . implode(',', $json['currentLocation']) . ")";
        }

        if ($json['genderType'] != '') {

            $filterQry .= " and u.gender in ('" . implode("','", $json['genderType']) . "')";
        }

        if ($json['workType'] != '') {

            $filterQry .= " and pd.workLocationPreference in ('" . implode("','", $json['workType']) . "')";
        }

        if ($json['subject1'] != '') {

            $having_query1 .= " and FIND_IN_SET ('" . implode("','", $json['subject1']) . "',skillsIds)";
        }

        if ($json['subject2'] != '') {

            $having_query2 .= " and FIND_IN_SET ('" . implode("','", $json['subject2']) . "',skillsIds)";
        }

        if ($json['subject3'] != '') {

            $having_query3 .= " and FIND_IN_SET ('" . implode("','", $json['subject3']) . "',skillsIds)";
        }


        $query = "SELECT
          cp.*,
          GROUP_CONCAT(DISTINCT s.id) AS skillsIds
      FROM
          (
          SELECT
              rr.name AS role,
              rr.id AS roleId,
              COUNT(
                  DISTINCT(
                      isc.candidate_id
                  )
              ) AS totalcandidates,
              COUNT(
                  DISTINCT CASE WHEN(
                      isc.noticePeriod  IS NOT NULL AND  isc.noticePeriod  IN('15 Days or less')
                  ) THEN isc.candidate_id
              END
      ) AS 'notice15days',
      COUNT(
          DISTINCT CASE WHEN(
               isc.noticePeriod IS NOT NULL AND  isc.noticePeriod IN('1 Month', '30 Days')
          ) THEN isc.candidate_id
      END
      ) AS 'notice30days',
      COUNT(
          DISTINCT CASE WHEN(
              isc.noticePeriod  IS NOT NULL AND  isc.noticePeriod  IN('2 Months', '60 Days')
          ) THEN isc.candidate_id
      END
      ) AS 'notice60days',
      COUNT(
          DISTINCT CASE WHEN(
              isc.noticePeriod IS NOT NULL AND  isc.noticePeriod  IN('3 Months', '90 Days')
          ) THEN isc.candidate_id
      END
      ) AS 'notice90days',
      COUNT(
          DISTINCT CASE WHEN(
               isc.noticePeriod IS NOT NULL AND  isc.noticePeriod IN('45 Days')
          ) THEN isc.candidate_id
      END
      ) AS 'notice45days',
      COUNT(
          DISTINCT CASE WHEN(
              isc.noticePeriod IS NOT NULL AND  isc.noticePeriod IN(
                  'Immediate',
                  'Serving Notice Period',
                  'Pursuing UG/PG',
                  ''
              )
          ) THEN isc.candidate_id
      END
      ) AS 'noticeImmediate',
      COUNT(
          DISTINCT CASE WHEN(
              isc.noticePeriod IS NOT NULL AND isc.noticePeriod IN('More than 3 Months')
          ) THEN isc.candidate_id
      END
      ) AS 'noticeMorethan3',
      COUNT(
          DISTINCT CASE WHEN(
              isc.currentSalary IS NOT NULL AND isc.currentSalary BETWEEN '0' AND '4,99,999'
          ) THEN isc.candidate_id
      END
      ) AS 'salary5LPA',
      COUNT(
          DISTINCT CASE WHEN(
              isc.currentSalary IS NOT NULL AND isc.currentSalary BETWEEN '5,00,000' AND '9,99,999'
          ) THEN isc.candidate_id
      END
      ) AS 'salary10LPA',
      COUNT(
          DISTINCT CASE WHEN(
              isc.currentSalary IS NOT NULL AND isc.currentSalary BETWEEN '10,00,000' AND '14,99,999'
          ) THEN isc.candidate_id
      END
      ) AS 'salary15LPA',
      COUNT(
          DISTINCT CASE WHEN(
              isc.currentSalary IS NOT NULL AND isc.currentSalary BETWEEN '15,00,000' AND '100,00,000'
          ) THEN isc.candidate_id
      END
      ) AS 'salarymorethan15',
      COUNT(
          DISTINCT CASE WHEN(
              isc.workExperience IS NOT NULL AND isc.workExperience IN('Fresher')
          ) THEN isc.candidate_id
      END
      ) AS 'workExperienceFresher',
      COUNT(
          DISTINCT CASE WHEN(
              isc.workExperience IS NOT NULL AND isc.workExperience IN('1 Yr', '2 Yrs', '0 Yr')
          ) THEN isc.candidate_id
      END
      ) AS 'workExperience0To3',
      COUNT(
          DISTINCT CASE WHEN(
              isc.workExperience IS NOT NULL AND isc.workExperience IN('3 Yrs', '4 Yrs', '5 Yrs')
          ) THEN 
          isc.candidate_id
      END
      ) AS 'workExperience3To6',
      COUNT(
          DISTINCT CASE WHEN(
              isc.workExperience IS NOT NULL AND isc.workExperience IN(
                  '6 Yrs',
                  '7 Yrs',
                  '8 Yrs',
                  '9 Yrs',
                  '10+ Yrs'
              )
          ) THEN 
              isc.candidate_id
             
      END
      ) AS 'workExperiencemore6',
      (
          SELECT
              GROUP_CONCAT(DISTINCT(q.subjectId))
          FROM
              feedback_status_question fsq
          INNER JOIN questions q ON
              q.id = fsq.questionId
          WHERE
              fsq.feedbackRequestId = fr.id
      ) AS subjectIds,
      RemoveNumbers( REPLACE
        (
        REPLACE
            (
            REPLACE
                (
                REPLACE
                    (
                         GROUP_CONCAT(isc.skillValues),
                        'Beginner,',
                        ''
                    ),
                    'Intermediate,',
                    ''
            ),
            'Expert,',
            ''
        ),
        ';',
        ''
    ) )  AS skillsset
      
      FROM
          interviewSchedule isc 
      LEFT JOIN feedback_request fr ON
         isc.candidate_id = fr.candidateId  
      LEFT JOIN interview i ON
          i.id = fr.interviewId AND i.createdBy = fr.candidateId
      LEFT JOIN preInterview pr ON
          pr.id = i.preInterviewId
      LEFT JOIN scps_transaction scps ON
          scps.preInterviewId = pr.id
      LEFT JOIN relavant_role rr ON
          rr.id = scps.position
      WHERE
          fr.review_status = 2 AND rr.id IS NOT NULL AND isc.currentSalary IS NOT NULL AND isc.noticePeriod IS NOT NULL AND isc.workExperience IS NOT NULL
      GROUP BY
          rr.id
      
      union 
               
      
       SELECT
              rr.name AS role,
              rr.id AS roleId,
              COUNT(
                  DISTINCT(
                    pd.candidateId
                  )
              ) AS totalcandidates,
              COUNT(
                  DISTINCT CASE WHEN(
                      pd.noticePeriod  IS NOT NULL AND  pd.noticePeriod IN('15 Days or less')
                  ) THEN pd.candidateId
              END
      ) AS 'notice15days',
      COUNT(
          DISTINCT CASE WHEN(
              pd.noticePeriod IS NOT NULL AND  pd.noticePeriod IN('1 Month', '30 Days')
          ) THEN pd.candidateId
      END
      ) AS 'notice30days',
      COUNT(
          DISTINCT CASE WHEN(
              pd.noticePeriod IS NOT NULL AND  pd.noticePeriod IN('2 Months', '60 Days')
          ) THEN pd.candidateId
      END
      ) AS 'notice60days',
      COUNT(
          DISTINCT CASE WHEN(
              pd.noticePeriod IS NOT NULL AND  pd.noticePeriod IN('3 Months', '90 Days')
          ) THEN pd.candidateId
      END
      ) AS 'notice90days',
      COUNT(
          DISTINCT CASE WHEN(
              pd.noticePeriod IS NOT NULL AND  pd.noticePeriod IN('45 Days')
          ) THEN pd.candidateId
      END
      ) AS 'notice45days',
      COUNT(
          DISTINCT CASE WHEN(
              pd.noticePeriod IS NOT NULL AND  pd.noticePeriod IN(
                  'Immediate',
                  'Serving Notice Period',
                  'Pursuing UG/PG',
                  ''
              )
          ) THEN pd.candidateId
      END
      ) AS 'noticeImmediate',
      COUNT(
          DISTINCT CASE WHEN(
               pd.noticePeriod IS NOT NULL AND  pd.noticePeriod IN('More than 3 Months')
          ) THEN  pd.candidateId
      END
      ) AS 'noticeMorethan3',
      COUNT(
          DISTINCT CASE WHEN(
              pd.salary IS NOT NULL AND pd.salary BETWEEN '0' AND '4,99,999'
          ) THEN pd.candidateId
      END
      ) AS 'salary5LPA',
      COUNT(
          DISTINCT CASE WHEN(
              pd.salary IS NOT NULL AND pd.salary BETWEEN '5,00,000' AND '9,99,999'
          ) THEN pd.candidateId
      END
      ) AS 'salary10LPA',
      COUNT(
          DISTINCT CASE WHEN(
              pd.salary IS NOT NULL AND pd.salary BETWEEN '10,00,000' AND '14,99,999'
          ) THEN pd.candidateId
      END
      ) AS 'salary15LPA',
      COUNT(
          DISTINCT CASE WHEN(
              pd.salary IS NOT NULL AND pd.salary BETWEEN '15,00,000' AND '100,00,000'
          ) THEN pd.candidateId
      END
      ) AS 'salarymorethan15',
      COUNT(
          DISTINCT CASE WHEN(
              pd.workExperience IS NOT NULL AND pd.workExperience IN('Fresher')
          ) THEN pd.candidateId
      END
      ) AS 'workExperienceFresher',
      COUNT(
          DISTINCT CASE WHEN(
              pd.workExperience IS NOT NULL AND pd.workExperience IN('1 Yr', '2 Yrs', '0 Yr')
          ) THEN pd.candidateId
      END
      ) AS 'workExperience0To3',
      COUNT(
          DISTINCT CASE WHEN(
              pd.workExperience IS NOT NULL AND pd.workExperience IN('3 Yrs', '4 Yrs', '5 Yrs')
          ) THEN pd.candidateId
      END
      ) AS 'workExperience3To6',
      COUNT(
          DISTINCT CASE WHEN(
              pd.workExperience IS NOT NULL AND pd.workExperience IN(
                  '6 Yrs',
                  '7 Yrs',
                  '8 Yrs',
                  '9 Yrs',
                  '10+ Yrs'
              )
          ) THEN pd.candidateId
      END
      ) AS 'workExperiencemore6',
      (
          SELECT
              GROUP_CONCAT(DISTINCT(q.subjectId))
          FROM
              feedback_status_question fsq
          INNER JOIN questions q ON
              q.id = fsq.questionId
          WHERE
              fsq.feedbackRequestId = fr.id
      ) AS subjectIds,
      RemoveNumbers (REPLACE
        (
        REPLACE
            (
            REPLACE
                (
                REPLACE
                    (
                         GROUP_CONCAT(pd.skills),
                        'Beginner,',
                        ''
                    ),
                    'Intermediate,',
                    ''
            ),
            'Expert,',
            ''
        ),
        ';',
        ''
    ) )
    AS skillsset
      FROM
          users u
      LEFT JOIN professionaldetails pd ON
          u.id = pd.candidateId
      LEFT JOIN feedback_request fr ON
          fr.candidateId = pd.candidateId
      LEFT JOIN interview i ON
          i.id = fr.interviewId AND i.createdBy = fr.candidateId
      LEFT JOIN preInterview pr ON
          pr.id = i.preInterviewId
      LEFT JOIN scps_transaction scps ON
          scps.preInterviewId = pr.id
      LEFT JOIN relavant_role rr ON
          rr.id = scps.position
      WHERE
          fr.review_status = 2 AND rr.id IS NOT NULL AND pd.salary IS NOT NULL AND pd.noticePeriod IS NOT NULL AND pd.workExperience IS NOT NULL  " . $filterQry . "
      GROUP BY
          rr.id
      
      ) AS cp
      LEFT JOIN skills s ON
          FIND_IN_SET(s.skillName, cp.skillsset)
      GROUP BY
          cp.roleid,
          cp.skillsset
      HAVING
          1 " . $having_query1 . " " . $having_query2 . " " . $having_query3 . ""
        ;
        //echo $query;
        $queryData = mysqli_query($databaseConnection, $query);
        $data = mysqli_fetch_all($queryData, MYSQLI_ASSOC);
        if (mysqli_num_rows($queryData) > 0) {
            $total_data['data'] = $data;
            $total_data['status'] = 1;
            $to_encode = $total_data;
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "in Error while retrieving Student information."
            );
        }


    } else {
        $to_encode = array(
            'result' => "error",
            'status' => 0,
            'errorCode' => "in Error while retrieving Student information."
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['getrescheduleInterviewDetails'])) {
    // this method is added by arun on 10 Feb 2023 to re-schedule interview
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if ($json) {
        $companyId = $json['companyId'];
        $userId = $json['userId'];
        $interviewDatetime = $json['interviewDatetime'];
        $currenturl = $json['currenturl'];
        $sectorId = $json['sectorId'];
        $candidateName = "";
        $candidateMobileNumber = "";
        $candidateEmailId = "";
        $preInterviewId = $json['preInterviewId'];

        $candidateDetails = mysqli_query($databaseConnection, "select * from users where id=" . $userId . "");

        while ($data = mysqli_fetch_assoc($candidateDetails)) {
            $candidateName = $data['firstName'];
            $candidateMobileNumber = $data['mobileNumber'];
            $candidateEmailId = $data['emailId'];
        }



        // AND interviewId IS NULL 
        $queryToCheck = "SELECT * FROM `interviewSchedule` WHERE `preInterviewId` = " . $preInterviewId . " AND `emailId` = '" . $candidateEmailId . "' order by id desc";
        $queryToCheckData = mysqli_query($databaseConnection, $queryToCheck);
        if (mysqli_num_rows($queryToCheckData) > 0) {

            $row = mysqli_fetch_assoc($queryToCheckData);
            if (empty($row['interviewId'])) {

                $queryToUpdate = "UPDATE `interviewSchedule` SET `scheduleTime`='" . $interviewDatetime . "',`emailed`='N',`scheduleFlag`='N',`reminderScheduled`='N',`reminderWPScheduled`='N' WHERE `preInterviewId` = " . $preInterviewId . " AND `emailId` = '" . $candidateEmailId . "' AND interviewId IS NULL ";
                $queryToUpdateData = mysqli_query($databaseConnection, $queryToUpdate);
                if ($queryToUpdateData) {

                    $to_encode = array(
                        'status' => 1,
                        'data' => 'Update Success'
                    );
                } else {
                    $to_encode = array(
                        'status' => -1,
                        'data' => 'Error While Update' . mysqli_error($databaseConnection)
                    );
                }
            } else {
                // modify or remove colums from previous schedule
                $newrow = array();
                $newrow['preInterviewId'] = $row['preInterviewId'];
                $newrow['company_id'] = $row['company_id'];
                $newrow['candidate_id'] = $row['candidate_id'];
                $newrow['url'] = $row['url'];
                $newrow['sectorId'] = $row['sectorId'];
                $newrow['currentCompany'] = $row['currentCompany'];
                $newrow['promotionSource'] = $row['promotionSource'];
                $newrow['workExperience'] = $row['workExperience'];
                $newrow['currentSalary'] = $row['currentSalary'];
                $newrow['expectedSalary'] = $row['expectedSalary'];
                $newrow['noticePeriod'] = $row['noticePeriod'];
                $newrow['currentLocation'] = $row['currentLocation'];
                $newrow['candidateName'] = $row['candidateName'];
                $newrow['emailId'] = $row['emailId'];
                $newrow['mobileNumber'] = $row['mobileNumber'];
                $newrow['scheduleTime'] = $interviewDatetime;
                $newrow['emailed'] = 'N';
                $newrow['scheduleFlag'] = 'N';
                $newrow['reminderScheduled'] = 'N';
                $newrow['reminderWPScheduled'] = 'N';
                $newrow['candidateStatus'] = 'Interview Scheduled';
                $newrow['firstScheduleDate'] = $interviewDatetime;

                $newrow['preferredrole'] = $row['preferredrole'];
                $newrow['resume'] = $row['resume'];
                $newrow['apmStatus'] = $row['apmStatus'];
                $newrow['apm'] = $row['apm'];
                $newrow['employmentStatus'] = $row['employmentStatus'];
                $newrow['apmDate'] = $row['apmDate'];
                $newrow['submissionFlag'] = $row['submissionFlag'];
                $newrow['apmStatusMessage'] = $row['apmStatusMessage'];


                // unset($row['id']);
                // unset($row['interviewId']);

                // dynamic insert with values from previous schedule
                // $insertColumns = implode(", ", array_keys($newrow));
                // $insertValues = implode(", ", array_map(function($value) use ($databaseConnection) {
                //     return "'" . mysqli_real_escape_string($databaseConnection, $value) . "'";
                // }, $newrow));

                // $queryToInsert = "INSERT INTO `interviewSchedule` ($insertColumns) VALUES ($insertValues)";

                // Initialize arrays for column names and values
                $columns = [];
                $values = [];

                // Process each column
                foreach ($newrow as $key => $value) {
                    // Skip empty values and NULL values (if needed)
                    if ($value !== "" && $value !== null) {
                        // Escape the value to prevent SQL injection
                        $escapedValue = mysqli_real_escape_string($databaseConnection, $value);
                        // Quote the value if it's not numeric
                        $quotedValue = is_numeric($value) ? $escapedValue : "'" . $escapedValue . "'";
                        // Add column name and value to arrays
                        $columns[] = "`$key`";
                        $values[] = $quotedValue;
                    }
                }

                // Convert arrays to strings
                $columnsString = implode(", ", $columns);
                $valuesString = implode(", ", $values);

                // Prepare the INSERT query with the modified values
                $queryToInsert = "INSERT INTO `interviewSchedule` ($columnsString) VALUES ($valuesString)";

                // var_dump($queryToInsert);

                $queryToInsertData = mysqli_query($databaseConnection, $queryToInsert);
                if ($queryToInsertData) {
                    $to_encode = array(
                        'status' => 1,
                        'data' => 'Insert Success'
                    );
                } else {
                    $to_encode = array(
                        'status' => -1,
                        'data' => 'Error While Insert'
                    );
                }
                mysqli_close($databaseConnection);

            }
        } else {
            $queryToInsert = "INSERT INTO `interviewSchedule`(`company_id`,`candidate_id`,`url`,`scheduleTime`,`sectorId`,`candidateName`,`emailId`,`mobileNumber`,`preInterviewId`,`firstScheduleDate`,`recruiterId`) VALUES (" . $companyId . "," . $userId . ",'" . $currenturl . "','" . $interviewDatetime . "'," . $sectorId . ",'" . $candidateName . "','" . $candidateEmailId . "'," . $candidateMobileNumber . ",'" . $preInterviewId . "','" . $interviewDatetime . "','18')";

            // var_dump($queryToInsert);

            $queryToInsertData = mysqli_query($databaseConnection, $queryToInsert);
            if ($queryToInsertData) {
                $to_encode = array(
                    'status' => 1,
                    'data' => 'Insert Success'
                );
            } else {
                $to_encode = array(
                    'status' => -1,
                    'data' => 'Error While Insert'
                );
            }
            mysqli_close($databaseConnection);

        }
    }
    echo json_encode($to_encode);
} else if (isset($_GET['candidateInterviewSchedule'])) {
    // this method is added by arun on 10 Feb 2023 to schedule interview
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    // var_dump($json);
    // exit;
    if ($json) {
        $companyId = $json['companyId'];
        $userId = $json['userId'];
        $currenturl = $json['currenturl'];
        $sectorId = $json['sectorId'];
        $preInterviewId = $json['preInterviewId'];
        $interviewId = $json['interviewId'];

        $candidateName = "";
        $candidateMobileNumber = "";
        $candidateEmailId = "";

        $jobType = "";
        $currentCompany = "";
        $workExperence = "";
        $currentSalary = "";
        $expectedSalary = "";
        $noticePeriod = "";
        $workLocationPreference = "";
        $timeToCall = "";
        $currentLocation = "";
        $preferredWorkLocation = "";
        $languages = "";
        $skillValues = "";
        $preferredrole = "";
        $certiValues = "";
        $avgTenure = "";
        $resume = "";

        $candidateDetails = mysqli_query($databaseConnection, "select * from users where id=" . $userId . "");

        while ($data = mysqli_fetch_assoc($candidateDetails)) {
            $candidateName = $data['firstName'];
            $candidateMobileNumber = $data['mobileNumber'];
            $candidateEmailId = $data['emailId'];
        }

        $professionalDetails = mysqli_query($databaseConnection, "select * from professionaldetails where candidateId=" . $userId . "");

        while ($data = mysqli_fetch_assoc($professionalDetails)) {

            $jobType = $data['jobType'];
            $currentCompany = $data['currentCompany'];
            $workExperience = $data['workExperience'];
            $salary = $data['salary'];
            $expectedSalary = $data['expectedSalary'];
            $noticePeriod = $data['noticePeriod'];
            $workLocationPreference = $data['workLocationPreference'];
            $timeToCall = $data['timeToCall'];
            $currentLocation = $data['currentLocation'];
            $preferredWorkLocation = $data['preferredWorkLocation'];
            $languages = $data['languages'];
            $skills = $data['skills'];
            $preferredRole = $data['preferredRole'];
            $certifications = $data['certifications'];
            $avgTenure = $data['avgTenure'];
            $resume = $data['resume'];
        }

        $queryToCheck = "SELECT * FROM `interviewSchedule` WHERE `preInterviewId` = " . $preInterviewId . " AND `emailId` = '" . $candidateEmailId . "' AND interviewId IS NULL ";
        $queryToCheckData = mysqli_query($databaseConnection, $queryToCheck);
        if (mysqli_num_rows($queryToCheckData) == 0) {

            // $queryToInsert = "INSERT INTO `interviewSchedule`(`company_id`,`candidate_id`,`url`,`scheduleTime`,`sectorId`,`candidateName`,`emailId`,`mobileNumber`,`recruiterId`,`preInterviewId`,`firstScheduleDate`,`interviewId`) VALUES (".$companyId.",".$userId.",'".$currenturl."',now(),".$sectorId.",'".$candidateName."','".$candidateEmailId."',".$candidateMobileNumber.",(select id from recruiterList where name ='Goprac' and corporateId=4),".$preInterviewId.",now(),".$interviewId.")";

            $queryToInsert = "INSERT INTO `interviewSchedule`(`company_id`,`candidate_id`,`url`,`scheduleTime`,`sectorId`,`candidateName`,`emailId`,`mobileNumber`,`recruiterId`,`preInterviewId`,`firstScheduleDate`,`interviewId`,`jobType`,`currentCompany`,`workExperience`,`expectedSalary`,`noticePeriod`,`workLocationPreference`,`timeToCall`,`currentLocation`,`preferredWorkLocation`,`languages`,`preferredRole`,`certiValues`,`avgTenure`,`resume`,`skillValues`, `currentSalary`) VALUES (" . $companyId . "," . $userId . ",'" . $currenturl . "',now()," . $sectorId . ",'" . $candidateName . "','" . $candidateEmailId . "'," . $candidateMobileNumber . ",(select id from recruiterList where name ='Goprac' and corporateId=4)," . $preInterviewId . ",now()," . $interviewId . ",'" . $jobType . "','" . $currentCompany . "','" . $workExperience . "','" . $expectedSalary . "','" . $noticePeriod . "','" . $workLocationPreference . "','" . $timeToCall . "','" . $currentLocation . "','" . $preferredWorkLocation . "','" . $languages . "','" . $preferredRole . "','" . $certifications . "','" . $avgTenure . "','" . $resume . "','" . $skills . "','" . $salary . "')";

            $queryToInsertData = mysqli_query($databaseConnection, $queryToInsert);
            if ($queryToInsertData) {
                $to_encode = array(
                    'status' => 1,
                    'data' => 'Insert Success'
                );
            } else {
                $to_encode = array(
                    'status' => -1,
                    'data' => 'Error While Insert'
                );
            }
        } else {

            $result = mysqli_fetch_all($queryToCheckData, MYSQLI_ASSOC);
            $recruiterId = $result[0]['recruiterId'];
            if (is_null($recruiterId)) {
                $recruiterId = '18';
            }

            if (is_null($result[0]['interviewId'])) {

                $queryToUpdate1 = "UPDATE `interviewSchedule` SET interviewId=" . $interviewId . " WHERE `preInterviewId` = " . $preInterviewId . " AND `emailId` = '" . $candidateEmailId . "' AND interviewId IS NULL";

                $queryToUpdateData1 = mysqli_query($databaseConnection, $queryToUpdate1);
                if ($queryToUpdateData1) {
                    $to_encode = array(
                        'status' => 1,
                        'data' => 'Updated InterviewId Success'
                    );
                } else {
                    $to_encode = array(
                        'status' => -1,
                        'data' => 'Error While Updating InterviewId'
                    );
                }


            } else {

                $checkingEntry = mysqli_query($databaseConnection, "SELECT * FROM `interviewSchedule` WHERE `preInterviewId` = " . $preInterviewId . " AND `interviewId` = " . $interviewId . " AND `emailId` = '" . $candidateEmailId . "'");

                if (mysqli_num_rows($checkingEntry) == 0) {

                    // $queryToInsert2 = "INSERT INTO `interviewSchedule`(`company_id`,`candidate_id`,`url`,`scheduleTime`,`sectorId`,`candidateName`,`emailId`,`mobileNumber`,`recruiterId`,`preInterviewId`,`firstScheduleDate`,`interviewId`) VALUES (".$companyId.",".$userId.",'".$currenturl."',now(),".$sectorId.",'".$candidateName."','".$candidateEmailId."',".$candidateMobileNumber.",".$recruiterId.",".$preInterviewId.",now(),".$interviewId.")";

                    $queryToInsert2 = "INSERT INTO `interviewSchedule`(`company_id`,`candidate_id`,`url`,`scheduleTime`,`sectorId`,`candidateName`,`emailId`,`mobileNumber`,`recruiterId`,`preInterviewId`,`firstScheduleDate`,`interviewId`,`jobType`,`currentCompany`,`workExperience`,`expectedSalary`,`noticePeriod`,`workLocationPreference`,`timeToCall`,`currentLocation`,`preferredWorkLocation`,`languages`,`preferredRole`,`certiValues`,`avgTenure`,`resume`,`skillValues`, `currentSalary`) VALUES (" . $companyId . "," . $userId . ",'" . $currenturl . "',now()," . $sectorId . ",'" . $candidateName . "','" . $candidateEmailId . "'," . $candidateMobileNumber . ",(select id from recruiterList where name ='Goprac' and corporateId=4)," . $preInterviewId . ",now()," . $interviewId . ",'" . $jobType . "','" . $currentCompany . "','" . $workExperience . "','" . $expectedSalary . "','" . $noticePeriod . "','" . $workLocationPreference . "','" . $timeToCall . "','" . $currentLocation . "','" . $preferredWorkLocation . "','" . $languages . "','" . $preferredRole . "','" . $certifications . "','" . $avgTenure . "','" . $resume . "','" . $skills . "','" . $salary . "')";

                    $queryToInsertData2 = mysqli_query($databaseConnection, $queryToInsert2);
                    if ($queryToInsertData2) {
                        $to_encode = array(
                            'status' => 1,
                            'data' => 'Insert Success'
                        );
                    } else {

                        $to_encode = array(
                            'status' => -1,
                            'data' => 'Error While Insert'
                            // 'data' => 'Error While Insert:'.mysqli_error($databaseConnection)
                        );
                    }
                } else {

                    $queryToUpdate = "UPDATE `interviewSchedule` SET scheduleTime=now() WHERE `preInterviewId` = " . $preInterviewId . " AND `interviewId` = " . $interviewId . " AND `emailId` = '" . $candidateEmailId . "'";

                    $queryToUpdateData = mysqli_query($databaseConnection, $queryToUpdate);
                    if ($queryToUpdateData) {
                        $to_encode = array(
                            'status' => 1,
                            'data' => 'Updated Success'
                        );
                    } else {
                        $to_encode = array(
                            'status' => -1,
                            'data' => 'Error While Updated'
                        );
                    }

                }
            }



        }
    }
    echo json_encode($to_encode);
} else if (isset($_GET['getEmployabilityrescheduleInterviewDetails'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if ($json) {
        $sectorId = $json['sectorId'];
        $userId = $json['userId'];
        $interviewDatetime = $json['interviewDatetime'];
        $currenturl = $json['currenturl'];

        $queryToCheck = "SELECT * FROM `interviewSchedule` WHERE `sectorId` = " . $sectorId . " AND `candidate_id` = " . $userId . " ";
        $queryToCheckData = mysqli_query($databaseConnection, $queryToCheck);
        if (mysqli_num_rows($queryToCheckData) > 0) {
            $queryToUpdate = "UPDATE `interviewSchedule` SET `scheduleTime`='" . $interviewDatetime . "',`emailed`='N' WHERE `sectorId` = " . $sectorId . " AND `candidate_id` = " . $userId . " ";
            $queryToUpdateData = mysqli_query($databaseConnection, $queryToUpdate);
            if ($queryToUpdateData) {
                $to_encode = array(
                    'status' => 1,
                    'data' => 'Update Success'
                );
            } else {
                $to_encode = array(
                    'status' => -1,
                    'data' => 'Error While Update'
                );
            }
        } else {
            $queryToInsert = "INSERT INTO `interviewSchedule`(`sectorId`,`candidate_id`,`url`,`scheduleTime`,`company_id`,`firstScheduleDate`) VALUES (" . $sectorId . "," . $userId . ",'" . $currenturl . "','" . $interviewDatetime . "',0,'" . $interviewDatetime . "')";
            $queryToInsertData = mysqli_query($databaseConnection, $queryToInsert);
            if ($queryToInsertData) {
                $to_encode = array(
                    'status' => 1,
                    'data' => 'Insert Success'
                );
            } else {
                $to_encode = array(
                    'status' => -1,
                    'data' => 'Error While Insert'
                );
            }
        }
    }
    echo json_encode($to_encode);
} else if (isset($_GET['updateCandidateStatus'])) {
    // This method is added by arun on Mar 16 2023 to update candidate details in interviewSchedule table
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if ($json) {
        $candidate_Id = $json['candidateId'];
        $candidateName = $json['name'];
        $interviewName = $json['interview_name'];
        $reporturl = $json['reportlink'];
        $mobile = $json['mobileNumber'];
        $candidateEmailId = $json['Email'];
        $noticePeriod = $json['noticePeriod'];
        $comment = $json['comment'];
        $workExperience = $json['workExperience'];
        $currentlocation = $json['currentlocation'];
        $currentCompany = $json['currentCompany'];
        $currentSalary = $json['currentSalary'];
        $expectedSalary = $json['expectedSalary'];
        $companyId = $json['companyId'];
        $pre_id = $json['preId'];
        $RecruiterEmail = ($json['RecruiterEmail'] != "") ? $json['RecruiterEmail'] : "sushil@goprac.com";
        $resume = $json['resume'];
        $f2fDate = $json['f2fDate'] || $json['f2fDate'] == 0 ? $json['f2fDate'] : null;

        // email sending
        if ($companyId != null) {
            $company_query = mysqli_query($databaseConnection, "SELECT name AS company FROM aspiration_company WHERE id = " . $companyId . " ");
            $company = mysqli_fetch_assoc($company_query);
            if ($company) {
                $companyName = $company['company'];
            }
        } else {
            $company_query = mysqli_query($databaseConnection, "SELECT name AS company FROM aspiration_company WHERE id = (select company_id from preInterview where id=" . $pre_id . ")");
            $company = mysqli_fetch_assoc($company_query);
            if ($company) {
                $companyName = $company['company'];
            }
        }

        if ($json['cs'] == "Client Shortlisted") {

            $preIdInt = $json['preId']; // Replace 123 with the actual value of the preId you are getting

            $interviewLink = $json['url'];


            $roleQuery = "SELECT position as roleId, GROUP_CONCAT(subject) as subjectIds FROM scps_transaction WHERE preInterviewId = $preIdInt";
            $roleQueryResult = mysqli_query($databaseConnection, $roleQuery);

            if ($roleQueryResult) {
                // echo  $roleQuery; 

                $roleData = mysqli_fetch_assoc($roleQueryResult);

                if ($roleData) {
                    $roleId = $roleData['roleId'];
                    $subjectId = $roleData['subjectIds'];

                    $insertQuery1 = "INSERT INTO register (registeredTime, roleId, subjectId, name, email, phone_no, candidateStatus,preId,f2fDate) 
                        VALUES (NOW(), '$roleId', '$subjectId', '$candidateName', '$candidateEmailId', '$mobile', 'client shortlisted',$preIdInt,'$f2fDate')";

                    //  echo  $insertQuery1 ;
                    //  exit();
                    $result = mysqli_query($databaseConnection, $insertQuery1);

                    // if ($result) {
                    //     echo "Data inserted successfully.";
                    // } else {
                    //     echo "Error inserting data: " . mysqli_error($databaseConnection);
                    // }


                    // echo $insertQuery1; 
                } else {
                    echo "No data found for preInterviewId = $preIdInt";
                }
            } else {
                echo "Error executing query: " . mysqli_error($databaseConnection);
            }

            // exit(); 


            $templateQuery = "select subject,details from candidateEmailTemplate where status = 'Client Shortlist' ";
            $templateQueryResult = mysqli_query($databaseConnection, $templateQuery);
            $msg = mysqli_fetch_assoc($templateQueryResult);

            $candidateName = $json['name'];
            $interviewName = $json['interview_name'];
            $RecruitingComapanyName = "Goprac";

            // Using str_replace
            $placeholders = array('{interview name}', '{student name}', 'interviewLink', 'interviewLink', '{interview}');
            $values = array($interviewName, $candidateName, $interviewLink, $interviewLink, $RecruitingComapanyName);
            $template = str_replace($placeholders, $values, $msg);



            // print_r($template);
            $dts = $template['details'];
            $dts1 = $template['subject'];
            $candidateEmailId = $json['Email'];


            // try {
            //     sendEmailToUser($candidateEmailId, null, $dts1, $dts);
            // } catch (Exception $e) {
            //     $response = array(
            //         'status' => -1,
            //         'data' => 'Error while sending email: ' . $e->getMessage()
            //     );
            //     echo json_encode($response);
            //     exit;
            // }

            // for whatsapp
            $watidata = array();
            $url = $interviewLink;
            $components = explode('/', $url);
            $modifiedUrl = isset($components[3]) ? $components[3] : '';
            $watidata["candidateName"] = $candidateName;
            $watidata["companyname"] = $interviewName;
            //modify by shrikant : 18/1/2024
            //$watidata["interviewLink"] = $modifiedUrl;
            $watidata["interviewLink"] = $url;
            $watidata["sender"] = $RecruitingComapanyName;
            // whatsAppMsg($databaseConnection,$json['mobileNumber'],$watidata,"clientShortlist");





        }

        // Shrikant added for sending email and wattsup message on updating candidatestatus : 25/1/2024
        //Shrikant changed : 6/3/2024
        //if($json['cs'] !='' && (($json['cs']=='Client Shortlisted') || ($json['cs']=='Client Rejected') || ($json['cs']=='Recruiter Reject') || ($json['cs']=='Offered'))){
        if ($json['cs'] != '' && (($json['cs'] == 'Client Shortlisted') || ($json['cs'] == 'Client Screen Reject') || ($json['cs'] == 'Recruiter Reject') || ($json['cs'] == 'Offered'))) {

            $candidateStatusForUpdate = $json['cs'];
            $msg = '';
            $wattsuptemplate = '';
            $templateQuery = '';
            $templateQueryResult = '';
            if ($candidateStatusForUpdate == 'Client Shortlisted') {
                $templateQuery = "select subject,details from candidateEmailTemplate where status = 'Client Shortlist' ";
                $templateQueryResult = mysqli_query($databaseConnection, $templateQuery);
                $msg = mysqli_fetch_assoc($templateQueryResult);
                $wattsuptemplate = 'clientShortlist';
            }
            // elseif( $candidateStatusForUpdate == 'Profile Shared'){
            //     $templateQuery = "select subject,details from candidateEmailTemplate where status = 'Resume Shared' ";
            //     $templateQueryResult = mysqli_query($databaseConnection,$templateQuery);
            //     $msg = mysqli_fetch_assoc($templateQueryResult);
            //     $wattsuptemplate='Resume Shared';   
            // }
            // elseif( $candidateStatusForUpdate == 'Client Rejected'){
            elseif ($candidateStatusForUpdate == 'Client Screen Reject') {
                $templateQuery = "select subject,details from candidateEmailTemplate where status = 'Client Rejected' ";
                $templateQueryResult = mysqli_query($databaseConnection, $templateQuery);
                $msg = mysqli_fetch_assoc($templateQueryResult);
                $wattsuptemplate = 'Client Rejected';
            } elseif ($candidateStatusForUpdate == 'Recruiter Reject') {
                $templateQuery = "select subject,details from candidateEmailTemplate where status = 'Recruiter Reject' ";
                $templateQueryResult = mysqli_query($databaseConnection, $templateQuery);
                $msg = mysqli_fetch_assoc($templateQueryResult);
                $wattsuptemplate = 'Recruiter Reject';

            } elseif ($candidateStatusForUpdate == 'Offered') {
                $templateQuery = "select subject,details from candidateEmailTemplate where status = 'Offered' ";
                $templateQueryResult = mysqli_query($databaseConnection, $templateQuery);
                $msg = mysqli_fetch_assoc($templateQueryResult);
                $wattsuptemplate = 'Offered';
            }

            $preIdInt = $json['preId'];
            $interviewLink = $json['url'];
            $candidateName = $json['name'];
            $interviewName = $json['interview_name'];
            $RecruitingCompanyName = "Team Goprac";
            $companyJobLocation = $json['companyJobLocation'];
            $dashboardLink = $emailApiHost . '/dashboard?p=' . $preIdInt;
            $serviceType = '';
            if ($preIdInt != null) {
                $query = "SELECT serviceType as sname FROM preInterview WHERE id = $preIdInt";
                $QueryResult = mysqli_query($databaseConnection, $query);

                if ($QueryResult) { // check if the query was successful
                    $result = mysqli_fetch_assoc($QueryResult);
                    $serviceType = $result['sname']; // assign the value to $serviceType
                }
            }

            if ($serviceType == 'IAS') {
                $RecruitingCompanyName = $interviewName . ", " . $companyJobLocation;
            }
            //$RecruitingComapanyName = "Goprac";
            // Using str_replace
            $placeholders = array('{interview name}', '{student name}', 'interviewLink', 'interviewLink', '{interview}', '{companyJobLocation}', 'dashboardLink');
            $values = array($interviewName, $candidateName, $interviewLink, $interviewLink, $RecruitingCompanyName, $companyJobLocation, $dashboardLink);

            $template = str_replace($placeholders, $values, $msg);
            $dts = $template['details'];
            $dts1 = $template['subject'];
            $candidateEmailId = $json['Email'];

            sendEmailToUser($candidateEmailId, null, $dts1, $dts);
            //sendEmailToUser('shrikantkolhatkar30336@gmail.com', null, $dts1, $dts);
            // debug
            // sendEmailToUser('sourabh13689@gmail.com', null, $dts1, $dts);

            // for whatsapp
            $watidata = array();
            $url = $interviewLink;
            $watidata["candidateName"] = $candidateName;
            $watidata["companyname"] = $interviewName . ", " . $companyJobLocation;
            $watidata["interviewLink"] = $url;
            $watidata["dashboardLink"] = $dashboardLink;
            $watidata["sender"] = $RecruitingCompanyName;

            //shrikant added : 6/2/2024 
            // sourabh 28 nov 2024 - also send for recruter reject 
            // if($json['cs'] != 'Recruiter Reject'){
            whatsAppMsg($databaseConnection, $json['mobileNumber'], $watidata, $wattsuptemplate);
            // whatsAppMsg($databaseConnection,'9767479189',$watidata,$wattsuptemplate);
            // debug
            // whatsAppMsg($databaseConnection,'9906308210',$watidata,$wattsuptemplate);
            // }

        }


        // email sending


        $queryToCheck_sql = "SELECT * FROM `interviewSchedule` WHERE `preInterviewId` = " . $json['preId'] . " AND `emailId` = '" . $json['Email'] . "'";
        // echo $queryToCheck_sql;
        $queryToCheck = mysqli_query($databaseConnection, $queryToCheck_sql);

        if (mysqli_num_rows($queryToCheck) > 0) {

            $result = mysqli_fetch_all($queryToCheck, MYSQLI_ASSOC);



            $queryToUpdate_Data = "UPDATE `interviewSchedule` SET ";

            if ($json['cs'] != '') {
                $queryToUpdate_Data .= "`candidateStatus`='" . $json['cs'] . "',";
                $queryToUpdate_Data .= "`candidateStatusDate`=CURDATE()";
            }
            if ($json['cs'] == "Profile Shared") {
                $queryToUpdate_Data .= ",`resumeSharedDate`=CURDATE()";
            }

            // if (is_null($json['interviewId'])) {

            $queryToUpdate_Data .= " where emailId='" . $json['Email'] . "' and preInterviewId=" . $json['preId'] . "";

            // } else {

            //     $queryToUpdate_Data .= " where emailId='" . $json['Email'] . "' and preInterviewId=" . $json['preId'] . " and interviewId=" . $json['interviewId'] . "";
            // }

            // echo $queryToUpdate_Data;

            $queryToUpdateData1 = mysqli_query($databaseConnection, $queryToUpdate_Data);


            if ($queryToUpdateData1) {
                if ($json['cs'] == "Profile Shared") {
                    $to = $RecruiterEmail;
                    // $to = 'sourabh13689@gmail.com';
                    $subjects = "Goprac Candidate Profiles | " . $interviewName . "";
                    $messages = "
                        <html>
                        <head>
                        </head>
                        <body>
                            <p style='font-weight:bold;color:black'>Dear Nitin,</p>
                            <p style='font-weight:bold;color:black'>Greetings from GoPrac!</p>   
                            <p style='font-weight:bold;color:black'>We recommend you to meet with the following candidates who have expressed interest in this job opportunity at " . $companyName . "</p>
                            <p style='font-weight:bold;color:black'>Candidate Details:</p>
                             <table style='border-collapse: collapse; border: 1px solid black;'>
                             <tr>
                                 <th style='border: 1px solid black;'>Resume Link</th>
                                 <th style='border: 1px solid black;'>Candidate Name</th>
                                 <th style='border: 1px solid black;'>Phone No</th>
                                 <th style='border: 1px solid black;'>Email ID</th>
                                 <th style='border: 1px solid black;'>Current Employer</th>
                                 <th style='border: 1px solid black;'>Total Years of Experience</th>
                                 <th style='border: 1px solid black;'>Location</th>
                                 <th style='border: 1px solid black;'>Current CTC</th>
                                 <th style='border: 1px solid black;'>Expected CTC</th>
                                 <th style='border: 1px solid black;'>Notice Period</th>
                                <th style='border: 1px solid black;'>Comments</th>
                             </tr>
                             <tr>
                                 <td style='border: 1px solid black;'>
                                   <a href='" . $resume . "'> " . strtolower($candidateName . '_resume') . "</a>
                                 </td>
                                  <td style='border: 1px solid black;'>" . $candidateName . "</td>
                                  <td style='border: 1px solid black;'>" . $mobile . "</td>
                                  <td style='border: 1px solid black;'>" . $candidateEmailId . "</td>
                                  <td style='border: 1px solid black;'>" . $currentCompany . "</td>
                                  <td style='border: 1px solid black;'>" . $workExperience . "</td>
                                  <td style='border: 1px solid black;'>" . $currentlocation . "</td>
                                  <td style='border: 1px solid black;'>" . $currentSalary . "</td>
                                  <td style='border: 1px solid black;'>" . $expectedSalary . "</td>
                                  <td style='border: 1px solid black;'>" . $noticePeriod . "</td>
                                  <td style='border: 1px solid black;'>" . ($comment ?? 'NA') . "</td>
                              </tr>
                              </table> 
                            <p style='font-weight:bold;color:black'>Do let us know if you need any further assistance. Thank you.</p> 
                            <p style='font-weight:bold;color:black'>Greetings!<br>GoPrac Team</p>
                        </body>
                        </html>";
                    // Send the email
                    //echo $messages;
                    sendEmailToUser($to, null, $subjects, $messages);

                }
                $to_encode = array(
                    'status' => 1,
                    'data' => 'Update Success'
                );
            } else {
                $to_encode = array(
                    'status' => -1,
                    'data' => 'Error While Update'
                );
            }
        } else {
            $to_encode = array(
                'status' => 1,
                'data' => 'Entry not exist in the table'
            );
        }



    }
    echo json_encode($to_encode);
} else if (isset($_GET['updateResumeSharedStatus'])) {
    // This method is added by arun on Mar 16 2023 to update candidate details in interviewSchedule table
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if ($json) {
        $candidateId = $json['candidateId'];
        $resumeShared_Company = $json['ResumeSharedCompany'];
        $resumeShared_Date = $json['ResumeSharedDate'];
        $candidate_feedback = $json['cFeedback'];


        $queryToUpdate = "UPDATE `professionaldetails` SET ";

        if ($json['ResumeSharedCompany'] != '') {
            $queryToUpdate .= " `resumeSharedCompany`='" . $resumeShared_Company . "',";
        } else {
            $queryToUpdate .= " `resumeSharedCompany`=NULL,";
        }


        if ($json['ResumeSharedDate'] != '') {
            $queryToUpdate .= " `resumeSharedDate`='" . $resumeShared_Date . "',";
        } else {
            $queryToUpdate .= " `resumeSharedDate`=NULL,";
        }

        if ($json['cFeedback'] != '') {
            $queryToUpdate .= "`candidateFeedback`='" . $candidate_feedback . "'";
        } else {
            $queryToUpdate .= "`candidateFeedback`=NULL";
        }

        $queryToUpdate .= " where candidateId=" . $candidateId . "";

        $queryToUpdateData = mysqli_query($databaseConnection, $queryToUpdate);

        $checkingQuery = mysqli_query($databaseConnection, "select u.id,u.emailId from users u inner join interviewSchedule isc on isc.emailId=u.emailId where u.id=" . $candidateId . " group by u.id");

        if (mysqli_num_rows($checkingQuery) >= 1) {

            $userEmailId = mysqli_fetch_assoc($checkingQuery)['emailId'];

            $queryToUpdate_Data = "UPDATE `interviewSchedule` SET ";

            if ($json['ResumeSharedCompany'] != '') {
                $queryToUpdate .= " `resumeSharedCompany`='" . $resumeShared_Company . "',";
            } else {
                $queryToUpdate .= " `resumeSharedCompany`=NULL,";
            }


            if ($json['ResumeSharedDate'] != '') {
                $queryToUpdate .= " `resumeSharedDate`='" . $resumeShared_Date . "',";
            } else {
                $queryToUpdate .= " `resumeSharedDate`=NULL,";
            }

            if ($json['cFeedback'] != '') {
                $queryToUpdate .= "`candidateFeedback`='" . $candidate_feedback . "'";
            } else {
                $queryToUpdate .= "`candidateFeedback`=NULL";
            }

            $queryToUpdate_Data .= " where emailId='" . $userEmailId . "'";

            $queryToUpdateData1 = mysqli_query($databaseConnection, $queryToUpdate_Data);
        }

        if ($queryToUpdateData) {
            $to_encode = array(
                'status' => 1,
                'data' => 'Update Success'
            );
        } else {
            $to_encode = array(
                'status' => -1,
                'data' => 'Error While Update'
            );
        }


    }
    echo json_encode($to_encode);
} else if (isset($_GET['updateAmplifierStatus'])) {
    // This method is added by arun on Mar 16 2023 to update candidate details in interviewSchedule table
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if ($json) {
        $id = $json['scheduleId'];


        $queryToUpdate = "UPDATE `interviewSchedule` SET ";

        if ($json['amplifier'] != '') {
            $queryToUpdate .= "`amplifier`='" . $json['amplifier'] . "'";
        } else {
            $queryToUpdate .= "`amplifier`=NULL ";
        }

        $queryToUpdate .= " where id=" . $id . "";



        $queryToUpdateData = mysqli_query($databaseConnection, $queryToUpdate);
        if ($queryToUpdateData) {
            $to_encode = array(
                'status' => 1,
                'data' => 'Update Success'
            );
        } else {
            $to_encode = array(
                'status' => -1,
                'data' => 'Error While Update'
            );
        }


    }
    echo json_encode($to_encode);
} else if (isset($_GET['getSubjects'])) {
    // This method is added by arun on Apr 04 2023 to list out the subjects for interview creation
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if ($json) {

        $vendorId = $json['vId'];
        $validateVendor = mysqli_query($databaseConnection, "select * from vendors where id=" . $vendorId . "");

        if (mysqli_num_rows($validateVendor) > 0) {

            // $coreSubjects = mysqli_query($databaseConnection,"select fs.id,fs.favourite_subject as subjectName from favourite_subject fs inner join questions q on q.subjectId=fs.id where q.deleted_at is null and fs.favourite_subject not in (select fav_prog_skill from fav_prog_skill) group by fs.id having count(distinct case when q.isFollowUp in ('Y','N')then q.id end)>=4 order by fs.favourite_subject ASC");

            $coreSubjects = mysqli_query($databaseConnection, "select fs.id,fs.favourite_subject as subjectName from favourite_subject fs inner join questions q on q.subjectId=fs.id where q.deleted_at is null  AND fs.active = 'Y' group by fs.id having count(distinct case when q.isFollowUp in ('Y','N')then q.id end)>=4 order by fs.favourite_subject ASC");


            // $programmingSubjects = mysqli_query($databaseConnection,"select fs.id,fs.favourite_subject as subjectName from favourite_subject fs inner join questions q on q.subjectId=fs.id inner join fav_prog_skill fps on fps.fav_prog_skill=fs.favourite_subject where q.deleted_at is null group by fs.id having count(distinct case when q.isFollowUp in ('Y','N')then q.id end)>=5 order by fs.favourite_subject ASC");

            $programmingSubjects = mysqli_query($databaseConnection, "select fs.id,fs.favourite_subject as subjectName from favourite_subject fs inner join questions q on q.subjectId=fs.id where q.deleted_at is null AND fs.active = 'Y' group by fs.id having count(distinct case when q.isFollowUp in ('Y','N')then q.id end)>=5 order by fs.favourite_subject ASC");



            if ($coreSubjects && $programmingSubjects) {
                $result['coreSubjects'] = mysqli_fetch_all($coreSubjects, MYSQLI_ASSOC);

                $result['programmingSubject'] = mysqli_fetch_all($programmingSubjects, MYSQLI_ASSOC);
                $result['status'] = 1;

                $to_encode = $result;
            } else {
                $to_encode = array(
                    'status' => -1,
                    'data' => 'Error While fetching the subjects'
                );
            }

        } else {
            $to_encode = array(
                'status' => -1,
                'result' => "error",
                'data' => 'Your not authorised to access this'
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'data' => 'Error'
        );
    }

    echo json_encode($to_encode);
} else if (isset($_GET['createAdaptiveInterview'])) {
    // This method is added by arun on 29 Mar 2023 for vendor interview creation

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if ($json) {

        $vendorId = $json['vId'];
        $roleName = $json['role'];
        $interviewStructureType = 0;
        $interviewName = $json['iName'];
        $Eligibility = $json['eligibility'];
        $iExpireDate = $json['interviewExpireDate'];
        $jd = $json['jobDescription'];

        // $difficultyLevel=$json['dLevel'];
        $level = '';
        $coreSubject1 = array();
        $coreSubject2 = array();
        $programmingsubject = array();

        if ($Eligibility == '') {

            $to_encode = array(
                'status' => -1,
                'result' => "error",
                'data' => "Eligibility can't be empty"
            );
            echo json_encode($to_encode);
            exit();

        }
        // else if(preg_match('/[\']/', $Eligibility)){
        //         $to_encode = array(
        //             'status' => -1,
        //             'result' => "error",
        //             'data' => "Special characters not allowed in eligibility section"
        //         );
        //         echo json_encode($to_encode);
        //         exit();

        // }

        if ($iExpireDate == '') {

            $to_encode = array(
                'status' => -1,
                'result' => "error",
                'data' => "Interview Expire Date can't be empty"
            );
            echo json_encode($to_encode);
            exit();

        }

        // if($jd==''){
        //     $to_encode = array(
        //         'status' => -1,
        //         'result' => "error",
        //         'data' => "Job Description can't be empty"
        //     );
        //     echo json_encode($to_encode);
        //     exit();

        // }else if(preg_match('/[\']/', $jd)){
        //         $to_encode = array(
        //             'status' => -1,
        //             'result' => "error",
        //             'data' => "Single Quote not allowed in between job description text"
        //         );
        //         echo json_encode($to_encode);
        //         exit();

        // }

        if ($interviewName == '') {
            $to_encode = array(
                'status' => -1,
                'result' => "error",
                'data' => "Interview Name can't be empty"
            );
            echo json_encode($to_encode);
            exit();

        }
        // else if(preg_match('/[\']/', $interviewName)){
        //         $to_encode = array(
        //             'status' => -1,
        //             'result' => "error",
        //             'data' => "Special characters not allowed in Interview Name"
        //         );
        //         echo json_encode($to_encode);
        //         exit();
        // }

        $level = 'Basic,Average,Advanced';



        if ($json['cSub1'] != '') {
            $coreSubject1 = preg_split("/\,/", $json['cSub1']);
        }

        if ($json['cSub2'] != '') {
            $coreSubject2 = preg_split("/\,/", $json['cSub2']);
        }

        if ($json['pSub'] != '') {
            $programmingsubject = preg_split("/\,/", $json['pSub']);
        }


        if (sizeOf($coreSubject1) == 1) {

            $subjectTest = mysqli_query($databaseConnection, "select fs.id,fs.favourite_subject as subjectName from favourite_subject fs inner join questions q on q.subjectId=fs.id where q.deleted_at is null and fs.favourite_subject= '" . $coreSubject1[0] . "'   group by fs.id having count(distinct case when q.isFollowUp in ('Y','N')then q.id end)>=4 order by fs.favourite_subject ASC");


            if (mysqli_num_rows($subjectTest) <= 0) {

                $to_encode = array(
                    'status' => -1,
                    'result' => "error",
                    'data' => "Core Subject 1 is not exists"
                );
                echo json_encode($to_encode);
                exit();
            }

        } else if (sizeOf($coreSubject1) < 1) {

            $to_encode = array(
                'status' => -1,
                'result' => "error",
                'data' => "Core Subject 1 can't be empty!"
            );
            echo json_encode($to_encode);
            exit();

        } else if (sizeOf($coreSubject1) > 1) {

            $to_encode = array(
                'status' => -1,
                'result' => "error",
                'data' => "Maximum subject is 1 You given more than that in Core Subject 1"
            );
            echo json_encode($to_encode);
            exit();
        }

        //core subject 2 validation

        if (sizeOf($coreSubject2) == 1) {

            $subjectTest = mysqli_query($databaseConnection, "select fs.id,fs.favourite_subject as subjectName from favourite_subject fs inner join questions q on q.subjectId=fs.id where q.deleted_at is null and fs.favourite_subject= '" . $coreSubject2[0] . "'     group by fs.id having count(distinct case when q.isFollowUp in ('Y','N')then q.id end)>=4 order by fs.favourite_subject ASC");

            if (mysqli_num_rows($subjectTest) <= 0) {

                $to_encode = array(
                    'status' => -1,
                    'result' => "error",
                    'data' => "Core Subject 2 is not exists"
                );
                echo json_encode($to_encode);
                exit();
            }

        } else if (sizeOf($coreSubject2) > 1) {

            $to_encode = array(
                'status' => -1,
                'result' => "error",
                'data' => "Maximum subject is 1 You given more than that in Core Subject 2"
            );
            echo json_encode($to_encode);
            exit();
        }

        //programming subject Validation

        if (sizeOf($programmingsubject) == 1) {

            $subjectTest = mysqli_query($databaseConnection, "select fs.id,fs.favourite_subject as subjectName from favourite_subject fs inner join questions q on q.subjectId=fs.id where q.deleted_at is null and fs.favourite_subject='" . $programmingsubject[0] . "'   group by fs.id having count(distinct case when q.isFollowUp in ('Y','N')then q.id end)>=5 order by fs.favourite_subject ASC");

            if (mysqli_num_rows($subjectTest) <= 0) {

                $to_encode = array(
                    'status' => -1,
                    'result' => "error",
                    'data' => "Programming Subject is not exists"
                );
                echo json_encode($to_encode);
                exit();
            }

        } else if (sizeOf($programmingsubject) > 1) {

            $to_encode = array(
                'status' => -1,
                'result' => "error",
                'data' => "Maximum subject is 1 You given more than that in Programming Subject"
            );
            echo json_encode($to_encode);
            exit();
        }



        if ($json['cSub1'] != '' && $json['cSub2'] != '' && $json['pSub'] != '') {

            $interviewStructureType = 2;

        } else if ($json['cSub1'] != '' && $json['cSub2'] != '' && $json['pSub'] == '') {

            $interviewStructureType = 1;

        } else if ($json['cSub1'] != '' && $json['cSub2'] == '' && $json['pSub'] != '') {

            $interviewStructureType = 3;

        } else if ($json['cSub1'] != '' && $json['cSub2'] == '' && $json['pSub'] == '') {

            $interviewStructureType = 4;

        } else if ($json['cSub1'] == '' && $json['cSub2'] == '' && $json['pSub'] != '') {

            $interviewStructureType = 5;

        } else if ($json['cSub1'] == '' && $json['cSub2'] == '' && $json['pSub'] == '') {

            $interviewStructureType = 0;

        }


        if ($vendorId != '' && $roleName != '' && $interviewStructureType != '' && $interviewName != '' && $interviewStructureType != 0 && $level != '') {
            $validateVendor = mysqli_query($databaseConnection, "select * from vendors where id=" . $vendorId . "");

            $protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";

            $CurPageURL = $protocol . substr($_SERVER['HTTP_HOST'], 4);

            if (mysqli_num_rows($validateVendor) > 0) {

                $checkingRole = mysqli_query($databaseConnection, "select id from relavant_role where name='" . $roleName . "'");

                if (mysqli_num_rows($checkingRole) > 0) {

                    $roleId = mysqli_fetch_assoc($checkingRole)['id'];

                    $checkingInterview = mysqli_query($databaseConnection, "select pr.id,pr.company_id,scps.position from preInterview pr inner join scps_transaction scps on scps.preInterviewId=pr.id where pr.vendorId=" . $vendorId . " and scps.position=" . $roleId . " group by scps.position");

                    if (mysqli_num_rows($checkingInterview) > 0) {

                        $to_encode = array(
                            'status' => -1,
                            'result' => "error",
                            'data' => 'Error ! Interview already exists for this role and you'
                        );

                    } else {

                        $vName = mysqli_fetch_assoc($validateVendor)['vendorName'];

                        $checkingCompany = mysqli_query($databaseConnection, "select * from aspiration_company where name='" . $vName . "'");

                        if (mysqli_num_rows($checkingCompany) <= 0) {

                            $insertingCompany = mysqli_query($databaseConnection, "INSERT INTO aspiration_company(`name`) VALUES ('" . $vName . "')");
                        }


                        $preInterviewInsert = mysqli_query($databaseConnection, "INSERT INTO preInterview(`company_id`, `categoryType`, `interviewLevel`, `assessmentParameter`,`interviewName`,`sectorId`,`productId`,`interviewStartDate`,`vendorId`,`workExperience`,`currentLocation`,`preferredWorkLocation`,`Language`,`jobType`,`currentCompany`,`currentProcess`,`processType`,`clientType`,`currentSalary`,`expectedSalary`,`noticePeriod`,`processPreference`,`shift`,`workLocationPreference`,`timeToCall`,`declaration`,`preferedJobType`,`joiningTimeline`,`JDsection`,`showJDsection`,`interviewExpireDate`,`targetAudience`) VALUES ((SELECT id FROM aspiration_company WHERE name='" . $vName . "'),'9','Medium','Communication Skill, Behavioural Skill, Concept Knowledge, Problem Solving skills, Coding SKill','" . addslashes($interviewName) . "',2,1,now(),'" . $vendorId . "','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','" . addslashes($jd) . "','Y','" . $iExpireDate . "','" . addslashes($Eligibility) . "')");

                        $preInterviewId = mysqli_query($databaseConnection, "SELECT id FROM preInterview ORDER BY id DESC LIMIT 1");

                        $preId = mysqli_fetch_assoc($preInterviewId)['id'];


                        if ($interviewStructureType == 1 && $preInterviewInsert) {

                            $sql = "INSERT INTO interviewStructure(`sectorId`, `companyId`, `roleId`, `sectionSequence`, `sectionId`, `noOfAnswer`, `noOfSkip`, `depthRequired`, `clusterLevel`,`preInterviewId`) VALUES 
                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'1','1','1','2','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1)),

                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'2','3','2','2','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1)),
                            
                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'2','4','2','2','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1)),
                            
                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'6','8','2','2','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1)),
                            
                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'4','6','1','2','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1)),
                            
                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'5','7','0','0','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1));";


                            $interviewStructureInsert = mysqli_query($databaseConnection, $sql);


                            if ($interviewStructureInsert) {
                                $scpsInsert = 0;

                                //for core subject 1 dropdown
                                for ($i = 0; $i < sizeOf($coreSubject1); $i++) {

                                    $subjectId = mysqli_query($databaseConnection, "select id from favourite_subject where favourite_subject='" . $coreSubject1[$i] . "'");

                                    if (mysqli_num_rows($subjectId) > 0) {

                                        $sql2 = mysqli_query($databaseConnection, "INSERT INTO scps_transaction(`sector`,`company`,`position`,`subject`,`coreSubjectSequence`,`priority`,`dropdown`,`preInterviewId`,`subjectType`) VALUES ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),(select id from favourite_subject where favourite_subject='" . $coreSubject1[$i] . "'),'1','1',1,(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1),'technical')");

                                        $scpsInsert += 1;

                                    }

                                }
                                //for core subject 2 drop down
                                for ($i = 0; $i < sizeOf($coreSubject2); $i++) {

                                    $subjectId = mysqli_query($databaseConnection, "select id from favourite_subject where favourite_subject='" . $coreSubject2[$i] . "'  ");

                                    if (mysqli_num_rows($subjectId) > 0) {

                                        $sql2 = mysqli_query($databaseConnection, "INSERT INTO scps_transaction(`sector`,`company`,`position`,`subject`,`coreSubjectSequence`,`priority`,`dropdown`,`preInterviewId`,`subjectType`) VALUES ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),(select id from favourite_subject where favourite_subject='" . $coreSubject2[$i] . "'),'1','1',2,(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1),'technical')");

                                        $scpsInsert += 1;

                                    }

                                }

                                if ($scpsInsert) {

                                    // $data= $CurPageURL . '/companyDetailsx?a=null&preId=' . $preId .'&vId=' .$vendorId;
                                    // $data= $CurPageURL . '/job?p=' . $preId .'&vId=' .$vendorId;
                                    $data = $CurPageURL . '/companyDetails?p=' . $preId . '&vId=' . $vendorId;

                                    $to_encode = array(
                                        'status' => 1,
                                        'result' => "Success",
                                        'data' => $data
                                    );
                                } else {
                                    $to_encode = array(
                                        'status' => -1,
                                        'result' => "error",
                                        'data' => 'Error while creating interview structure step 3'
                                    );
                                }


                            } else {
                                $to_encode = array(
                                    'status' => -1,
                                    'result' => "error",
                                    'data' => 'Error while creating interview structure step 2'
                                );
                            }

                        } else if ($interviewStructureType == 2 && $preInterviewInsert) {

                            $sql = "INSERT INTO interviewStructure(sectorId, companyId, roleId, sectionSequence, sectionId, noOfAnswer, noOfSkip, depthRequired, clusterLevel, preInterviewId) VALUES 
                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'1','1','1','2','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1)),
                            
                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'2','3','2','2','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1)),
                            
                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'2','4','2','2','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1)),
                            
                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'6','8','2','2','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1)),
                            
                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'3','5','2','2','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1)),
                            
                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'4','6','1','2','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1)),
                            
                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'5','7','0','0','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1));";


                            $interviewStructureInsert = mysqli_query($databaseConnection, $sql);


                            if ($interviewStructureInsert) {
                                $scpsInsert = 0;

                                //for core subject 1 dropdown
                                for ($i = 0; $i < sizeOf($coreSubject1); $i++) {

                                    $subjectId = mysqli_query($databaseConnection, "select id from favourite_subject where favourite_subject='" . $coreSubject1[$i] . "' ");

                                    if (mysqli_num_rows($subjectId) > 0) {

                                        $sql2 = mysqli_query($databaseConnection, "INSERT INTO scps_transaction(`sector`,`company`,`position`,`subject`,`coreSubjectSequence`,`priority`,`dropdown`,`preInterviewId`,`subjectType`) VALUES ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),(select id from favourite_subject where favourite_subject='" . $coreSubject1[$i] . "'),'1','1',1,(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1),'technical')");

                                        $scpsInsert += 1;

                                    }

                                }
                                //for core subject 2 drop down
                                for ($i = 0; $i < sizeOf($coreSubject2); $i++) {

                                    $subjectId = mysqli_query($databaseConnection, "select id from favourite_subject where favourite_subject='" . $coreSubject2[$i] . "'  ");

                                    if (mysqli_num_rows($subjectId) > 0) {

                                        $sql2 = mysqli_query($databaseConnection, "INSERT INTO scps_transaction(`sector`,`company`,`position`,`subject`,`coreSubjectSequence`,`priority`,`dropdown`,`preInterviewId`,`subjectType`) VALUES ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),(select id from favourite_subject where favourite_subject='" . $coreSubject2[$i] . "'),'1','1',2,(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1),'technical')");

                                        $scpsInsert += 1;

                                    }

                                }

                                //for programming subject drop down
                                for ($i = 0; $i < sizeOf($programmingsubject); $i++) {

                                    $subjectId = mysqli_query($databaseConnection, "select id from favourite_subject where favourite_subject='" . $programmingsubject[$i] . "'  ");

                                    if (mysqli_num_rows($subjectId) > 0) {

                                        $sql2 = mysqli_query($databaseConnection, "INSERT INTO scps_transaction(`sector`,`company`,`position`,`subject`,`coreSubjectSequence`,`priority`,`dropdown`,`preInterviewId`,`subjectType`) VALUES ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),(select id from favourite_subject where favourite_subject='" . $programmingsubject[$i] . "'),'1','1',1,(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1),'coding')");

                                        $scpsInsert += 1;

                                    }

                                }



                                if ($scpsInsert) {

                                    // $data= $CurPageURL . '/companyDetailsx?a=null&preId=' . $preId .'&vId=' .$vendorId;

                                    // $data= $CurPageURL . '/job?p=' . $preId .'&vId=' .$vendorId;
                                    $data = $CurPageURL . '/companyDetails?p=' . $preId . '&vId=' . $vendorId;

                                    $to_encode = array(
                                        'status' => 1,
                                        'result' => "Success",
                                        'data' => $data
                                    );
                                } else {
                                    $to_encode = array(
                                        'status' => -1,
                                        'result' => "error",
                                        'data' => 'Error while creating interview structure step 3'
                                    );
                                }


                            } else {
                                $to_encode = array(
                                    'status' => -1,
                                    'result' => "error",
                                    'data' => 'Error while creating interview structure step 2'
                                );
                            }


                        } else if ($interviewStructureType == 3 && $preInterviewInsert) {

                            $sql = "INSERT INTO interviewStructure(sectorId, companyId, roleId, sectionSequence, sectionId, noOfAnswer, noOfSkip, depthRequired, clusterLevel, preInterviewId) VALUES 
                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'1','1','1','2','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1)),
                            
                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'2','3','2','2','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1)),
                            
                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'3','5','2','2','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1)),
                            
                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'4','6','1','2','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1)),
                            
                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'5','7','0','0','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1));";


                            $interviewStructureInsert = mysqli_query($databaseConnection, $sql);


                            if ($interviewStructureInsert) {
                                $scpsInsert = 0;

                                //for core subject 1 dropdown
                                for ($i = 0; $i < sizeOf($coreSubject1); $i++) {

                                    $subjectId = mysqli_query($databaseConnection, "select id from favourite_subject where favourite_subject='" . $coreSubject1[$i] . "'");

                                    if (mysqli_num_rows($subjectId) > 0) {

                                        $sql2 = mysqli_query($databaseConnection, "INSERT INTO scps_transaction(`sector`,`company`,`position`,`subject`,`coreSubjectSequence`,`priority`,`dropdown`,`preInterviewId`,`subjectType`) VALUES ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),(select id from favourite_subject where favourite_subject='" . $coreSubject1[$i] . "'),'1','1',1,(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1),'technical')");

                                        $scpsInsert += 1;

                                    }

                                }

                                //for programming subject drop down
                                for ($i = 0; $i < sizeOf($programmingsubject); $i++) {

                                    $subjectId = mysqli_query($databaseConnection, "select id from favourite_subject where favourite_subject='" . $programmingsubject[$i] . "'  ");

                                    if (mysqli_num_rows($subjectId) > 0) {

                                        $sql2 = mysqli_query($databaseConnection, "INSERT INTO scps_transaction(`sector`,`company`,`position`,`subject`,`coreSubjectSequence`,`priority`,`dropdown`,`preInterviewId`,`subjectType`) VALUES ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),(select id from favourite_subject where favourite_subject='" . $programmingsubject[$i] . "'),'1','1',1,(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1),'coding')");

                                        $scpsInsert += 1;

                                    }

                                }



                                if ($scpsInsert) {

                                    // $data= $CurPageURL . '/companyDetailsx?a=null&preId=' . $preId .'&vId=' .$vendorId;

                                    // $data= $CurPageURL . '/job?p=' . $preId .'&vId=' .$vendorId;
                                    $data = $CurPageURL . '/companyDetails?p=' . $preId . '&vId=' . $vendorId;

                                    $to_encode = array(
                                        'status' => 1,
                                        'result' => "Success",
                                        'data' => $data
                                    );
                                } else {
                                    $to_encode = array(
                                        'status' => -1,
                                        'result' => "error",
                                        'data' => 'Error while creating interview structure step 3'
                                    );
                                }


                            } else {
                                $to_encode = array(
                                    'status' => -1,
                                    'result' => "error",
                                    'data' => 'Error while creating interview structure step 2'
                                );
                            }

                        } else if ($interviewStructureType == 4 && $preInterviewInsert) {

                            $sql = "INSERT INTO interviewStructure(sectorId, companyId, roleId, sectionSequence, sectionId, noOfAnswer, noOfSkip, depthRequired, clusterLevel, preInterviewId) VALUES 
                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'1','1','1','2','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1)),
                            
                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'2','3','2','2','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1)),
                                                        
                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'3','6','1','2','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1)),
                            
                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'4','7','0','0','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1));";


                            $interviewStructureInsert = mysqli_query($databaseConnection, $sql);


                            if ($interviewStructureInsert) {
                                $scpsInsert = 0;

                                //for core subject 1 dropdown
                                for ($i = 0; $i < sizeOf($coreSubject1); $i++) {

                                    $subjectId = mysqli_query($databaseConnection, "select id from favourite_subject where favourite_subject='" . $coreSubject1[$i] . "' ");

                                    if (mysqli_num_rows($subjectId) > 0) {

                                        $sql2 = mysqli_query($databaseConnection, "INSERT INTO scps_transaction(`sector`,`company`,`position`,`subject`,`coreSubjectSequence`,`priority`,`dropdown`,`preInterviewId`,`subjectType`) VALUES ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),(select id from favourite_subject where favourite_subject='" . $coreSubject1[$i] . "'),'1','1',1,(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1),'technical')");

                                        $scpsInsert += 1;

                                    }

                                }

                                if ($scpsInsert) {

                                    // $data= $CurPageURL . '/companyDetailsx?a=null&preId=' . $preId .'&vId=' .$vendorId;

                                    // $data= $CurPageURL . '/job?p=' . $preId .'&vId=' .$vendorId;
                                    $data = $CurPageURL . '/companyDetails?p=' . $preId . '&vId=' . $vendorId;

                                    $to_encode = array(
                                        'status' => 1,
                                        'result' => "Success",
                                        'data' => $data
                                    );
                                } else {
                                    $to_encode = array(
                                        'status' => -1,
                                        'result' => "error",
                                        'data' => 'Error while creating interview structure step 3'
                                    );
                                }


                            } else {
                                $to_encode = array(
                                    'status' => -1,
                                    'result' => "error",
                                    'data' => 'Error while creating interview structure step 2'
                                );
                            }


                        } else if ($interviewStructureType == 5 && $preInterviewInsert) {

                            $sql = "INSERT INTO interviewStructure(sectorId, companyId, roleId, sectionSequence, sectionId, noOfAnswer, noOfSkip, depthRequired, clusterLevel, preInterviewId) VALUES 
                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'1','1','1','2','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1)),
                            
                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'3','5','2','2','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1)),
                            
                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'4','6','1','2','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1)),
                            
                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'5','7','0','0','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1));";


                            $interviewStructureInsert = mysqli_query($databaseConnection, $sql);


                            if ($interviewStructureInsert) {
                                $scpsInsert = 0;

                                //for core subject 1 dropdown
                                for ($i = 0; $i < sizeOf($programmingsubject); $i++) {

                                    $subjectId = mysqli_query($databaseConnection, "select id from favourite_subject where favourite_subject='" . $programmingsubject[$i] . "' ");

                                    if (mysqli_num_rows($subjectId) > 0) {

                                        $sql2 = mysqli_query($databaseConnection, "INSERT INTO scps_transaction(`sector`,`company`,`position`,`subject`,`coreSubjectSequence`,`priority`,`dropdown`,`preInterviewId`,`subjectType`) VALUES ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),(select id from favourite_subject where favourite_subject='" . $programmingsubject[$i] . "'),'1','1',1,(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1),'coding')");

                                        $scpsInsert += 1;

                                    }

                                }

                                if ($scpsInsert) {

                                    // $data= $CurPageURL . '/companyDetailsx?a=null&preId=' . $preId .'&vId=' .$vendorId;

                                    // $data= $CurPageURL . '/job?p=' . $preId .'&vId=' .$vendorId;
                                    $data = $CurPageURL . '/companyDetails?p=' . $preId . '&vId=' . $vendorId;

                                    $to_encode = array(
                                        'status' => 1,
                                        'result' => "Success",
                                        'data' => $data
                                    );
                                } else {
                                    $to_encode = array(
                                        'status' => -1,
                                        'result' => "error",
                                        'data' => 'Error while creating interview structure step 3'
                                    );
                                }


                            } else {
                                $to_encode = array(
                                    'status' => -1,
                                    'result' => "error",
                                    'data' => 'Error while creating interview structure step 2'
                                );
                            }

                        } else {
                            $to_encode = array(
                                'status' => -1,
                                'result' => "error",
                                'data' => 'Error while creating interview structure'
                            );
                        }
                    }

                } else {

                    $insertingRole = mysqli_query($databaseConnection, "INSERT INTO relavant_role(`name`) VALUES ('" . $roleName . "')");

                    $vName = mysqli_fetch_assoc($validateVendor)['vendorName'];

                    $checkingCompany = mysqli_query($databaseConnection, "select * from aspiration_company where name='" . $vName . "'");

                    if (mysqli_num_rows($checkingCompany) <= 0) {

                        $insertingCompany = mysqli_query($databaseConnection, "INSERT INTO aspiration_company(`name`) VALUES ('" . $vName . "')");
                    }


                    $preInterviewInsert = mysqli_query($databaseConnection, "INSERT INTO preInterview(`company_id`, `categoryType`, `interviewLevel`, `assessmentParameter`,`interviewName`,`sectorId`,`productId`,`interviewStartDate`,`vendorId`,`workExperience`,`currentLocation`,`preferredWorkLocation`,`Language`,`jobType`,`currentCompany`,`currentProcess`,`processType`,`clientType`,`currentSalary`,`expectedSalary`,`noticePeriod`,`processPreference`,`shift`,`workLocationPreference`,`timeToCall`,`declaration`,`preferedJobType`,`joiningTimeline`,`JDsection`,`showJDsection`,`interviewExpireDate`,`targetAudience`) VALUES ((SELECT id FROM aspiration_company WHERE name='" . $vName . "'),'9','Medium','Communication Skill, Behavioural Skill, Concept Knowledge, Problem Solving skills, Coding SKill','" . addslashes($interviewName) . "',2,1,now(),'" . $vendorId . "','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','" . addslashes($jd) . "','Y','" . $iExpireDate . "','" . addslashes($Eligibility) . "')");

                    $preInterviewId = mysqli_query($databaseConnection, "SELECT id FROM preInterview ORDER BY id DESC LIMIT 1");

                    $preId = mysqli_fetch_assoc($preInterviewId)['id'];


                    if ($interviewStructureType == 1 && $preInterviewInsert) {

                        $sql = "INSERT INTO interviewStructure(`sectorId`, `companyId`, `roleId`, `sectionSequence`, `sectionId`, `noOfAnswer`, `noOfSkip`, `depthRequired`, `clusterLevel`, `preInterviewId`) VALUES ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'1','1','1','2','N','" . $level . "'),

                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'2','3','2','2','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1)),
                            
                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'2','4','2','2','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1)),
                            
                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'6','8','2','2','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1)),
                            
                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'4','6','1','2','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1)),
                            
                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'5','7','0','0','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1));";


                        $interviewStructureInsert = mysqli_query($databaseConnection, $sql);


                        if ($interviewStructureInsert) {
                            $scpsInsert = 0;

                            //for core subject 1 dropdown
                            for ($i = 0; $i < sizeOf($coreSubject1); $i++) {

                                $subjectId = mysqli_query($databaseConnection, "select id from favourite_subject where favourite_subject='" . $coreSubject1[$i] . "' ");

                                if (mysqli_num_rows($subjectId) > 0) {

                                    $sql2 = mysqli_query($databaseConnection, "INSERT INTO scps_transaction(`sector`,`company`,`position`,`subject`,`coreSubjectSequence`,`priority`,`dropdown`,`preInterviewId`,`subjectType`) VALUES ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),(select id from favourite_subject where favourite_subject='" . $coreSubject1[$i] . "'),'1','1',1,(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1),'technical')");

                                    $scpsInsert += 1;

                                }

                            }
                            //for core subject 2 drop down
                            for ($i = 0; $i < sizeOf($coreSubject2); $i++) {

                                $subjectId = mysqli_query($databaseConnection, "select id from favourite_subject where favourite_subject='" . $coreSubject2[$i] . "' ");

                                if (mysqli_num_rows($subjectId) > 0) {

                                    $sql2 = mysqli_query($databaseConnection, "INSERT INTO scps_transaction(`sector`,`company`,`position`,`subject`,`coreSubjectSequence`,`priority`,`dropdown`,`preInterviewId`,`subjectType`) VALUES ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),(select id from favourite_subject where favourite_subject='" . $coreSubject2[$i] . "'),'1','1',2,(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1),'technical')");

                                    $scpsInsert += 1;

                                }

                            }

                            if ($scpsInsert) {

                                // $data= $CurPageURL . '/companyDetailsx?a=null&preId=' . $preId .'&vId=' .$vendorId;
                                // $data= $CurPageURL . '/job?p=' . $preId .'&vId=' .$vendorId;
                                $data = $CurPageURL . '/companyDetails?p=' . $preId . '&vId=' . $vendorId;

                                $to_encode = array(
                                    'status' => 1,
                                    'result' => "Success",
                                    'data' => $data
                                );
                            } else {
                                $to_encode = array(
                                    'status' => -1,
                                    'result' => "error",
                                    'data' => 'Error while creating interview structure step 3'
                                );
                            }


                        } else {
                            $to_encode = array(
                                'status' => -1,
                                'result' => "error",
                                'data' => 'Error while creating interview structure step 2'
                            );
                        }

                    } else if ($interviewStructureType == 2 && $preInterviewInsert) {

                        $sql = "INSERT INTO interviewStructure(sectorId, companyId, roleId, sectionSequence, sectionId, noOfAnswer, noOfSkip, depthRequired, clusterLevel, preInterviewId) VALUES 
                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'1','1','1','2','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1)),
                            
                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'2','3','2','2','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1)),
                            
                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'2','4','2','2','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1)),
                            
                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'6','8','2','2','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1)),
                            
                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'3','5','2','2','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1)),
                            
                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'4','6','1','2','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1)),
                            
                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'5','7','0','0','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1));";


                        $interviewStructureInsert = mysqli_query($databaseConnection, $sql);


                        if ($interviewStructureInsert) {
                            $scpsInsert = 0;

                            //for core subject 1 dropdown
                            for ($i = 0; $i < sizeOf($coreSubject1); $i++) {

                                $subjectId = mysqli_query($databaseConnection, "select id from favourite_subject where favourite_subject='" . $coreSubject1[$i] . "' ");

                                if (mysqli_num_rows($subjectId) > 0) {

                                    $sql2 = mysqli_query($databaseConnection, "INSERT INTO scps_transaction(`sector`,`company`,`position`,`subject`,`coreSubjectSequence`,`priority`,`dropdown`,`preInterviewId`,`subjectType`) VALUES ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),(select id from favourite_subject where favourite_subject='" . $coreSubject1[$i] . "'),'1','1',1,(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1),'technical')");

                                    $scpsInsert += 1;

                                }

                            }
                            //for core subject 2 drop down
                            for ($i = 0; $i < sizeOf($coreSubject2); $i++) {

                                $subjectId = mysqli_query($databaseConnection, "select id from favourite_subject where favourite_subject='" . $coreSubject2[$i] . "' ");

                                if (mysqli_num_rows($subjectId) > 0) {

                                    $sql2 = mysqli_query($databaseConnection, "INSERT INTO scps_transaction(`sector`,`company`,`position`,`subject`,`coreSubjectSequence`,`priority`,`dropdown`,`preInterviewId`,`subjectType`) VALUES ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),(select id from favourite_subject where favourite_subject='" . $coreSubject2[$i] . "'),'1','1',2,(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1),'technical')");

                                    $scpsInsert += 1;

                                }

                            }

                            //for programming subject drop down
                            for ($i = 0; $i < sizeOf($programmingsubject); $i++) {

                                $subjectId = mysqli_query($databaseConnection, "select id from favourite_subject where favourite_subject='" . $programmingsubject[$i] . "'  ");

                                if (mysqli_num_rows($subjectId) > 0) {

                                    $sql2 = mysqli_query($databaseConnection, "INSERT INTO scps_transaction(`sector`,`company`,`position`,`subject`,`coreSubjectSequence`,`priority`,`dropdown`,`preInterviewId`,`subjectType`) VALUES ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),(select id from favourite_subject where favourite_subject='" . $programmingsubject[$i] . "'),'1','1',1,(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1),'coding')");

                                    $scpsInsert += 1;

                                }

                            }



                            if ($scpsInsert) {

                                // $data= $CurPageURL . '/companyDetailsx?a=null&preId=' . $preId .'&vId=' .$vendorId;

                                // $data= $CurPageURL . '/job?p=' . $preId .'&vId=' .$vendorId;
                                $data = $CurPageURL . '/companyDetails?p=' . $preId . '&vId=' . $vendorId;

                                $to_encode = array(
                                    'status' => 1,
                                    'result' => "Success",
                                    'data' => $data
                                );
                            } else {
                                $to_encode = array(
                                    'status' => -1,
                                    'result' => "error",
                                    'data' => 'Error while creating interview structure step 3'
                                );
                            }


                        } else {
                            $to_encode = array(
                                'status' => -1,
                                'result' => "error",
                                'data' => 'Error while creating interview structure step 2'
                            );
                        }


                    } else if ($interviewStructureType == 3 && $preInterviewInsert) {

                        $sql = "INSERT INTO interviewStructure(sectorId, companyId, roleId, sectionSequence, sectionId, noOfAnswer, noOfSkip, depthRequired, clusterLevel, preInterviewId) VALUES 
                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'1','1','1','2','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1)),
                            
                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'2','3','2','2','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1)),
                            
                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'3','5','2','2','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1)),
                            
                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'4','6','1','2','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1)),
                            
                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'5','7','0','0','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1));";


                        $interviewStructureInsert = mysqli_query($databaseConnection, $sql);


                        if ($interviewStructureInsert) {
                            $scpsInsert = 0;

                            //for core subject 1 dropdown
                            for ($i = 0; $i < sizeOf($coreSubject1); $i++) {

                                $subjectId = mysqli_query($databaseConnection, "select id from favourite_subject where favourite_subject='" . $coreSubject1[$i] . "'");

                                if (mysqli_num_rows($subjectId) > 0) {

                                    $sql2 = mysqli_query($databaseConnection, "INSERT INTO scps_transaction(`sector`,`company`,`position`,`subject`,`coreSubjectSequence`,`priority`,`dropdown`,`preInterviewId`,`subjectType`) VALUES ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),(select id from favourite_subject where favourite_subject='" . $coreSubject1[$i] . "'),'1','1',1,(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1),'technical')");

                                    $scpsInsert += 1;

                                }

                            }

                            //for programming subject drop down
                            for ($i = 0; $i < sizeOf($programmingsubject); $i++) {

                                $subjectId = mysqli_query($databaseConnection, "select id from favourite_subject where favourite_subject='" . $programmingsubject[$i] . "'  ");

                                if (mysqli_num_rows($subjectId) > 0) {

                                    $sql2 = mysqli_query($databaseConnection, "INSERT INTO scps_transaction(`sector`,`company`,`position`,`subject`,`coreSubjectSequence`,`priority`,`dropdown`,`preInterviewId`,`subjectType`) VALUES ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),(select id from favourite_subject where favourite_subject='" . $programmingsubject[$i] . "'),'1','1',1,(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1),'coding')");

                                    $scpsInsert += 1;

                                }

                            }



                            if ($scpsInsert) {
                                // $data= $CurPageURL . '/companyDetailsx?a=null&preId=' . $preId .'&vId=' .$vendorId;

                                // $data= $CurPageURL . '/job?p=' . $preId .'&vId=' .$vendorId;
                                $data = $CurPageURL . '/companyDetails?p=' . $preId . '&vId=' . $vendorId;

                                $to_encode = array(
                                    'status' => 1,
                                    'result' => "Success",
                                    'data' => $data
                                );
                            } else {
                                $to_encode = array(
                                    'status' => -1,
                                    'result' => "error",
                                    'data' => 'Error while creating interview structure step 3'
                                );
                            }


                        } else {
                            $to_encode = array(
                                'status' => -1,
                                'result' => "error",
                                'data' => 'Error while creating interview structure step 2'
                            );
                        }

                    } else if ($interviewStructureType == 4 && $preInterviewInsert) {

                        $sql = "INSERT INTO interviewStructure(sectorId, companyId, roleId, sectionSequence, sectionId, noOfAnswer, noOfSkip, depthRequired, clusterLevel, preInterviewId) VALUES 
                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'1','1','1','2','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1)),
                            
                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'2','3','2','2','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1)),
                                                        
                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'3','6','1','2','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1)),
                            
                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'4','7','0','0','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1));";


                        $interviewStructureInsert = mysqli_query($databaseConnection, $sql);


                        if ($interviewStructureInsert) {
                            $scpsInsert = 0;

                            //for core subject 1 dropdown
                            for ($i = 0; $i < sizeOf($coreSubject1); $i++) {

                                $subjectId = mysqli_query($databaseConnection, "select id from favourite_subject where favourite_subject='" . $coreSubject1[$i] . "'  ");

                                if (mysqli_num_rows($subjectId) > 0) {

                                    $sql2 = mysqli_query($databaseConnection, "INSERT INTO scps_transaction(`sector`,`company`,`position`,`subject`,`coreSubjectSequence`,`priority`,`dropdown`,`preInterviewId`,`subjectType`) VALUES ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),(select id from favourite_subject where favourite_subject='" . $coreSubject1[$i] . "'),'1','1',1,(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1),'technical')");

                                    $scpsInsert += 1;

                                }

                            }

                            if ($scpsInsert) {

                                // $data= $CurPageURL . '/companyDetailsx?a=null&preId=' . $preId .'&vId=' .$vendorId;
                                // $data= $CurPageURL . '/job?p=' . $preId .'&vId=' .$vendorId;
                                $data = $CurPageURL . '/companyDetails?p=' . $preId . '&vId=' . $vendorId;

                                $to_encode = array(
                                    'status' => 1,
                                    'result' => "Success",
                                    'data' => $data
                                );

                            } else {
                                $to_encode = array(
                                    'status' => -1,
                                    'result' => "error",
                                    'data' => 'Error while creating interview structure step 3'
                                );
                            }


                        } else {
                            $to_encode = array(
                                'status' => -1,
                                'result' => "error",
                                'data' => 'Error while creating interview structure step 2'
                            );
                        }


                    } else if ($interviewStructureType == 5 && $preInterviewInsert) {

                        $sql = "INSERT INTO interviewStructure(sectorId, companyId, roleId, sectionSequence, sectionId, noOfAnswer, noOfSkip, depthRequired, clusterLevel, preInterviewId) VALUES 
                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'1','1','1','2','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1)),
                            
                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'3','5','2','2','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1)),
                            
                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'4','6','1','2','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1)),
                            
                            ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),'5','7','0','0','N','" . $level . "',(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1));";


                        $interviewStructureInsert = mysqli_query($databaseConnection, $sql);


                        if ($interviewStructureInsert) {
                            $scpsInsert = 0;

                            //for core subject 1 dropdown
                            for ($i = 0; $i < sizeOf($programmingsubject); $i++) {

                                $subjectId = mysqli_query($databaseConnection, "select id from favourite_subject where favourite_subject='" . $programmingsubject[$i] . "'  ");

                                if (mysqli_num_rows($subjectId) > 0) {

                                    $sql2 = mysqli_query($databaseConnection, "INSERT INTO scps_transaction(`sector`,`company`,`position`,`subject`,`coreSubjectSequence`,`priority`,`dropdown`,`preInterviewId`,`subjectType`) VALUES ('2',(SELECT id FROM aspiration_company WHERE name='" . $vName . "'),(SELECT id FROM relavant_role WHERE name='" . $roleName . "'),(select id from favourite_subject where favourite_subject='" . $programmingsubject[$i] . "'),'1','1',1,(SELECT id FROM preInterview ORDER BY id DESC LIMIT 1),'coding')");

                                    $scpsInsert += 1;

                                }

                            }

                            if ($scpsInsert) {
                                // $data= $CurPageURL . '/companyDetailsx?a=null&preId=' . $preId .'&vId=' .$vendorId;
                                // $data= $CurPageURL . '/job?p=' . $preId .'&vId=' .$vendorId;
                                $data = $CurPageURL . '/companyDetails?p=' . $preId . '&vId=' . $vendorId;

                                $to_encode = array(
                                    'status' => 1,
                                    'result' => "Success",
                                    'data' => $data
                                );
                            } else {
                                $to_encode = array(
                                    'status' => -1,
                                    'result' => "error",
                                    'data' => 'Error while creating interview structure step 3'
                                );
                            }


                        } else {
                            $to_encode = array(
                                'status' => -1,
                                'result' => "error",
                                'data' => 'Error while creating interview structure step 2'
                            );
                        }

                    } else {
                        $to_encode = array(
                            'status' => -1,
                            'result' => "error",
                            'data' => 'Error while creating interview structure'
                        );
                    }
                }



            } else {
                $to_encode = array(
                    'status' => -1,
                    'result' => "error",
                    'data' => 'Your not authorised to access this'
                );

            }
        } else {
            $to_encode = array(
                'status' => -1,
                'result' => "error",
                'errorCode' => "Error in the given data"
            );
        }

    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "Error in the given data"
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['createAdaptiveInterview_Goprac_v2'])) {
    // v2 endpoint for New Job Creation with limited fields.

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if ($json) {

        $interviewStructure = '';
        $behavioral = array();
        $coreSubject1 = array();
        $coreSubject2 = array();
        $programmingsubject = array();
        $companyId = $json['companyId'];
        $roleId = $json['roleId'];
        $subjectIdValue = '';
        if (isset($json['subjectId'])) {
            if (is_array($json['subjectId'])) {
                $subjectIdValue = implode(',', array_filter(array_map('trim', $json['subjectId'])));
            } else {
                $subjectIdValue = trim($json['subjectId']);
            }
        }
        $subjectId = $subjectIdValue;
        $userId = $json['userId'];
        $validationState = $json['validationState'];
        $preId = '';

        $jd = $json['jobDescription'];

        if ($json['behavioral'] != '') {
            $behavioral = preg_split("/\,/", implode(",", $json['behavioral']));
        }

        if ($json['coreSubject1'] != '') {
            $coreSubject1 = preg_split("/\,/", implode(",", $json['coreSubject1']));
        }

        if ($json['coreSubject2'] != '') {
            $coreSubject2 = preg_split("/\,/", implode(",", $json['coreSubject2']));
        }

        if ($json['codingSubject'] != '') {
            $programmingsubject = preg_split("/\,/", implode(",", $json['codingSubject']));
        }

        $serviceType = isset($json['serviceType']) ? "'" . addslashes($json['serviceType']) . "'" : 'NULL';
        $JDsection = !empty(trim($json['jobDescription'])) ? "'" . addslashes($json['jobDescription']) . "'" : 'NULL';
        $JobWorkExperience = isset($json['iJobWorkExperience']) ? "'" . addslashes($json['iJobWorkExperience']) . "'" : 'NULL';

        $RecruiterEmail = isset($json['RecruiterEmail']) ? $json['RecruiterEmail'] : '';
        $pendingInterviews = isset($json['pendingInterviews']) ? $json['pendingInterviews'] : '';
        $JDupload = isset($json['JDupload']) ? $json['JDupload'] : '';
        $showJDsection = isset($json['showJDsectionCheck']) ? $json['showJDsectionCheck'] : 'Y';
        $Additional = isset($json['Additional']) ? $json['Additional'] : 'Y';
        $screeningQuestions = isset($json['screeningQuestions']) && $json['screeningQuestions'] == 'Y' ? 'Y' : 'N';
        $screeningQuestionRows = isset($json['jobScreeningQuestions']) && is_array($json['jobScreeningQuestions']) ? $json['jobScreeningQuestions'] : array();
        $normalizedScreeningQuestions = array();
        $allowedScreeningQuestionTypes = array('TEXT', 'NUMBER', 'YES_NO', 'SINGLE_SELECT');
        $preInterviewIdValue = isset($json['preInterviewId']) ? $json['preInterviewId'] : '';
        $attemptedCount = 0;

        if ($preInterviewIdValue != '') {
            $safeScreeningPreInterviewId = (int) $preInterviewIdValue;
            $filter1 = "select count(distinct(fr.id)) as attempted from feedback_request fr inner join interview i on i.id=fr.interviewId where i.preInterviewId='" . $safeScreeningPreInterviewId . "';";
            $filter1Result = mysqli_query($databaseConnection, $filter1);
            if ($filter1Result) {
                $row = mysqli_fetch_assoc($filter1Result);
                $attemptedCount = isset($row['attempted']) ? (int) $row['attempted'] : 0;
            }

            if ($attemptedCount > 0) {
                $existingScreeningFlagResult = mysqli_query($databaseConnection, "SELECT screeningQuestions FROM preInterview WHERE id = '" . $safeScreeningPreInterviewId . "' LIMIT 1");
                $existingScreeningQuestions = null;
                if ($existingScreeningFlagResult && mysqli_num_rows($existingScreeningFlagResult) > 0) {
                    $existingScreeningQuestions = mysqli_fetch_assoc($existingScreeningFlagResult)['screeningQuestions'];
                }

                if ($existingScreeningQuestions !== null) {
                    $screeningQuestions = $existingScreeningQuestions == 'Y' ? 'Y' : 'N';
                }
            }
        }

        foreach ($screeningQuestionRows as $screeningIndex => $screeningRow) {
            if (!is_array($screeningRow)) {
                continue;
            }

            $questionText = isset($screeningRow['questionText']) ? trim((string) $screeningRow['questionText']) : '';
            if ($questionText == '') {
                continue;
            }

            $questionType = isset($screeningRow['questionType']) ? strtoupper(trim((string) $screeningRow['questionType'])) : 'TEXT';
            if (!in_array($questionType, $allowedScreeningQuestionTypes)) {
                $to_encode = array(
                    'status' => -1,
                    'result' => "error",
                    'data' => 'Invalid screening question type at question ' . ($screeningIndex + 1)
                );
                echo json_encode($to_encode);
                exit();
            }

            $options = array();
            if ($questionType == 'SINGLE_SELECT') {
                if (isset($screeningRow['options']) && is_array($screeningRow['options'])) {
                    $options = $screeningRow['options'];
                } else if (isset($screeningRow['optionsJson'])) {
                    if (is_array($screeningRow['optionsJson'])) {
                        $options = $screeningRow['optionsJson'];
                    } else {
                        $decodedOptions = json_decode((string) $screeningRow['optionsJson'], true);
                        if (is_array($decodedOptions)) {
                            $options = $decodedOptions;
                        } else {
                            $options = explode(',', (string) $screeningRow['optionsJson']);
                        }
                    }
                }

                $cleanOptions = array();
                $seenOptions = array();
                foreach ($options as $option) {
                    $cleanOption = trim((string) $option);
                    $optionKey = strtolower($cleanOption);
                    if ($cleanOption != '' && !isset($seenOptions[$optionKey])) {
                        $seenOptions[$optionKey] = true;
                        $cleanOptions[] = $cleanOption;
                    }
                }
                $options = $cleanOptions;

                if ($attemptedCount == 0 && $screeningQuestions == 'Y' && count($options) < 2) {
                    $to_encode = array(
                        'status' => -1,
                        'result' => "error",
                        'data' => 'Please add at least two options for screening question ' . ($screeningIndex + 1)
                    );
                    echo json_encode($to_encode);
                    exit();
                }
            }

            $normalizedScreeningQuestions[] = array(
                'id' => isset($screeningRow['id']) ? (int) $screeningRow['id'] : 0,
                'questionText' => $questionText,
                'questionType' => $questionType,
                'optionsJson' => $questionType == 'SINGLE_SELECT' ? json_encode($options) : '',
                'sortOrder' => isset($screeningRow['sortOrder']) ? (int) $screeningRow['sortOrder'] : count($normalizedScreeningQuestions) + 1,
                'isActive' => isset($screeningRow['isActive']) && $screeningRow['isActive'] == 'N' ? 'N' : 'Y'
            );
        }

        if ($attemptedCount == 0 && $screeningQuestions == 'Y' && count($normalizedScreeningQuestions) == 0) {
            $to_encode = array(
                'status' => -1,
                'result' => "error",
                'data' => 'Please add at least one screening question'
            );
            echo json_encode($to_encode);
            exit();
        }

        $workExperiencePreference = !empty($json['workExperiencePreference']) ? "'" . addslashes(implode(', ', $json['workExperiencePreference'])) . "'" : "''";

        if ($preInterviewIdValue != '') {

            if ($attemptedCount > 0) {

            } else {
                $deleteScps = mysqli_query($databaseConnection, "delete from scps_transaction where preInterviewId='" . $preInterviewIdValue . "'");
                $deleteInterviewStructure = mysqli_query($databaseConnection, "delete from interviewStructure where preInterviewId='" . $preInterviewIdValue . "'");
            }

            $qq = "UPDATE preInterview SET roleId='" . $json['roleId'] . "', subjectId='" . $subjectIdValue . "', company_id = '" . implode(',', $json['companyId']) . "',interviewName = '" . addslashes($json['interviewName']) . "', interviewStartDate = '" . $json['interviewStartDate'] . "', interviewExpireDate = '" . $json['interviewEndDate'] . "', company_url = " . (empty(trim($json['companyUrl'])) ? 'NULL' : "'" . trim($json['companyUrl']) . "'") . ", JDsection = " . $JDsection . ", showJDsection = '" . $showJDsection . "',jobCategory = 'interview',
                serviceType=$serviceType ,RecruiterEmail='" . addslashes($RecruiterEmail) . "',pendingInterviews='" . $pendingInterviews . "',JDupload='" . addslashes($JDupload) . "',additionalJobDetails='" . $Additional . "'
                ,screeningQuestions='" . $screeningQuestions . "'
                WHERE id = '" . $preInterviewIdValue . "'";

            $updatePreInterview = mysqli_query($databaseConnection, $qq);

            if ($updatePreInterview) {
            } else {
                echo "Query encountered an error";
                echo "Error: " . mysqli_error($databaseConnection);
            }

            $preId = $preInterviewIdValue;

            $s8 = mysqli_query($databaseConnection, "SELECT * from profilePreferences where preInterviewId='$preId' and fieldName = 'workExperience'");
            if (mysqli_num_rows($s8) > 0) {
                $updatefield8 = mysqli_query($databaseConnection, "UPDATE profilePreferences SET fieldValue = " . $JobWorkExperience . ",preference=$workExperiencePreference  WHERE preInterviewId = '$preId' AND fieldName = 'workExperience'");
            } else {
                $insertfield8 = mysqli_query($databaseConnection, "INSERT INTO profilePreferences (preInterviewId, fieldName, fieldValue, preference) VALUES ('$preId', 'workExperience', $JobWorkExperience, $workExperiencePreference )");
            }

        } else {

            $qi = "INSERT INTO preInterview(`roleId` ,`subjectId` ,`company_id`, `categoryType`, `interviewLevel`, `interviewName`, `sectorId`, `productId`, `interviewStartDate`, `interviewExpireDate`, `company_url`, `duration`, JDsection, showJDsection,serviceType,RecruiterEmail,pendingInterviews,JDupload,additionalJobDetails,screeningQuestions,createdAt)
        VALUES ('" . $json['roleId'] . "','" . $subjectIdValue . "','" . implode(',', $json['companyId']) . "', '9', 'Medium', '" . addslashes($json['interviewName']) . "', 2, 1, '" . $json['interviewStartDate'] . "', '" . $json['interviewEndDate'] . "', " . (empty(trim($json['companyUrl'])) ? 'NULL' : "'" . trim($json['companyUrl']) . "'") . ",'', $JDsection, '" . $showJDsection . "', $serviceType,'" . addslashes($RecruiterEmail) . "','" . $pendingInterviews . "','" . addslashes($JDupload) . "','" . $Additional . "','" . $screeningQuestions . "',NOW())";

            $preInterviewInsert = mysqli_query($databaseConnection, $qi);

            if ($preInterviewInsert) {
                // echo "Insertion successful!";
            } else {
                echo "Insert Query encountered an error";
            }

            $preInterviewId = mysqli_query($databaseConnection, "SELECT id FROM preInterview ORDER BY id DESC LIMIT 1");
            $preId = mysqli_fetch_assoc($preInterviewId)['id'];

            $insertfield8 = mysqli_query($databaseConnection, "INSERT INTO profilePreferences (preInterviewId, fieldName, fieldValue, preference) VALUES ('$preId', 'workExperience', $JobWorkExperience,  $workExperiencePreference)");
        }

        if ($preId != '' && $attemptedCount == 0 && isset($json['jobScreeningQuestions']) && is_array($json['jobScreeningQuestions'])) {
            $existingScreeningQuestionIds = array();
            $existingScreeningQuestionsResult = mysqli_query($databaseConnection, "SELECT id FROM jobScreeningQuestions WHERE preInterviewId = '" . $preId . "'");
            if ($existingScreeningQuestionsResult) {
                while ($existingScreeningQuestion = mysqli_fetch_assoc($existingScreeningQuestionsResult)) {
                    $existingScreeningQuestionIds[] = (int) $existingScreeningQuestion['id'];
                }
            }

            $submittedScreeningQuestionIds = array();
            foreach ($normalizedScreeningQuestions as $screeningRow) {
                $screeningQuestionId = (int) $screeningRow['id'];
                $questionTextSql = mysqli_real_escape_string($databaseConnection, $screeningRow['questionText']);
                $questionTypeSql = mysqli_real_escape_string($databaseConnection, $screeningRow['questionType']);
                $optionsSql = $screeningRow['optionsJson'] != ''
                    ? "'" . mysqli_real_escape_string($databaseConnection, $screeningRow['optionsJson']) . "'"
                    : "NULL";
                $sortOrderSql = (int) $screeningRow['sortOrder'];
                $isActiveSql = $screeningRow['isActive'] == 'N' ? 'N' : 'Y';

                if ($screeningQuestionId > 0 && in_array($screeningQuestionId, $existingScreeningQuestionIds)) {
                    $updateScreeningQuestion = "UPDATE jobScreeningQuestions SET questionText = '" . $questionTextSql . "', questionType = '" . $questionTypeSql . "', optionsJson = " . $optionsSql . ", sortOrder = '" . $sortOrderSql . "', isActive = '" . $isActiveSql . "' WHERE id = '" . $screeningQuestionId . "' AND preInterviewId = '" . $preId . "'";
                    $updateScreeningQuestionResult = mysqli_query($databaseConnection, $updateScreeningQuestion);
                    if (!$updateScreeningQuestionResult) {
                        $to_encode = array(
                            'status' => -1,
                            'result' => "error",
                            'data' => 'Error while updating screening questions'
                        );
                        echo json_encode($to_encode);
                        exit();
                    }
                    $submittedScreeningQuestionIds[] = $screeningQuestionId;
                } else {
                    $insertScreeningQuestion = "INSERT INTO jobScreeningQuestions (preInterviewId, questionText, questionType, optionsJson, sortOrder, isActive, createdAt) VALUES ('" . $preId . "', '" . $questionTextSql . "', '" . $questionTypeSql . "', " . $optionsSql . ", '" . $sortOrderSql . "', '" . $isActiveSql . "', NOW())";
                    $insertScreeningQuestionResult = mysqli_query($databaseConnection, $insertScreeningQuestion);
                    if (!$insertScreeningQuestionResult) {
                        $to_encode = array(
                            'status' => -1,
                            'result' => "error",
                            'data' => 'Error while saving screening questions'
                        );
                        echo json_encode($to_encode);
                        exit();
                    }
                    $submittedScreeningQuestionIds[] = (int) mysqli_insert_id($databaseConnection);
                }
            }

            $screeningQuestionIdsToDisable = array_diff($existingScreeningQuestionIds, $submittedScreeningQuestionIds);
            if (count($screeningQuestionIdsToDisable) > 0) {
                $safeDisableIds = implode(',', array_map('intval', $screeningQuestionIdsToDisable));
                $disableScreeningQuestions = mysqli_query($databaseConnection, "UPDATE jobScreeningQuestions SET isActive = 'N' WHERE preInterviewId = '" . $preId . "' AND id IN (" . $safeDisableIds . ")");
                if (!$disableScreeningQuestions) {
                    $to_encode = array(
                        'status' => -1,
                        'result' => "error",
                        'data' => 'Error while deleting screening questions'
                    );
                    echo json_encode($to_encode);
                    exit();
                }
            }
        }

        if ($attemptedCount > 0) {
            $to_encode = array(
                'status' => 1,
                'result' => "Success",
                'data' => 'Interview Created Successfull'
            );
        } else {

            $interviewStructure = "INSERT INTO interviewStructure(`sectorId`, `companyId`, `roleId`, `sectionSequence`, `sectionId`, `noOfAnswer`, `noOfSkip`, `depthRequired`, `clusterLevel`,`preInterviewId`) VALUES";

            if (sizeof($behavioral) > 0) {
                $interviewStructure .= "('2','" . implode(',', $json['companyId']) . "','" . $json['roleId'] . "','1','1','2','2','N','" . $json['difficultyLevel'] . "','" . $preId . "'),";
            }

            if ($json['validationState'] != 0) {

                if (sizeof($coreSubject1) > 0) {
                    $interviewStructure .= "('2','" . implode(',', $json['companyId']) . "','" . $json['roleId'] . "','2','3','2','2','N','" . $json['coreSubject1Level'] . "','" . $preId . "'),";
                }

                if (sizeof($coreSubject2) > 0) {
                    $interviewStructure .= "('2','" . implode(',', $json['companyId']) . "','" . $json['roleId'] . "','2','4','2','2','N','" . $json['coreSubject2Level'] . "','" . $preId . "'),";
                }

                if (sizeof($coreSubject1) > 0) {
                    if ($json['validationState'] == 2) {
                        $interviewStructure .= "('2','" . implode(',', $json['companyId']) . "','" . $json['roleId'] . "','2','4','2','2','N','" . $json['coreSubject1Level'] . "','" . $preId . "'),";
                    }
                }

                if (sizeof($coreSubject2) > 0) {
                    if ($json['validationState'] == 2) {
                        $interviewStructure .= "('2','" . implode(',', $json['companyId']) . "','" . $json['roleId'] . "','2','4','2','2','N','" . $json['coreSubject2Level'] . "','" . $preId . "'),";
                    }
                }

                if ($json['validationState'] == 3) {
                    $interviewStructure .= "('2','" . implode(',', $json['companyId']) . "','" . $json['roleId'] . "','6','8','2','2','N','" . $json['coreSubject1Level'] . "','" . $preId . "'),";
                }

                if (sizeof($programmingsubject) > 0) {
                    $interviewStructure .= "('2','" . implode(',', $json['companyId']) . "','" . $json['roleId'] . "','3','5','2','2','N','" . $json['codingSubjectLevel'] . "','" . $preId . "'),";
                }
            }

            $interviewStructure .= "('2','" . implode(',', $json['companyId']) . "','" . $json['roleId'] . "','5','7','0','0','N','" . $json['difficultyLevel'] . "','" . $preId . "');";

            if ($preId) {
                $interviewStructureInsert = mysqli_query($databaseConnection, $interviewStructure);

                if ($interviewStructureInsert) {
                    $scpsInsert = 0;

                    if ($json['validationState'] != 0) {
                        if (sizeOf($coreSubject1) > 0) {
                            for ($i = 0; $i < sizeOf($coreSubject1); $i++) {

                                $topics = '';

                                if ($json['core1Topics'] != '') {
                                    $core1Topics = $json['core1Topics'];
                                    $core1Topics1 = str_replace('addmore', '', $core1Topics);
                                    $core1Topics1 = rtrim($core1Topics1, ',');

                                    $topic = mysqli_query($databaseConnection, "select distinct(subjectId) as subjectId,group_concat(distinct(topic_id)) as topic from questions where topic_id in(" . $core1Topics1 . ") and subjectId='" . $coreSubject1[$i] . "' group by subjectId");

                                    if (mysqli_num_rows($topic) > 0) {
                                        $topics = mysqli_fetch_assoc($topic)['topic'];
                                    }
                                }

                                $scpsInsertion = mysqli_query($databaseConnection, "INSERT INTO scps_transaction(`sector`,`company`,`position`,`subject`,`coreSubjectSequence`,`priority`,`dropdown`,`preInterviewId`,`subjectType`,`weightage`,`topics`) VALUES ('2','" . implode(',', $json['companyId']) . "','" . $json['roleId'] . "','" . $coreSubject1[$i] . "','1','1',1,'" . $preId . "','technical'," . $json['core1CutOff'] . ",NULLIF('" . $topics . "',''))");

                                if ($scpsInsertion) {
                                    $scpsInsert += 1;
                                }
                            }
                        }

                        if (sizeOf($coreSubject2) > 0) {
                            for ($j = 0; $j < sizeOf($coreSubject2); $j++) {

                                $topics = '';

                                if ($json['core2Topics'] != '') {
                                    $core2Topics = $json['core2Topics'];
                                    $core2Topics2 = str_replace('addmore', '', $core2Topics);
                                    $core2Topics2 = rtrim($core2Topics2, ',');

                                    $topic = mysqli_query($databaseConnection, "select distinct(subjectId) as subjectId,group_concat(distinct(topic_id)) as topic from questions where topic_id in(" . $core2Topics2 . ") and subjectId='" . $coreSubject2[$j] . "' group by subjectId");

                                    if (mysqli_num_rows($topic) > 0) {
                                        $topics = mysqli_fetch_assoc($topic)['topic'];
                                    }
                                }

                                $scpsInsertion = mysqli_query($databaseConnection, "INSERT INTO scps_transaction(`sector`,`company`,`position`,`subject`,`coreSubjectSequence`,`priority`,`dropdown`,`preInterviewId`,`subjectType`,`weightage`,`topics`) VALUES ('2','" . implode(',', $json['companyId']) . "','" . $json['roleId'] . "','" . $coreSubject2[$j] . "','1','1',2,'" . $preId . "','technical'," . $json['core2CutOff'] . ",NULLIF('" . $topics . "',''))");

                                if ($scpsInsertion) {
                                    $scpsInsert += 1;
                                }
                            }
                        }

                        if (sizeOf($programmingsubject) > 0) {
                            for ($k = 0; $k < sizeOf($programmingsubject); $k++) {

                                $topics = '';

                                if ($json['codingTopics'] != '') {
                                    $topic = mysqli_query($databaseConnection, "select distinct(subjectId) as subjectId,group_concat(distinct(topic_id)) as topic from questions where topic_id in(" . $json['codingTopics'] . ") and subjectId='" . $programmingsubject[$k] . "' group by subjectId");

                                    if (mysqli_num_rows($topic) > 0) {
                                        $topics = mysqli_fetch_assoc($topic)['topic'];
                                    }
                                }

                                $scpsInsertion = mysqli_query($databaseConnection, "INSERT INTO scps_transaction(`sector`,`company`,`position`,`subject`,`coreSubjectSequence`,`priority`,`dropdown`,`preInterviewId`,`subjectType`,`weightage`,`topics`) VALUES ('2','" . implode(',', $json['companyId']) . "','" . $json['roleId'] . "','" . $programmingsubject[$k] . "','1','1',1,'" . $preId . "','coding'," . $json['codingCutOff'] . ",NULLIF('" . $topics . "',''))");

                                if ($scpsInsertion) {
                                    $scpsInsert += 1;
                                }
                            }
                        }

                        if ($scpsInsert > 0) {
                            $to_encode = array(
                                'status' => 1,
                                'result' => "Success",
                                'data' => 'Interview Created Successfull'
                            );
                        } else {
                            $to_encode = array(
                                'status' => -1,
                                'result' => "error",
                                'data' => 'Error while creating interview structure at stage 3  (scps Insertion Inside 1)'
                            );
                        }

                    } else if ($json['validationState'] == 0) {

                        $scpsInsertion = mysqli_query($databaseConnection, "INSERT INTO scps_transaction(`sector`,`company`,`position`,`subject`,`coreSubjectSequence`,`priority`,`dropdown`,`preInterviewId`,`subjectType`) VALUES ('2','" . implode(',', $json['companyId']) . "','" . $json['roleId'] . "','0','1','1',1,'" . $preId . "','soft')");

                        $scpsInsert += 1;

                        if ($scpsInsert > 0) {
                            $to_encode = array(
                                'status' => 1,
                                'result' => "Success",
                                'data' => 'Interview Created Successfull'
                            );
                        } else {
                            $to_encode = array(
                                'status' => -1,
                                'result' => "error",
                                'data' => 'Error while creating interview structure at stage 3  (scps Insertion Inside 2)'
                            );
                        }

                    } else {
                        $to_encode = array(
                            'status' => -1,
                            'result' => "error",
                            'data' => 'Error while creating interview structure at stage 3  (scps Insertion outside)'
                        );
                    }

                } else {
                    $to_encode = array(
                        'status' => -1,
                        'result' => "error",
                        'data' => 'Error while creating interview structure at stage 2 (Interview Structure Insertion)'
                    );
                }

            } else {
                $to_encode = array(
                    'status' => -1,
                    'result' => "error",
                    'data' => 'Error while creating interview structure at stage 1 (preInterview Insertion)'
                );
            }

        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "Error in the given data"
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['createAdaptiveInterview_Goprac'])) {
    // This method is added by arun on 04 Jul 2023 for Goprac interview creation

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if ($json) {

        $interviewStructure = '';
        $behavioral = array();
        $coreSubject1 = array();
        $coreSubject2 = array();
        $programmingsubject = array();
        $companyId = $json['companyId'];
        $roleId = $json['roleId'];
        $subjectId = $json['subjectId'];
        $userId = $json['userId'];
        $validationState = $json['validationState'];
        $preId = '';

        $jd = $json['jobDescription'];
        // echo $jd ;

        if ($json['behavioral'] != '') {
            $behavioral = preg_split("/\,/", implode(",", $json['behavioral']));
        }

        if ($json['coreSubject1'] != '') {
            $coreSubject1 = preg_split("/\,/", implode(",", $json['coreSubject1']));
        }

        if ($json['coreSubject2'] != '') {
            $coreSubject2 = preg_split("/\,/", implode(",", $json['coreSubject2']));
        }

        if ($json['codingSubject'] != '') {
            $programmingsubject = preg_split("/\,/", implode(",", $json['codingSubject']));
        }

        $serviceType = isset($json['serviceType']) ? "'" . addslashes($json['serviceType']) . "'" : 'NULL';

        // $JobPitch=!empty(trim($json['iJobPitch'])) ? "'" . addslashes($json['iJobPitch']) . "'" : 'NULL';
        $JDsection = !empty(trim($json['jobDescription'])) ? "'" . addslashes($json['jobDescription']) . "'" : 'NULL';

        // $rolesAndResponsibilities = !empty(trim($json['rolesAndResponsibilities'])) ? "'" . addslashes($json['rolesAndResponsibilities']) . "'" : 'NULL';
        // $iClientInterviewProcess = !empty(trim($json['iClientInterviewProcess'])) ? "'" . addslashes($json['iClientInterviewProcess']) . "'" : 'NULL';
        $JobWorkExperience = isset($json['iJobWorkExperience']) ? "'" . addslashes($json['iJobWorkExperience']) . "'" : 'NULL';
        $SalaryRange = !empty(trim($json['iSalaryRange'])) ? "'" . addslashes($json['iSalaryRange']) . "'" : 'NULL';
        $VcompanySalaryRange = !empty(trim($json['VcompanySalaryRange'])) ? "'" . addslashes($json['VcompanySalaryRange']) . "'" : 'N';

        $iHeadcount = !empty(trim($json['iHeadcount'])) ? "'" . addslashes($json['iHeadcount']) . "'" : 'NULL';

        $outstation = !empty(trim($json['outstation'])) ? "'" . addslashes($json['outstation']) . "'" : 'NULL';
        $apmType = !empty(trim($json['apmType'])) ? "'" . addslashes($json['apmType']) . "'" : 'NULL';

        $employmentType = !empty(trim($json['employmentType'])) ? "'" . addslashes($json['employmentType']) . "'" : 'NULL';

        $bondAgreementRequired = !empty(trim($json['bondAgreementRequired'])) ? "'" . addslashes($json['bondAgreementRequired']) . "'" : 'NULL';

        $iStrength = !empty(trim($json['iStrength'])) ? "'" . addslashes($json['iStrength']) . "'" : 'NULL';

        $jobType = !empty($json['jobType']) ? "'" . addslashes(implode(', ', $json['jobType'])) . "'" : "''";
        // $processType = !empty($json['processType']) ? "'" . addslashes(implode(', ', $json['processType'])) . "'" : "''";
        // $currentProcess = !empty($json['currentProcess']) ? "'" . addslashes(implode(', ', $json['currentProcess'])) . "'" : "''";
        $iEmploymentType = !empty(trim($json['iEmploymentType'])) ? "'" . addslashes($json['iEmploymentType']) . "'" : 'NULL';
        $iWorkingDays = !empty(trim($json['iWorkingDays'])) ? "'" . addslashes($json['iWorkingDays']) . "'" : 'NULL';
        $iJobMode = !empty($json['iJobMode']) ? "'" . addslashes(implode(', ', $json['iJobMode'])) . "'" : "''";
        $ishift = !empty($json['ishift']) ? "'" . addslashes(implode(', ', $json['ishift'])) . "'" : "''";
        $inoticePeriod = !empty($json['inoticePeriod']) ? "'" . $json['inoticePeriod'] . "'" : "''";
        $JobLocation = !empty($json['iJobLocation']) ? "'" . addslashes(implode(', ', $json['iJobLocation'])) . "'" : "''";

        $CandidateDeclaration = $json['CandidateDeclaration'];
        $AdvancedProfileMatch = $json['AdvancedProfileMatch'];
        $RecruiterEmail = $json['RecruiterEmail'];
        $pendingInterviews = $json['pendingInterviews'];
        $promoteValue = $json['promoteValue'];
        $requestText = $json['requestText'];
        $JDupload = $json['JDupload'];
        // $JobLocation=!empty(trim($json['iJobLocation'])) ? "'" . addslashes($json['iJobLocation']) . "'" : 'NULL';    
        // $JobWorkExperience=!empty(trim($json['iJobWorkExperience'])) ? "'" . addslashes($json['iJobWorkExperience']) . "'" : 'NULL';
        // $JobWorkExperience=!empty(trim($json['iJobWorkExperience'])) ? "'" . addslashes($json['iJobWorkExperience']) . "'" : 'NULL';   
        // $skill=!empty($json['skill']) ? "'" . addslashes(implode(', ', $json['skill'])) . "'" : "''";

        // $industryTypeCheck = $json['industryTypeCheck'];
        // $skillsCheck = $json['skillsCheck'];
        // $noticePeriodCheck = $json['noticePeriodCheck'];
        // $resumeCheck = $json['resumeCheck'];
        // $declarationCheck = $json['declarationCheck'];

        // $workExperienceCheck = $json['workExperienceCheck'];
        // $currentSalaryCheck = $json['currentSalaryCheck'];
        // $expectedSalaryCheck = $json['expectedSalaryCheck'];

        // $shiftCheck = $json['shiftCheck'];
        // $processTypeCheck = $json['processTypeCheck'];
        // $currentProcessCheck = $json['currentProcessCheck'];
        // $jobModeCheck = $json['jobModeCheck'];
        // $currentLocationCheck = $json['currentLocationCheck'];

        // showJDsectionCheck:showJDsectionCheck,

        $showJDsection = $json['showJDsectionCheck'];
        $Additional = $json['Additional'];

        $cEmployment = $json['cEmployment'];
        $cWorkingDays = $json['cWorkingDays'];
        $cJobMode = $json['cJobMode'];
        $cJobShift = $json['cJobShift'];
        $cCompanyJobLoc = $json['cCompanyJobLoc'];

        $aCandidateResume = $json['aCandidateResume'];
        $aCandidateNoticePeriod = $json['aCandidateNoticePeriod'];
        $aCandidateTotalWorkExp = $json['aCandidateTotalWorkExp'];
        $aCandidateCurrentLocation = $json['aCandidateCurrentLocation'];
        $aCandidateCurrentSalary = $json['aCandidateCurrentSalary'];
        $aCandidateExpectedSalary = $json['aCandidateExpectedSalary'];
        $aCandidateCurrentCompany = $json['aCandidateCurrentCompany'];

        $jobTypePreference = !empty($json['jobTypePreference']) ? "'" . addslashes(implode(', ', $json['jobTypePreference'])) . "'" : "''";
        // $currentProcessPreference = !empty($json['currentProcessPreference']) ? "'" . addslashes(implode(', ', $json['currentProcessPreference'])) . "'" : "''";
        // $processTypePreference = !empty($json['processTypePreference']) ? "'" . addslashes(implode(', ', $json['processTypePreference'])) . "'" : "''";
        $workExperiencePreference = !empty($json['workExperiencePreference']) ? "'" . addslashes(implode(', ', $json['workExperiencePreference'])) . "'" : "''";
        $noticePeriodPreference = !empty($json['noticePeriodPreference']) ? "'" . addslashes(implode(', ', $json['noticePeriodPreference'])) . "'" : "''";
        $shiftsPreference = !empty($json['shiftsPreference']) ? "'" . addslashes(implode(', ', $json['shiftsPreference'])) . "'" : "''";
        $currentLocationPreference = !empty($json['currentLocationPreference']) ? "'" . addslashes(implode(', ', $json['currentLocationPreference'])) . "'" : "''";
        // $skillsPreference = !empty($json['skillsPreference']) ? "'" . addslashes(implode(', ', $json['skillsPreference'])) . "'" : "''";
        $currentSalaryPreference = !empty($json['currentSalaryPreference']) ? "'" . addslashes(implode(', ', $json['currentSalaryPreference'])) . "'" : "''";
        $workLocationPreferences = !empty($json['workLocationPreferences']) ? "'" . addslashes(implode(', ', $json['workLocationPreferences'])) . "'" : "''";

        // $requiredSkills = !empty($json['requiredSkills']) ? "'" . addslashes(implode(', ', $json['requiredSkills'])) . "'" : "''";

        // $apmReady = !empty($json['apmReady']) && $json['apmReady'] == 'Y' ? ",apmReady='Y'" : "";


        $apmReady = !empty($json['apmReady']) ? "'" . $json['apmReady'] . "'" : 'NULL';


        // $roleDepSubDepId = !empty($json['roleDepSubDepId']) ? "'" . $json['roleDepSubDepId'] . "'" : "''";
        //$requiredSkills = !empty($json['requiredSkills']) ? "'" . $json['requiredSkills'] . "'" : "''"; 
        $requiredSkills = !empty($json['requiredSkills']) ? "'" . addslashes(implode(', ', $json['requiredSkills'])) . "'" : "''";
        $skillText = !empty($json['skillText']) ? "'" . $json['skillText'] . "'" : 'NULL';
        $ultraMandatorySkill = !empty($json['ultraMandatorySkill']) ? "'" . addslashes(implode(', ', $json['ultraMandatorySkill'])) . "'" : "''";
        $goodToHaveSkill = !empty($json['goodToHaveSkill']) ? "'" . addslashes(implode(', ', $json['goodToHaveSkill'])) . "'" : "''";

        // echo $apmReady;
        // print_r($requiredSkills);
        // exit();


        $filter1 = "select count(distinct(fr.id)) as attempted from feedback_request fr inner join interview i on i.id=fr.interviewId where i.preInterviewId='" . $json['preInterviewId'] . "';";
        $filter1Result = mysqli_query($databaseConnection, $filter1);
        $row = mysqli_fetch_assoc($filter1Result);
        $attemptedCount = $row['attempted'];
        // echo "SQL Query: " . $filter1 . "<br>";
        // echo "Attempted Count: " . $attemptedCount . "<br>";
        if ($json['preInterviewId'] != '') {

            if ($attemptedCount > 0) {

            } else {

                $deleteScps = mysqli_query($databaseConnection, "delete from scps_transaction where preInterviewId='" . $json['preInterviewId'] . "'");
                $deleteInterviewStructure = mysqli_query($databaseConnection, "delete from interviewStructure where preInterviewId='" . $json['preInterviewId'] . "'");
            }
            //Akash JDsection 10/26/2023


            $qq = "UPDATE preInterview SET VcompanySalaryRange=" . $VcompanySalaryRange . ", roleId='" . $json['roleId'] . "', subjectId='" . $json['subjectId'] . "', company_id = '" . implode(',', $json['companyId']) . "',interviewName = '" . addslashes($json['interviewName']) . "', interviewStartDate = '" . $json['interviewStartDate'] . "', interviewExpireDate = '" . $json['interviewEndDate'] . "', company_url = " . (empty(trim($json['companyUrl'])) ? 'NULL' : "'" . trim($json['companyUrl']) . "'") . ", JDsection = " . $JDsection . ", showJDsection = '" . $showJDsection . "',jobCategory = 'interview' , iStrength = " . $iStrength . ", iWorkingDays = " . $iWorkingDays . ", iHeadcount = " . $iHeadcount . ", outstationFlag = " . $outstation . ", apmType = " . $apmType . ", employmentType = " . $employmentType . ", bondAgreementRequired = " . $bondAgreementRequired . ", iEmploymentType = " . $iEmploymentType . ",
                serviceType=$serviceType ,CandidateDeclaration='" . $CandidateDeclaration . "',AdvancedProfileMatch='" . $AdvancedProfileMatch . "',RecruiterEmail='" . $RecruiterEmail . "',pendingInterviews='" . $pendingInterviews . "',requestText='" . $requestText . "',JDupload='" . $JDupload . "',additionalJobDetails='" . $Additional . "',apmReady=" . $apmReady . ",requiredSkills=" . $requiredSkills . ",skillText=" . $skillText . ",ultraMandatorySkill=" . $ultraMandatorySkill . ",goodToHaveSkill=" . $goodToHaveSkill . ",VemploymentType='" . $cEmployment . "',VworkingDays='" . $cWorkingDays . "',vcdJobShift='" . $cJobShift . "',vcdJobMode='" . $cJobMode . "',vcdjobLocation='" . $cCompanyJobLoc . "',Vresume='" . $aCandidateResume . "',vcdJobNoticePeriod='" . $aCandidateNoticePeriod . "',VsalaryRange='" . $aCandidateCurrentSalary . "',VworkExperienceRange='" . $aCandidateTotalWorkExp . "',VcurrentLocation='" . $aCandidateCurrentLocation . "',VcurrentCompany='" . $aCandidateCurrentCompany . "',VexpectedSalary='" . $aCandidateExpectedSalary . "'
                WHERE id = '" . $json['preInterviewId'] . "'";


            // echo $qq;
            // exit();
            $updatePreInterview = mysqli_query($databaseConnection, $qq);

            if ($updatePreInterview) {
            } else {
                echo "Query encountered an error";
                echo "Error: " . mysqli_error($databaseConnection);
            }

            $preId = $json['preInterviewId'];



            $sq1 = "SELECT * from profilePreferences where preInterviewId='$preId' and fieldName = 'jobType'";
            $s1 = mysqli_query($databaseConnection, $sq1);
            if (mysqli_num_rows($s1) > 0) {
                $q2 = "UPDATE profilePreferences SET fieldValue =" . $jobType . ",preference=$jobTypePreference WHERE preInterviewId = '$preId' AND fieldName = 'jobType'  ;";
                $updatefield1 = mysqli_query($databaseConnection, $q2);
            } else {
                $q1 = "INSERT INTO profilePreferences (preInterviewId, fieldName, fieldValue, preference) VALUES ('$preId', 'jobType', $jobType, $jobTypePreference)";
                $insertfield1 = mysqli_query($databaseConnection, $q1);
            }


            $s2 = mysqli_query($databaseConnection, "SELECT * from profilePreferences where preInterviewId='$preId' and fieldName = 'shift'");
            if (mysqli_num_rows($s2) > 0) {
                $updatefield2 = mysqli_query($databaseConnection, "UPDATE profilePreferences SET fieldValue =" . $ishift . ",preference=$shiftsPreference WHERE preInterviewId = '$preId' AND fieldName = 'shift'");
            } else {
                $insertfield2 = mysqli_query($databaseConnection, "INSERT INTO profilePreferences (preInterviewId, fieldName, fieldValue, preference) VALUES ('$preId', 'shift', $ishift, $shiftsPreference)");
            }

            $s3 = mysqli_query($databaseConnection, "SELECT * from profilePreferences where preInterviewId='$preId' and fieldName = 'noticePeriod'");
            if (mysqli_num_rows($s3) > 0) {
                $updatefield3 = mysqli_query($databaseConnection, "UPDATE profilePreferences SET fieldValue =" . $inoticePeriod . " ,preference=$noticePeriodPreference WHERE preInterviewId = '$preId' AND fieldName = 'noticePeriod'");
            } else {
                $insertfield3 = mysqli_query($databaseConnection, "INSERT INTO profilePreferences (preInterviewId, fieldName, fieldValue, preference) VALUES ('$preId', 'noticePeriod', $inoticePeriod, $noticePeriodPreference)");
            }

            $s6 = mysqli_query($databaseConnection, "SELECT * from profilePreferences where preInterviewId='$preId' and fieldName = 'currentLocation'");
            if (mysqli_num_rows($s6) > 0) {
                $updatefield6 = mysqli_query($databaseConnection, "UPDATE profilePreferences SET fieldValue = " . $JobLocation . " ,preference=$currentLocationPreference  WHERE preInterviewId = '$preId' AND fieldName = 'currentLocation'");
            } else {
                $insertfield6 = mysqli_query($databaseConnection, "INSERT INTO profilePreferences (preInterviewId, fieldName, fieldValue, preference) VALUES ('$preId', 'currentLocation', $JobLocation, $currentLocationPreference )");
            }

            $s7 = mysqli_query($databaseConnection, "SELECT * from profilePreferences where preInterviewId='$preId' and fieldName = 'currentSalary'");
            if (mysqli_num_rows($s7) > 0) {
                $updatefield7 = mysqli_query($databaseConnection, "UPDATE profilePreferences SET fieldValue = " . $SalaryRange . " ,preference=$currentSalaryPreference  WHERE preInterviewId = '$preId' AND fieldName = 'currentSalary'");
            } else {
                $insertfield7 = mysqli_query($databaseConnection, "INSERT INTO profilePreferences (preInterviewId, fieldName, fieldValue, preference) VALUES ('$preId', 'currentSalary', $SalaryRange, $currentSalaryPreference )");
            }

            $s8 = mysqli_query($databaseConnection, "SELECT * from profilePreferences where preInterviewId='$preId' and fieldName = 'workExperience'");
            if (mysqli_num_rows($s8) > 0) {
                $updatefield8 = mysqli_query($databaseConnection, "UPDATE profilePreferences SET fieldValue = " . $JobWorkExperience . ",preference=$workExperiencePreference  WHERE preInterviewId = '$preId' AND fieldName = 'workExperience'");
            } else {
                $insertfield8 = mysqli_query($databaseConnection, "INSERT INTO profilePreferences (preInterviewId, fieldName, fieldValue, preference) VALUES ('$preId', 'workExperience', $JobWorkExperience, $workExperiencePreference )");
            }

            $s9 = mysqli_query($databaseConnection, "SELECT * from profilePreferences where preInterviewId='$preId' and fieldName = 'workLocationPreference'");
            if (mysqli_num_rows($s9) > 0) {
                $updatefield9 = mysqli_query($databaseConnection, "UPDATE profilePreferences SET fieldValue = " . $iJobMode . ",preference=$workLocationPreferences  WHERE preInterviewId = '$preId' AND fieldName = 'workLocationPreference'");
            } else {
                $insertfield9 = mysqli_query($databaseConnection, "INSERT INTO profilePreferences (preInterviewId, fieldName, fieldValue, preference) VALUES ('$preId', 'workLocationPreference', $iJobMode, $workLocationPreferences)");
            }




            if ($promoteValue != '') {
                $parts = explode(",", $promoteValue);
                $quotedParts = array_map(function ($part) {
                    return "'" . $part . "'";
                }, $parts);
                $promoteValueForDelete = implode(",", $quotedParts);

                $deleteQuery = "DELETE FROM promotion WHERE preInterviewId = '$preId' AND jobpromotion not in(" . $promoteValueForDelete . ") ";
            } else {
                $deleteQuery = "DELETE FROM promotion WHERE (preInterviewId = '$preId' AND jobpromotion = 'S') OR (preInterviewId = '$preId' AND jobpromotion = 'L')  OR (preInterviewId = '$preId' AND jobpromotion = 'N')  OR (preInterviewId = '$preId' AND jobpromotion = 'G')";
            }
            $deleteResult = mysqli_query($databaseConnection, $deleteQuery);

            if (!$deleteResult) {
                echo "Error deleting records: " . mysqli_error($databaseConnection);
            } else {
                if ($promoteValue != '') {
                    $promoteValues = explode(",", $promoteValue);

                    foreach ($promoteValues as $promotion) {
                        $promotion = mysqli_real_escape_string($databaseConnection, trim($promotion));
                        if ($promotion == "N") {
                            $checkQuery = "SELECT COUNT(*) AS count FROM promotion WHERE preInterviewid = '$preId' AND jobpromotion = '$promotion'";
                            $checkResult = mysqli_query($databaseConnection, $checkQuery);
                            $rowCount = mysqli_fetch_assoc($checkResult)['count'];
                            if ($rowCount == 0) {
                                $insertQuery = "INSERT INTO promotion (preInterviewId, jobpromotion,uploadFlag) VALUES ('$preId', '$promotion',1)";
                                $insertResult = mysqli_query($databaseConnection, $insertQuery);

                                if (!$insertResult) {
                                    echo "Error inserting record: " . mysqli_error($databaseConnection);
                                }
                            } else {
                                $updateQuery = "UPDATE promotion SET jobpromotion ='$promotion',uploadFlag=1 WHERE preInterviewId = '$preId' AND jobpromotion = '$promotion' ";
                                $updateResult = mysqli_query($databaseConnection, $updateQuery);

                                if (!$updateResult) {
                                    echo "Error updating record: " . mysqli_error($databaseConnection);
                                }
                            }
                        } else {
                            $checkQuery = "SELECT COUNT(*) AS count FROM promotion WHERE preInterviewid = '$preId' AND jobpromotion = '$promotion'";
                            $checkResult = mysqli_query($databaseConnection, $checkQuery);
                            $rowCount = mysqli_fetch_assoc($checkResult)['count'];
                            if ($rowCount == 0) {
                                $insertQuery = "INSERT INTO promotion (preInterviewId, jobpromotion) VALUES ('$preId', '$promotion')";
                                $insertResult = mysqli_query($databaseConnection, $insertQuery);

                                if (!$insertResult) {
                                    echo "Error inserting record: " . mysqli_error($databaseConnection);
                                }
                            } else {
                                $updateQuery = "UPDATE promotion SET jobpromotion ='$promotion' WHERE preInterviewId = '$preId' AND jobpromotion = '$promotion' ";
                                $updateResult = mysqli_query($databaseConnection, $updateQuery);

                                if (!$updateResult) {
                                    echo "Error updating record: " . mysqli_error($databaseConnection);
                                }
                            }
                        }
                    }
                }
            }

        } else {
            //Akash JDsection 10/26/2023                                            



            $qi = "INSERT INTO preInterview(`VcompanySalaryRange`,`roleId` ,`subjectId` ,`company_id`, `categoryType`, `interviewLevel`, `interviewName`, `sectorId`, `productId`, `interviewStartDate`, `interviewExpireDate`, `company_url`, `duration`, JDsection, showJDsection, iStrength, iWorkingDays, iHeadcount,outstationFlag, iEmploymentType,serviceType,CandidateDeclaration,AdvancedProfileMatch ,RecruiterEmail,pendingInterviews,requestText,JDupload,additionalJobDetails,apmReady,createdAt,requiredSkills,skillText,ultraMandatorySkill,goodToHaveSkill,apmType,employmentType,bondAgreementRequired,VemploymentType,VworkingDays,vcdJobShift,vcdJobMode,vcdjobLocation,Vresume,vcdJobNoticePeriod,VsalaryRange,VworkExperienceRange,VcurrentLocation,VcurrentCompany,VexpectedSalary)
        VALUES ($VcompanySalaryRange,'" . $json['roleId'] . "','" . $json['subjectId'] . "','" . implode(',', $json['companyId']) . "', '9', 'Medium', '" . addslashes($json['interviewName']) . "', 2, 1, '" . $json['interviewStartDate'] . "', '" . $json['interviewEndDate'] . "', " . (empty(trim($json['companyUrl'])) ? 'NULL' : "'" . trim($json['companyUrl']) . "'") . ",'', $JDsection, 'Y', $iStrength,$iWorkingDays,$iHeadcount,$outstation, $iEmploymentType, $serviceType,'" . $CandidateDeclaration . "','" . $AdvancedProfileMatch . "','" . $RecruiterEmail . "','" . $pendingInterviews . "' ,'" . $requestText . "','" . $JDupload . "','" . $Additional . "' ," . $apmReady . ",NOW()," . $requiredSkills . "," . $skillText . "," . $ultraMandatorySkill . "," . $goodToHaveSkill . "," . $apmType . "," . $employmentType . "," . $bondAgreementRequired . ",'" . $cEmployment . "','" . $cWorkingDays . "','" . $cJobShift . "','" . $cJobMode . "','" . $cCompanyJobLoc . "','" . $aCandidateResume . "','" . $aCandidateNoticePeriod . "','" . $aCandidateCurrentSalary . "','" . $aCandidateTotalWorkExp . "','" . $aCandidateCurrentLocation . "','" . $aCandidateCurrentCompany . "','" . $aCandidateExpectedSalary . "')";


            // echo $qi;


            $preInterviewInsert = mysqli_query($databaseConnection, $qi);

            if ($preInterviewInsert) {
                // echo "Insertion successful!";
            } else {
                echo "Insert Query encountered an error";
                // echo "Error: " . mysqli_error($databaseConnection);
            }
            // showJDsectionCheck:showJDsectionCheck,


            $preInterviewId = mysqli_query($databaseConnection, "SELECT id FROM preInterview ORDER BY id DESC LIMIT 1");

            $preId = mysqli_fetch_assoc($preInterviewId)['id'];


            $q1 = "INSERT INTO profilePreferences (preInterviewId, fieldName, fieldValue, preference) VALUES ('$preId', 'jobType', $jobType,$jobTypePreference)";
            $insertfield1 = mysqli_query($databaseConnection, $q1);
            $insertfield2 = mysqli_query($databaseConnection, "INSERT INTO profilePreferences (preInterviewId, fieldName, fieldValue, preference) VALUES ('$preId', 'shift', $ishift,  $shiftsPreference)");
            $insertfield3 = mysqli_query($databaseConnection, "INSERT INTO profilePreferences (preInterviewId, fieldName, fieldValue, preference) VALUES ('$preId', 'noticePeriod', $inoticePeriod,  $noticePeriodPreference )");

            // $insertfield4 = mysqli_query($databaseConnection, "INSERT INTO profilePreferences (preInterviewId, fieldName, fieldValue, preference) VALUES ('$preId', 'processType', $processType,  $processTypePreference)");
            // $insertfield5 = mysqli_query($databaseConnection, "INSERT INTO profilePreferences (preInterviewId, fieldName, fieldValue, preference) VALUES ('$preId', 'currentProcess', $currentProcess,   $currentProcessPreference)");        
            $insertfield6 = mysqli_query($databaseConnection, "INSERT INTO profilePreferences (preInterviewId, fieldName, fieldValue, preference) VALUES ('$preId', 'currentLocation', $JobLocation,  $currentLocationPreference)");
            $insertfield7 = mysqli_query($databaseConnection, "INSERT INTO profilePreferences (preInterviewId, fieldName, fieldValue, preference) VALUES ('$preId', 'currentSalary', $SalaryRange,   $currentSalaryPreference)");
            $insertfield8 = mysqli_query($databaseConnection, "INSERT INTO profilePreferences (preInterviewId, fieldName, fieldValue, preference) VALUES ('$preId', 'workExperience', $JobWorkExperience,  $workExperiencePreference)");
            $insertfield9 = mysqli_query($databaseConnection, "INSERT INTO profilePreferences (preInterviewId, fieldName, fieldValue, preference) VALUES ('$preId', 'workLocationPreference', $iJobMode,  $workLocationPreferences)");

            // $insertfield10 = mysqli_query($databaseConnection, "INSERT INTO profilePreferences (preInterviewId, fieldName, fieldValue) VALUES ('$preId', 'depId', $department)");
            // $insertfield11 = mysqli_query($databaseConnection, "INSERT INTO profilePreferences (preInterviewId, fieldName, fieldValue) VALUES ('$preId', 'subDepId', $subdepartment)");

            if ($promoteValue != null && $promoteValue != '') {
                $promoteValues = explode(",", $promoteValue);


                foreach ($promoteValues as $promotion) {
                    $promotion = mysqli_real_escape_string($databaseConnection, trim($promotion));
                    if ($promotion == "N") {
                        $insertQuery = "INSERT INTO promotion (preInterviewId, jobpromotion, uploadFlag) VALUES ('$preId', '$promotion', 1)";
                    } else {
                        $insertQuery = "INSERT INTO promotion (preInterviewId, jobpromotion) VALUES ('$preId', '$promotion')";
                    }
                    $insertResult = mysqli_query($databaseConnection, $insertQuery);

                    if (!$insertResult) {
                        echo "Error inserting record: " . mysqli_error($databaseConnection);
                    }
                }
            }

        }

        if ($attemptedCount > 0) {
            $to_encode = array(
                'status' => 1,
                'result' => "Success",
                'data' => 'Interview Created Successfull'
            );
        } else {

            $interviewStructure = "INSERT INTO interviewStructure(`sectorId`, `companyId`, `roleId`, `sectionSequence`, `sectionId`, `noOfAnswer`, `noOfSkip`, `depthRequired`, `clusterLevel`,`preInterviewId`) VALUES";

            if (sizeof($behavioral) > 0) {

                $interviewStructure .= "('2','" . implode(',', $json['companyId']) . "','" . $json['roleId'] . "','1','1','2','2','N','" . $json['difficultyLevel'] . "','" . $preId . "'),";

            }

            if ($json['validationState'] != 0) {

                if (sizeof($coreSubject1) > 0) {

                    $interviewStructure .= "('2','" . implode(',', $json['companyId']) . "','" . $json['roleId'] . "','2','3','2','2','N','" . $json['coreSubject1Level'] . "','" . $preId . "'),";
                }

                if (sizeof($coreSubject2) > 0) {

                    $interviewStructure .= "('2','" . implode(',', $json['companyId']) . "','" . $json['roleId'] . "','2','4','2','2','N','" . $json['coreSubject2Level'] . "','" . $preId . "'),";

                }
                //commented by shrikant :15/1/2024
                // else if($json['validationState']==2){

                //     $interviewStructure .="('2','".implode(',',$json['companyId'])."','".implode(',',$json['roleId'])."','2','4','2','2','N','".$json['coreSubject1Level']."','".$preId."'),";
                // }
                //added by shrikant :15/1/2024
                if (sizeof($coreSubject1) > 0) {
                    if ($json['validationState'] == 2) {

                        $interviewStructure .= "('2','" . implode(',', $json['companyId']) . "','" . $json['roleId'] . "','2','4','2','2','N','" . $json['coreSubject1Level'] . "','" . $preId . "'),";
                    }
                }
                if (sizeof($coreSubject2) > 0) {
                    if ($json['validationState'] == 2) {

                        $interviewStructure .= "('2','" . implode(',', $json['companyId']) . "','" . $json['roleId'] . "','2','4','2','2','N','" . $json['coreSubject2Level'] . "','" . $preId . "'),";
                    }
                }

                if ($json['validationState'] == 3) {

                    $interviewStructure .= "('2','" . implode(',', $json['companyId']) . "','" . $json['roleId'] . "','6','8','2','2','N','" . $json['coreSubject1Level'] . "','" . $preId . "'),";
                }


                if (sizeof($programmingsubject) > 0) {

                    $interviewStructure .= "('2','" . implode(',', $json['companyId']) . "','" . $json['roleId'] . "','3','5','2','2','N','" . $json['codingSubjectLevel'] . "','" . $preId . "'),";
                }


            }

            // $interviewStructure .="('2','".implode(',',$json['companyId'])."','".implode(',',$json['roleId'])."','4','6','1','2','N','".$json['difficultyLevel']."','".$preId."'),";

            $interviewStructure .= "('2','" . implode(',', $json['companyId']) . "','" . $json['roleId'] . "','5','7','0','0','N','" . $json['difficultyLevel'] . "','" . $preId . "');";


            if ($preId) {
                // echo $interviewStructure;

                $interviewStructureInsert = mysqli_query($databaseConnection, $interviewStructure);

                if ($interviewStructureInsert) {
                    $scpsInsert = 0;

                    if ($json['validationState'] != 0) {
                        //for core subject 1 dropdown
                        if (sizeOf($coreSubject1) > 0) {
                            for ($i = 0; $i < sizeOf($coreSubject1); $i++) {


                                $topics = '';

                                if ($json['core1Topics'] != '') {

                                    $core1Topics = $json['core1Topics'];

                                    $core1Topics1 = str_replace('addmore', '', $core1Topics);
                                    $core1Topics1 = rtrim($core1Topics1, ',');

                                    $topic = mysqli_query($databaseConnection, "select distinct(subjectId) as subjectId,group_concat(distinct(topic_id)) as topic from questions where topic_id in(" . $core1Topics1 . ") and subjectId='" . $coreSubject1[$i] . "' group by subjectId");

                                    if (mysqli_num_rows($topic) > 0) {

                                        $topics = mysqli_fetch_assoc($topic)['topic'];
                                    }

                                }


                                $scpsInsertion = mysqli_query($databaseConnection, "INSERT INTO scps_transaction(`sector`,`company`,`position`,`subject`,`coreSubjectSequence`,`priority`,`dropdown`,`preInterviewId`,`subjectType`,`weightage`,`topics`) VALUES ('2','" . implode(',', $json['companyId']) . "','" . $json['roleId'] . "','" . $coreSubject1[$i] . "','1','1',1,'" . $preId . "','technical'," . $json['core1CutOff'] . ",NULLIF('" . $topics . "',''))");

                                if ($scpsInsertion) {

                                    $scpsInsert += 1;
                                }

                            }
                        }

                        //for core subject 2 dropdown
                        if (sizeOf($coreSubject2) > 0) {
                            for ($j = 0; $j < sizeOf($coreSubject2); $j++) {

                                $topics = '';

                                if ($json['core2Topics'] != '') {

                                    $core2Topics = $json['core2Topics'];

                                    $core2Topics2 = str_replace('addmore', '', $core2Topics);
                                    $core2Topics2 = rtrim($core2Topics2, ',');

                                    $topic = mysqli_query($databaseConnection, "select distinct(subjectId) as subjectId,group_concat(distinct(topic_id)) as topic from questions where topic_id in(" . $core2Topics2 . ") and subjectId='" . $coreSubject2[$j] . "' group by subjectId");

                                    if (mysqli_num_rows($topic) > 0) {

                                        $topics = mysqli_fetch_assoc($topic)['topic'];
                                    }


                                }

                                $scpsInsertion = mysqli_query($databaseConnection, "INSERT INTO scps_transaction(`sector`,`company`,`position`,`subject`,`coreSubjectSequence`,`priority`,`dropdown`,`preInterviewId`,`subjectType`,`weightage`,`topics`) VALUES ('2','" . implode(',', $json['companyId']) . "','" . $json['roleId'] . "','" . $coreSubject2[$j] . "','1','1',2,'" . $preId . "','technical'," . $json['core2CutOff'] . ",NULLIF('" . $topics . "',''))");

                                if ($scpsInsertion) {

                                    $scpsInsert += 1;
                                }

                            }
                        }

                        //for coding Subject dropdown
                        if (sizeOf($programmingsubject) > 0) {
                            for ($k = 0; $k < sizeOf($programmingsubject); $k++) {

                                $topics = '';

                                if ($json['codingTopics'] != '') {

                                    $topic = mysqli_query($databaseConnection, "select distinct(subjectId) as subjectId,group_concat(distinct(topic_id)) as topic from questions where topic_id in(" . $json['codingTopics'] . ") and subjectId='" . $programmingsubject[$k] . "' group by subjectId");

                                    if (mysqli_num_rows($topic) > 0) {

                                        $topics = mysqli_fetch_assoc($topic)['topic'];
                                    }


                                }

                                $scpsInsertion = mysqli_query($databaseConnection, "INSERT INTO scps_transaction(`sector`,`company`,`position`,`subject`,`coreSubjectSequence`,`priority`,`dropdown`,`preInterviewId`,`subjectType`,`weightage`,`topics`) VALUES ('2','" . implode(',', $json['companyId']) . "','" . $json['roleId'] . "','" . $programmingsubject[$k] . "','1','1',1,'" . $preId . "','coding'," . $json['codingCutOff'] . ",NULLIF('" . $topics . "',''))");

                                if ($scpsInsertion) {

                                    $scpsInsert += 1;
                                }

                            }
                        }

                        if ($scpsInsert > 0) {

                            $to_encode = array(
                                'status' => 1,
                                'result' => "Success",
                                'data' => 'Interview Created Successfull'
                            );
                        } else {
                            $to_encode = array(
                                'status' => -1,
                                'result' => "error",
                                'data' => 'Error while creating interview structure at stage 3  (scps Insertion Inside 1)'
                            );
                        }

                    } else if ($json['validationState'] == 0) {

                        $scpsInsertion = mysqli_query($databaseConnection, "INSERT INTO scps_transaction(`sector`,`company`,`position`,`subject`,`coreSubjectSequence`,`priority`,`dropdown`,`preInterviewId`,`subjectType`) VALUES ('2','" . implode(',', $json['companyId']) . "','" . $json['roleId'] . "','0','1','1',1,'" . $preId . "','soft')");

                        $scpsInsert += 1;

                        if ($scpsInsert > 0) {

                            $to_encode = array(
                                'status' => 1,
                                'result' => "Success",
                                'data' => 'Interview Created Successfull'
                            );
                        } else {
                            $to_encode = array(
                                'status' => -1,
                                'result' => "error",
                                'data' => 'Error while creating interview structure at stage 3  (scps Insertion Inside 2)'
                            );
                        }

                    } else {

                        $to_encode = array(
                            'status' => -1,
                            'result' => "error",
                            'data' => 'Error while creating interview structure at stage 3  (scps Insertion outside)'
                        );
                    }



                } else {
                    $to_encode = array(
                        'status' => -1,
                        'result' => "error",
                        'data' => 'Error while creating interview structure at stage 2 (Interview Structure Insertion)'
                    );
                }

            } else {
                $to_encode = array(
                    'status' => -1,
                    'result' => "error",
                    'data' => 'Error while creating interview structure at stage 1 (preInterview Insertion)'
                );
            }

        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "Error in the given data"
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['createPacticeInterview'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    $to_encode = array();
    if ($json) {

        $subject1 = array();
        $subject2 = array();
        $topic1 = array();
        $topic2 = array();
        $roleId = $json['roleId'];
        $userId = $json['userId'];
        $jobId = $json['jobId'];
        $preId = '';
        $interviewName = 'Practice_';
        $subjectValues = '';
        $subjectString = '';
        $subjectArray = '';
        $topicArray = '';
        $topic1String = '';
        $topic2String = '';

        // echo "subjects : ";
        // print_r($json['subject1']);

        if (!empty($json['subject1'])) {
            $subjectArray = json_decode($json['subject1']);
            // Split the values of $json['subject1'] into two separate arrays
            $subjectValues = preg_split("/\,/", implode(",", $subjectArray));

            // Assign the first value to $subject1 and the second value to $subject2
            if (isset($subjectValues[0])) {
                $subject1[] = $subjectValues[0];
            }
            if (isset($subjectValues[1])) {
                $subject2[] = $subjectValues[1];
            }
        }
        if (!empty($json['topics'])) {
            $topicArray = json_decode($json['topics']);
            $topicValues = preg_split("/\,/", implode(",", $topicArray));
        }
        // exit();
        $subjectString = implode(',', $subjectArray);
        $name1 = '';
        $name2 = '';
        $nameId1 = '';
        $nameId2 = '';
        $position = '';

        if (sizeof($subject1) > 0) {
            $subjectIds = implode(',', $subject1); // Convert subject1 array to comma-separated string
            $subjectNameQuery = mysqli_query($databaseConnection, "SELECT id,favourite_subject FROM favourite_subject WHERE id IN ($subjectIds)");
            while ($row = mysqli_fetch_assoc($subjectNameQuery)) {
                $nameId1 = $subjectIds;
                $name1 .= $row['favourite_subject']; // Append favourite_subject to name1
            }
        }

        if (sizeof($subject2) > 0) {
            $subjectIds = implode(',', $subject2); // Convert subject2 array to comma-separated string
            $subjectNameQuery = mysqli_query($databaseConnection, "SELECT id,favourite_subject FROM favourite_subject WHERE id IN ($subjectIds)");
            while ($row = mysqli_fetch_assoc($subjectNameQuery)) {
                $nameId2 = $subjectIds;
                $name2 .= $row['favourite_subject']; // Append favourite_subject to name2
            }
        }

        if ($name1 != '') {
            $interviewName .= $name1; // Concatenate name1 to interviewName
        }

        if ($name2 != '') {
            $interviewName .= '_' . $name2; // Concatenate name2 to interviewName with underscore
        }

        // echo "subId1 :".$nameId1;

        // echo "subId2 :".$nameId2;
        // echo "sub2Size : ";
        // print_r(sizeof($subject2));
        // exit();
        $sub1PreId = '';
        $subjectNameQuery1 = mysqli_query($databaseConnection, "SELECT scps.preInterviewId FROM scps_transaction scps inner join preInterview pr ON pr.id=scps.preInterviewId WHERE scps.subject ='$nameId1' AND scps.position = '$roleId' and pr.interviewType='Practice'");
        while ($row = mysqli_fetch_assoc($subjectNameQuery1)) {
            $sub1PreId = $row['preInterviewId'];
        }
        $sub2PreId = '';
        if (!empty($sub1PreId) && !empty($nameId2)) {
            $subjectNameQuery2 = mysqli_query($databaseConnection, "SELECT preInterviewId FROM scps_transaction WHERE preInterviewId = '$sub1PreId' AND subject ='$nameId2'  AND position = '$roleId'");
            while ($row = mysqli_fetch_assoc($subjectNameQuery2)) {
                $sub2PreId = $row['preInterviewId'];
            }
        }
        $sub1PreIdCount = 0;
        $subjectNameQuery3 = mysqli_query($databaseConnection, "SELECT count(*) as count1 FROM scps_transaction scps inner join preInterview pr ON pr.id=scps.preInterviewId WHERE scps.preInterviewId = '$sub1PreId' and pr.interviewType='Practice'");
        while ($row = mysqli_fetch_assoc($subjectNameQuery3)) {
            $sub1PreIdCount = $row['count1'];
        }
        // if(!empty($sub1PreId) && !empty($sub2PreId)){
        //     if($sub1PreId == $sub2PreId){
        //       $preId=$sub1PreId;
        //     }
        // }else if(!empty($sub1PreId) && $sub1PreIdCount==1 && empty($nameId2)){
        //     $preId=$sub1PreId;
        // }

        $sub1Topics = [];
        $sub2Topics = [];
        if (!empty($nameId1)) {
            $subjectQuery1 = mysqli_query($databaseConnection, "
            select DISTINCT t.id as topicId, 
                    t.name as topicName from questions q left join topic t on t.id=q.topic_id where q.isActive = 'Y' and 
                    q.subjectId ='$nameId1' and q.deleted_at is null group by q.topic_id");
            while ($row = mysqli_fetch_assoc($subjectQuery1)) {
                $sub1Topics[] = $row['topicId'];
            }
        }


        if (!empty($nameId2)) {
            $subjectQuery2 = mysqli_query($databaseConnection, "
            select DISTINCT t.id as topicId, 
                    t.name as topicName from questions q left join topic t on t.id=q.topic_id where q.isActive = 'Y' and 
                    q.subjectId ='$nameId2' and q.deleted_at is null group by q.topic_id");
            while ($row = mysqli_fetch_assoc($subjectQuery2)) {
                $sub2Topics[] = $row['topicId'];
            }
        }

        foreach ($topicValues as $topic) {
            if (in_array($topic, $sub1Topics)) {
                $topic1[] = $topic;
            } elseif (in_array($topic, $sub2Topics)) {
                $topic2[] = $topic;
            }
        }


        $topic1String = implode(",", $topic1);
        $topic2String = implode(",", $topic2);


        // if(empty($preId)){
        $qi = "INSERT INTO preInterview(`company_id`,`roleId`, `interviewLevel`, `interviewType`, `interviewName`, `interviewStartDate`, `interviewExpireDate`,`sectorId`,`productId`,`AdvancedProfileMatch`) VALUES ('0','" . $roleId . "', 'Medium', 'Practice', '" . $interviewName . "', CURDATE(), DATE_ADD(CURDATE(), INTERVAL 60 DAY),2,1,'Y')";

        $preInterviewInsert = mysqli_query($databaseConnection, $qi);

        if ($preInterviewInsert) {
            // echo "Insertion successful!";
        } else {
            echo "Insert Query encountered an error";
            // echo "Error: " . mysqli_error($databaseConnection);
        }

        $preInterviewId = mysqli_query($databaseConnection, "SELECT id FROM preInterview ORDER BY id DESC LIMIT 1");

        $preId = mysqli_fetch_assoc($preInterviewId)['id'];

        $interviewStructure = "INSERT INTO interviewStructure(`companyId`,`sectorId`, `roleId`, `sectionSequence`, `sectionId`, `noOfAnswer`, `noOfSkip`, `depthRequired`, `clusterLevel`,`preInterviewId`) VALUES";
        if ((sizeOf($subject1) > 0)) {
            $interviewStructure .= "('0','2','" . $roleId . "','2','3','2','2','N','" . $json['difficultyLevel'] . "','" . $preId . "'),";
        }
        if ((sizeOf($subject2) > 0)) {
            $interviewStructure .= "('0','2','" . $roleId . "','2','4','2','2','N','" . $json['difficultyLevel'] . "','" . $preId . "'),";
            $interviewStructure .= "('0','2','" . $roleId . "','6','8','2','2','N','" . $json['difficultyLevel'] . "','" . $preId . "'),";
        }

        $interviewStructure .= "('0','2','" . $roleId . "','5','7','0','0','N','" . $json['difficultyLevel'] . "','" . $preId . "');";

        if ($preId) {
            //echo $interviewStructure;
            $interviewStructureInsert = mysqli_query($databaseConnection, $interviewStructure);

            if ($interviewStructureInsert) {
                $scpsInsert = 0;
                if (sizeOf($subject1) > 0) {
                    for ($i = 0; $i < sizeOf($subject1); $i++) {


                        // $topics='';

                        //     $topic=mysqli_query($databaseConnection,"select distinct(subjectId) as subjectId,group_concat(distinct(topic_id)) as topic from questions where isActive = 'Y' and subjectId='".$subject1[$i]."' group by subjectId");

                        //     if(mysqli_num_rows($topic)>0){

                        //         $topics=mysqli_fetch_assoc($topic)['topic'];

                        //     }




                        $scpsInsertion = mysqli_query($databaseConnection, "INSERT INTO scps_transaction(`company`,`sector`,`position`,`subject`,`coreSubjectSequence`,`priority`,`dropdown`,`preInterviewId`,`subjectType`,`weightage`,`topics`) VALUES ('0','2','" . $roleId . "','" . $subject1[$i] . "','1','1',1,'" . $preId . "','technical','4',NULLIF('" . $topic1String . "',''))");

                        if ($scpsInsertion) {

                            $scpsInsert += 1;
                        }

                    }
                }
                if (sizeOf($subject2) > 0) {
                    for ($i = 0; $i < sizeOf($subject2); $i++) {


                        // $topics='';

                        //     $topic=mysqli_query($databaseConnection,"select distinct(subjectId) as subjectId,group_concat(distinct(topic_id)) as topic from questions where isActive = 'Y' and subjectId='".$subject2[$i]."' group by subjectId");

                        //     if(mysqli_num_rows($topic)>0){

                        //         $topics=mysqli_fetch_assoc($topic)['topic'];

                        //     }




                        $scpsInsertion = mysqli_query($databaseConnection, "INSERT INTO scps_transaction(`company`,`sector`,`position`,`subject`,`coreSubjectSequence`,`priority`,`dropdown`,`preInterviewId`,`subjectType`,`weightage`,`topics`) VALUES ('0','2','" . $roleId . "','" . $subject2[$i] . "','1','1',2,'" . $preId . "','technical','4',NULLIF('" . $topic2String . "',''))");

                        if ($scpsInsertion) {

                            $scpsInsert += 1;
                        }

                    }
                }


                if ($scpsInsert > 0) {

                    $to_encode = array(
                        'status' => 1,
                        'preId' => $preId,
                        'result' => "Success",
                        'data' => 'Interview Created Successfull'
                    );
                } else {
                    $to_encode = array(
                        'status' => -1,
                        'result' => "error",
                        'data' => 'Error while creating interview structure at stage 3  (scps Insertion Inside 1)'
                    );
                }


            }

        }

        // }else{
        //     $to_encode = array(
        //     'status' => 1,
        //     'preId' => $preId,
        //     'jobId' => $jobId,
        //     'result' => "Success",
        //     'data' => 'Interview Already exist with same role and subjects'
        //     );
        // }
        if ($preId) {
            // $candidateIds = implode(',', $json['userId']);
            $candidPreId = "INSERT INTO candidateInterviewMapping(`candidateId`, `preInterviewId`, `role`, `subject`,`createdAt`) VALUES('" . $userId . "', '" . $preId . "', '" . $roleId . "', '" . $subjectString . "', NOW())";
            $candidPreIdInsert = mysqli_query($databaseConnection, $candidPreId);
        }
        if ($preId && $jobId != '') {
            // $candidateIds = implode(',', $json['userId']);
            $jobPreId = "INSERT INTO jobPracticeMapping(`jobPreInterviewId`, `practicePreInterviewId`) VALUES('" . $jobId . "', '" . $preId . "')";
            $jobPreIdInsert = mysqli_query($databaseConnection, $jobPreId);
        }

    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "Error in the given data"
        );
    }
    echo json_encode($to_encode);
}
else if (isset($_GET['createPacticeInterview_GoPrac'])) {

    $to_encode = array();

    // Handle file upload
    // $uploadedFilePath = null;
    // if (isset($_FILES['logoImage']) && $_FILES['logoImage']['error'] === UPLOAD_ERR_OK) {
    //     $uploadDir = '../pracschool_app/public/images/';
    //     if (!file_exists($uploadDir)) {
    //         mkdir($uploadDir, 0777, true);
    //     }
    //     $fileName = uniqid() . '_' . basename($_FILES['logoImage']['name']);
    //     $targetFilePath = $uploadDir . $fileName;

    //     if (move_uploaded_file($_FILES['logoImage']['tmp_name'], $targetFilePath)) {
    //         $uploadedFilePath = $fileName;
    //     } else {
    //         echo json_encode(['status' => -1, 'message' => 'File upload failed']);
    //         exit();
    //     }
    // } else {
    //     $uploadedFilePath = NULL;
    // }

    if ($_POST) {

        // Extract data from $_POST
        $subject1 = $_POST['coreSubject1'] ?? null;
        $subject2 = $_POST['coreSubject2'] ?? null;

        $topic1 = $_POST['core1Topics'];
        $topic2 = $_POST['core2Topics'];

        $interviewName = $_POST['practiceName'] ?? null;
        $practiceDuration = $_POST['practiceDuration'] ?? null;
        $preId = $_POST['preId'];
        $YOE = $_POST['YOE'] ?? null;

        // Validate and sanitize inputs
        $interviewName = mysqli_real_escape_string($databaseConnection, $interviewName);
        $practiceDuration = mysqli_real_escape_string($databaseConnection, $practiceDuration);
        $college_id = isset($_POST['college_id']) ? $_POST['college_id'] : '';
        $roleId = isset($_POST['roleId']) ? $_POST['roleId'] : '';
        $subjectId = isset($_POST['subjectId']) ? $_POST['subjectId'] : '';
        $practiceType = isset($_POST['practiceType']) ? $_POST['practiceType'] : '';
        // $ECertificate = isset($_POST['ECertificate']) ? $_POST['ECertificate'] : '';
        $practiceDescription = isset($_POST['practiceDescription']) && $_POST['practiceDescription'] !== '' ? $_POST['practiceDescription'] : NULL;
        $logoUrl = isset($_POST['logoUrl']) ? $_POST['logoUrl'] : null;

        $uploadedFilePath = null;
        if($logoUrl){
            $uploadedFilePath = $logoUrl;
        }


        // Insert or update logic
        // echo $preId;


        if (isset($preId) && $preId !== null && $preId !== '' && $preId != 'null') {

            $deleteScps = mysqli_query($databaseConnection, "delete from scps_transaction where preInterviewId='" . $preId . "'");
            $deleteInterviewStructure = mysqli_query($databaseConnection, "delete from interviewStructure where preInterviewId='" . $preId . "'");

            $updateQuery = "UPDATE preInterview SET 
                interviewName = '$interviewName',
                college_id = $college_id,
                roleId = $roleId,
                subjectId = '$subjectId',
                practiceType = '$practiceType',
                duration = '$practiceDuration',
                logoText = " . ($uploadedFilePath !== NULL ? "'$uploadedFilePath'" : "NULL") . ",
                description = " . ($practiceDescription !== NULL ? "'$practiceDescription'" : "NULL") . ",
                YOE = " . ($YOE !== NULL && $YOE !== '' ? "'YOE'" : "NULL") . "
                WHERE id = '$preId'";

            // echo $updateQuery;


            $result = mysqli_query($databaseConnection, $updateQuery);

            // echo $preId;
        } else {

            $insertQuery = "INSERT INTO preInterview(`college_id`, `roleId`,`subjectId`,`practiceType`, `interviewLevel`, `interviewType`, `interviewName`, `interviewStartDate`, `interviewExpireDate`, `sectorId`, `productId`, `duration`, `description`, `logoText`, `YOE`) 
            VALUES (
                $college_id, 
                $roleId, 
                '$subjectId',
                '$practiceType',
                'Medium', 
                'Practice', 
                '" . $interviewName . "', 
                CURDATE(), 
                DATE_ADD(CURDATE(), INTERVAL 360 DAY), 
                2, 
                1, 
                '" . $practiceDuration . "', 
                " . (isset($_POST['practiceDescription']) && $_POST['practiceDescription'] !== '' ? "'" . $_POST['practiceDescription'] . "'" : "NULL") . ", 
                " . ($uploadedFilePath !== NULL && $uploadedFilePath !== '' ? "'" . $uploadedFilePath . "'" : "NULL") . ",
                " . ($YOE !== NULL && $YOE !== '' ? "'" . $YOE . "'" : "NULL") . 
                ")";

            // echo $insertQuery;

            $result = mysqli_query($databaseConnection, $insertQuery);

            if ($result) {
                // get preId
                $preInterviewId = mysqli_query($databaseConnection, "SELECT id FROM preInterview ORDER BY id DESC LIMIT 1");
                $preId = mysqli_fetch_assoc($preInterviewId)['id'];
            } else {
                echo "Insert Query encountered an error";
                // echo "Error: " . mysqli_error($databaseConnection);
            }
        }
        // echo $preId;

        $interviewStructure = "INSERT INTO interviewStructure(`companyId`,`sectorId`, `roleId`, `sectionSequence`, `sectionId`, `noOfAnswer`, `noOfSkip`, `depthRequired`, `clusterLevel`,`preInterviewId`) VALUES";
        if ($_POST['coreSubject1'] != '') {
            if (!is_array($subject1)) {
                $subject1 = explode(',', $subject1);
            }
            if ((sizeOf($subject1) > 0)) {
                $interviewStructure .= "('0','2','0','2','3','2','2','N','" . $_POST['difficultyLevel'] . "','" . $preId . "'),";
            }
        }
        if ($_POST['coreSubject2'] != '') {
            if (!is_array($subject2)) {
                $subject2 = explode(',', $subject2);
            }
            if ((sizeOf($subject2) > 0)) {
                $interviewStructure .= "('0','2','0','2','4','2','2','N','" . $_POST['difficultyLevel'] . "','" . $preId . "'),";
                $interviewStructure .= "('0','2','0','6','8','2','2','N','" . $_POST['difficultyLevel'] . "','" . $preId . "'),";
            }
        }
        $interviewStructure .= "('0','2','0','5','7','0','0','N','" . $_POST['difficultyLevel'] . "','" . $preId . "');";

        //  echo $preId;

        if ($preId) {
            //echo $interviewStructure;
            $interviewStructureInsert = mysqli_query($databaseConnection, $interviewStructure);

            if ($interviewStructureInsert) {
                $scpsInsert = 0;
                if ($_POST['coreSubject1'] != '') {
                    if (!is_array($subject1)) {
                        $subject1 = explode(',', $subject1);
                    }
                    // echo $subject1;
                    if (sizeOf($subject1) > 0) {
                        for ($i = 0; $i < sizeOf($subject1); $i++) {

                            $topics = '';

                            if ($_POST['core1Topics'] != '') {

                                $core1Topics = $_POST['core1Topics'];

                                $core1Topics1 = str_replace('addmore', '', $core1Topics);
                                $core1Topics1 = rtrim($core1Topics1, ',');

                                $topic = mysqli_query($databaseConnection, "select distinct(subjectId) as subjectId,group_concat(distinct(topic_id)) as topic from questions where topic_id in(" . $core1Topics1 . ") and subjectId='" . $subject1[$i] . "' group by subjectId");

                                if (mysqli_num_rows($topic) > 0) {

                                    $topics = mysqli_fetch_assoc($topic)['topic'];

                                }

                            }

                            $t1sql = "INSERT INTO scps_transaction(`company`,`sector`,`position`,`subject`,`coreSubjectSequence`,`priority`,`dropdown`,`preInterviewId`,`subjectType`,`weightage`,`topics`) VALUES ('0','2','0','" . $subject1[$i] . "','1','1',1,'" . $preId . "','technical','4',NULLIF('" . $topics . "',''))";

                            // echo $t1sql;

                            $scpsInsertion = mysqli_query($databaseConnection, $t1sql);
                            // if (!$scpsInsertion) {
                            //     error_log("SCPS INSERT FAILED");
                            //     error_log("preInterviewId: " . $preId);
                            //     error_log("subjectId: " . $subject1[$i]);
                            //     error_log("SQL: " . $t1sql);
                            //     error_log("MySQL Error: " . mysqli_error($databaseConnection));
                            // }

                            if ($scpsInsertion) {

                                $scpsInsert += 1;
                            }

                        }
                    }
                }
                if ($_POST['coreSubject2'] != '') {

                    if (!is_array($subject2)) {
                        $subject2 = explode(',', $subject2);
                    }
                    if (sizeOf($subject2) > 0) {
                        for ($i = 0; $i < sizeOf($subject2); $i++) {


                            $scpsInsertion = mysqli_query($databaseConnection, "INSERT INTO scps_transaction(`company`,`sector`,`position`,`subject`,`coreSubjectSequence`,`priority`,`dropdown`,`preInterviewId`,`subjectType`,`weightage`,`topics`) VALUES ('0','2','0','" . $subject2[$i] . "','1','1',2,'" . $preId . "','technical','4',NULLIF('" . $topic2 . "',''))");

                            if ($scpsInsertion) {

                                $scpsInsert += 1;
                            }

                        }
                    }
                }


                if ($scpsInsert > 0) {

                    $to_encode = array(
                        'status' => 1,
                        'preId' => $preId,
                        'interviewName' => $interviewName,
                        'result' => "Success",
                        'data' => 'Interview Created Successfull'
                    );
                } else {
                    $to_encode = array(
                        'status' => -1,
                        'result' => "error",
                        'data' => 'Error while creating interview structure at stage 3  (scps Insertion Inside 1)'
                    );
                }


            } else {
                $to_encode = array(
                    'status' => -1,
                    'result' => "error",
                    'errorCode' => "Error in the given data (1)"
                );
            }

        } else {
            $to_encode = array(
                'status' => -1,
                'result' => "error",
                'errorCode' => "Error in the given data (2)"
            );

        }

    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "Error in the given data (3)"
        );
    }

    echo json_encode($to_encode);
}
else if (isset($_GET['deletePracticeInterview'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    $to_encode = array();
    if ($json) {
        if ($json['preId'] != '') {

            $deleteScps = mysqli_query($databaseConnection, "delete from scps_transaction where preInterviewId='" . $json['preId'] . "'");
            $deleteInterviewStructure = mysqli_query($databaseConnection, "delete from interviewStructure where preInterviewId='" . $json['preId'] . "'");
            $deletePreInterview = mysqli_query($databaseConnection, "delete from preInterview where id='" . $json['preId'] . "'");

            $to_encode = array(
                'status' => 1,
                'result' => "Success",
                'data' => 'Practice Deleted Successfull'
            );

        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "error",
                'data' => 'Error while deleting practice'
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "Error in the given data"
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['assignPractice'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    $to_encode = array();
    if ($json) {
        $emailId = $json['emailId'];
        $mobileNumber = $json['mobileNumber'];
        $candidateName = $json['candidateName'];
        $subject = $json['subject'];
        $preId = null;
        $roleId = "";
        $practiceFrequency = $json['practiceFrequency'];

        if (!empty($json['subject'])) {
            if (is_array($json['subject'])) {
                $subject = implode(',', $json['subject']);
            } else {
                $subject = $json['subject'];
            }
        } else {
            $subject = null;
        }

        if (!empty($emailId)) {
            $useId = "SELECT id AS candidateId FROM users WHERE emailId = '" . $emailId . "'";
            $useIdIdResult = mysqli_query($databaseConnection, $useId);

            if ($useIdIdResult) {
                $row = mysqli_fetch_assoc($useIdIdResult);
                if ($row) {
                    $userId = $row['candidateId'];
                }
            }
        }
        if (empty($userId)) {
            if (!empty($mobileNumber)) {
                $useId1 = "SELECT id AS candidateId FROM users WHERE mobileNumber = '" . $mobileNumber . "'";
                $useIdIdResult1 = mysqli_query($databaseConnection, $useId1);

                if ($useIdIdResult1) {
                    $row1 = mysqli_fetch_assoc($useIdIdResult1);
                    if ($row1) {
                        $userId = $row1['candidateId'];
                    }
                }
            }
        }
        if (empty($userId)) {
            if ($json['candidateId'] == '' || $json['candidateId'] == NULL) {
                $userId = NULL;
            } else {
                $userId = $json['candidateId'];
            }
        }

        // if($json['cimId'] != ''){
        //     if($preId){

        //         $candidPreIdUpdate = "UPDATE candidateInterviewMapping 
        //           SET candidateId = ".($userId === NULL ? "NULL" : "'".$userId."'").", 
        //               emailId = '".$emailId."', 
        //               preInterviewId = '".$preId."', 
        //               practiceFrequency = '".$practiceFrequency."' 
        //           WHERE id = '".$json['cimId']."'";

        //         $candidPreIdUpdateResult=mysqli_query($databaseConnection,$candidPreIdUpdate);

        //          if($candidPreIdUpdateResult){
        //              $to_encode = array(
        //              'status' => 1,
        //              'preId' => $preId,
        //              'candidateId'=>$userId,
        //              'emailId'=>$emailId,
        //              'candidateName'=> $candidateName,
        //              'mobileNumber'=> $mobileNumber,
        //              'practiceFrequency'=>$practiceFrequency,
        //              'result' => "Assigned Practice Edited Successfully",

        //             );
        //              }else{
        //                $to_encode = array(
        //                'status' => 0,
        //               'result' => "error",
        //             ); 
        //            }

        //      }
        // }else{
        //     if($preId){
        //         // $candidPreId ="INSERT INTO candidateInterviewMapping(`candidateId`, `preInterviewId`, `role`, `subject`, `createdAt`, `practiceFrequency`) VALUES('".$userId."', '".$preId ."', '".$roleId."', '".$subjectString."', NOW(), '".$practiceFrequency."')";
        //         $candidPreId = "INSERT INTO candidateInterviewMapping(`candidateId`, `preInterviewId`, `emailId`, `createdAt`, `practiceFrequency`) 
        //         VALUES(".($userId === NULL ? "NULL" : "'".$userId."'").", '".$preId."', '".$emailId."', NOW(), '".$practiceFrequency."')";

        //         $candidPreIdInsert=mysqli_query($databaseConnection,$candidPreId);

        //          if($candidPreIdInsert>0){
        //              $to_encode = array(
        //              'status' => 1,
        //              'preId' => $preId,
        //              'candidateId'=>$userId,
        //              'emailId'=>$emailId,
        //              'candidateName'=> $candidateName,
        //              'mobileNumber'=> $mobileNumber,
        //              'practiceFrequency'=>$practiceFrequency,
        //              'result' => "Practice Assign Successfully",

        //             );
        //              }else{
        //                $to_encode = array(
        //                'status' => 0,
        //               'result' => "error",
        //             ); 
        //            }

        //     }
        // }  

        if (!empty($subject)) {
            $role = "SELECT roleId FROM role_subject where subjectId IN ($subject)";
            // echo $role;
            $roleResult = mysqli_query($databaseConnection, $role);

            if ($roleResult) {
                $row = mysqli_fetch_assoc($roleResult);
                if ($row) {
                    $roleId = $row['roleId'];
                }
            }
        }

        if ($subject != '' && $subject != null && $subject != '0') {
            $sql2 = "SELECT st.preInterviewId from scps_transaction st inner join preInterview pr ON pr.id=st.preInterviewId where pr.interviewType = 'Practice' and st.subject IN (" . $subject . ") group by st.subject";
            $subject_query2 = mysqli_query($databaseConnection, $sql2);
            if (mysqli_num_rows($subject_query2) > 0) {
                $subjectResult2 = mysqli_fetch_all($subject_query2, MYSQLI_ASSOC);

                if (!empty($subjectResult2[0]['preInterviewId'])) {
                    $preId = $subjectResult2[0]['preInterviewId'];
                } else {
                    $preId = '904';
                }
            } else {
                $preId = '904';
            }
        } else {
            $preId = '904';
        }

        if ($preId) {
            // Check if a row with the same preInterviewId and either candidateId or emailId exists
            $checkQuery = "SELECT id FROM candidateInterviewMapping 
                               WHERE preInterviewId = '" . $preId . "' 
                                 AND (candidateId = " . ($userId === NULL ? "NULL" : "'" . $userId . "'") . " 
                                      OR emailId = '" . $emailId . "')";

            $checkResult = mysqli_query($databaseConnection, $checkQuery);
            $isDuplicate = mysqli_num_rows($checkResult) > 0; // True if duplicate row exists

            if ($json['cimId'] != '' && $isDuplicate) {
                // Proceed with update
                $candidPreIdUpdate = "UPDATE candidateInterviewMapping 
                                              SET candidateId = " . ($userId === NULL ? "NULL" : "'" . $userId . "'") . ", 
                                                  emailId = '" . $emailId . "', 
                                                  preInterviewId = '" . $preId . "', 
                                                subject = '" . $subject . "', 
                                                  role = '" . $roleId . "'
                                              WHERE id = '" . $json['cimId'] . "'";

                // echo $candidPreIdUpdate;                    

                $candidPreIdUpdateResult = mysqli_query($databaseConnection, $candidPreIdUpdate);

                if ($candidPreIdUpdateResult) {
                    $to_encode = array(
                        'status' => 1,
                        'preId' => $preId,
                        'candidateId' => $userId,
                        'emailId' => $emailId,
                        'candidateName' => $candidateName,
                        'mobileNumber' => $mobileNumber,
                        'practiceFrequency' => $practiceFrequency,
                        'result' => "Assigned Practice Edited Successfully",
                    );
                } else {
                    $to_encode = array(
                        'status' => 0,
                        'result' => "Error during update",
                    );
                }

            } else {
                // Proceed with insertion
                $candidPreId = "INSERT INTO candidateInterviewMapping(`candidateId`, `preInterviewId`, `emailId`, `createdAt`,`role`, `subject`) 
                                        VALUES(" . ($userId === NULL ? "NULL" : "'" . $userId . "'") . ", '" . $preId . "', '" . $emailId . "', NOW(), '" . $roleId . "', '" . $subject . "')";

                // echo $candidPreId;

                $candidPreIdInsert = mysqli_query($databaseConnection, $candidPreId);

                if ($candidPreIdInsert > 0) {
                    $to_encode = array(
                        'status' => 1,
                        'preId' => $preId,
                        'candidateId' => $userId,
                        'emailId' => $emailId,
                        'candidateName' => $candidateName,
                        'mobileNumber' => $mobileNumber,
                        'practiceFrequency' => $practiceFrequency,
                        'result' => "Practice Assigned Successfully",
                    );
                } else {
                    $to_encode = array(
                        'status' => 0,
                        'result' => "Error during insert",
                    );
                }
            }
        }


    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "Error in the given data"
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['checkPracticeSessions'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    $to_encode = array();
    if ($json['userId']) {
        $userId = $json['userId'];
        $email = null;
        if ($userId) {

            $data = "
                SELECT u.emailId
                FROM users u
                INNER JOIN register r ON u.emailId = r.email
                WHERE u.id = ? AND u.emailId IS NOT NULL AND u.emailId <> ''
            ";
            // echo $data;
            $stmt = mysqli_prepare($databaseConnection, $data);
            mysqli_stmt_bind_param($stmt, 'i', $userId);
            mysqli_stmt_execute($stmt);
            $result = mysqli_stmt_get_result($stmt);

            if (mysqli_num_rows($result) >= 1) {
                $row = mysqli_fetch_assoc($result);
                $email = $row['emailId'];

                $to_encode = array(
                    'status' => 2,
                    'result' => "Success",
                    'data' => 'found'
                );
            } else {
                $to_encode = array(
                    'status' => 1,
                    'result' => "Success",
                    'data' => 'not found'
                );
            }
        } else {
            $to_encode = array(
                'status' => -1,
                'result' => "error",
                'errorCode' => "Error in the given data"
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "Error in the given data"
        );
    }
    mysqli_stmt_close($stmt);
    echo json_encode($to_encode);
} else if (isset($_GET['getEventReportData'])) {
    /* Sibin sept 2022 Event-Report*/
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $filter_query = " ";
        $having_query = " ";
        $limit = $json['limit'];
        $start = ($json['page'] - 1) * ($limit);
        $limit_query = $limit == 0 ? "" : " limit " . $start . "," . $limit;
        $alldata = array();
        $values = array();
        $collegeId = '';
        $order_query = "order by temp2.interviewSessionId desc";
        $rawData = " ";
        $rawData2 = " ";
        $preInterviewId = $json['preInterviewId'];
        $selectData = '';
        $queryData = '';
        $flag = $json['flag'];
        $hrcmpfilter = '';
        $jobnamefilter = '';
        $postedbyfilter = '';
        // $sflag = $json['sflag'];
        $jobnameArray = $json['jobname'];

        if ($jobnameArray !== null && $jobnameArray !== "") {
            if (is_array($jobnameArray)) {
                $jobname = implode(",", $jobnameArray);
                $jobnamefilter = " AND pr.id IN (" . $jobname . ")";
            } else {
                $jobnamefilter = " AND pr.id IN (" . $jobnameArray . ")";
            }
        }
        $startDate = isset($json['postedfrom']) ? $json['postedfrom'] : null;
        $endDate = isset($json['postedto']) ? $json['postedto'] : null;

        if ($startDate && $endDate) {

            $postedbyfilter = " AND pr.interviewStartDate BETWEEN '" . $startDate . "' AND '" . $endDate . "'";
        } else if ($startDate) {

            $postedbyfilter = " AND pr.interviewStartDate >= '" . $startDate . "' ";
        }

        if ($userType != 'corporate') {
            $hiringcompanyArray = $json['hiringcompany'];


            if ($hiringcompanyArray !== null && $hiringcompanyArray !== "") {
                if (is_array($hiringcompanyArray)) {
                    $hiringcompany = implode(",", $hiringcompanyArray);
                    $hrcmpfilter = " AND pr.company_id IN (" . $hiringcompany . ")";
                } else {
                    $hrcmpfilter = " AND pr.company_id IN (" . $hiringcompanyArray . ")";
                }
            }
            $servicetypefilter = "and pr.serviceType != 'IAS' ";

            $servicetypeArray = $json['servicetype'];
            if ($servicetypeArray !== null) {

                $servicetypeConditions = array_map(function ($type) {
                    return "pr.serviceType = '$type'";
                }, $servicetypeArray);

                $servicetypefilter = " AND (" . implode(" OR ", $servicetypeConditions) . ")";
            }
        }

        if ($userType == 'corporate') {
            $servicetypefilter = "and pr.serviceType = 'IAS' ";
        }

        if ($userType == 'corporate') {
            $code = mysqli_query($databaseConnection, "SELECT firstName as compname FROM users WHERE id = " . $userId . "");
            while ($fil = mysqli_fetch_assoc($code)) {

                $letcheck = $fil['compname'];
            }
            $total_data['compname'] = $letcheck;
        }

        if ($userType == 'corporate') {
            $rawData .= " and i.preInterviewId in (SELECT preinterviewId FROM preInterview_corporate WHERE userId=" . $userId . ")";
            $rawData2 .= " and pr.id in(SELECT cd.id FROM preInterview cd WHERE cd.id IN (SELECT preinterviewId FROM preInterview_corporate WHERE userId=" . $userId . ")) ";
        }
        if ($flag) {

            //    $query="select u.firstName,u.mobileNumber,u.emailId,CASE WHEN fbr.review_status=2 THEN 'Assessment Completed' WHEN fbr.review_status=-4 THEN 'Assessment Rejected' When fbr.review_status=2 then 'Assessment Open' when fbr.review_status=1 then 'Assessment In-Progress' End as status,case when fbr.review_status=-4 then fbr.suggestion end as suggestion from feedback_request fbr inner join interview i on i.id=fbr.interviewId inner join users u on u.id=fbr.candidateId where i.companyId=".$companyId." ";

            // query is modified to show all the attempted and scheduled candidates in one excel report

            $query = "select u.firstName,u.mobileNumber,u.emailId,CASE WHEN fbr.review_status=2 THEN 'Assessment Completed' WHEN fbr.review_status=-4 THEN 'Assessment Rejected' When fbr.review_status=2 then 'Assessment Open' when fbr.review_status=1 then 'Assessment In-Progress' End as status,case when fbr.review_status=-4 then fbr.suggestion end as suggestion,'Attempted' as InterviewStatus,rr.name as RecruiterName,pd.workExperience,pd.noticePeriod,pd.salary as 'currentSalary',pd.joinstatus,pd.jobType,pd.preferedJobType,pd.currentCompany,pd.currentProcess,pd.processType,pd.clientType,pd.expectedSalary,pd.processPreference,pd.shift,pd.workLocationPreference,pd.timeToCall,l.cityName as 'currentLocations',(select group_concat(l.cityName) from locations l where FIND_IN_SET(l.id,pd.preferredWorkLocation)) as 'preferredWorkLocation',ivs.scheduleTime from feedback_request fbr inner join interview i on i.id=fbr.interviewId inner join users u on u.id=fbr.candidateId inner join professionaldetails pd on pd.candidateId=u.id left join interviewSchedule ivs on ivs.emailId=u.emailId and ivs.company_id=i.companyId left join recruiterList rr on rr.id=ivs.recruiterId left join locations l on l.id=pd.currentLocation where i.preInterviewId=" . $preInterviewId . "
            union
            select * from (select t.candidateName as firstName,t.mobileNumber,t.emailId,null as status,null as suggestion,case when t.scheduleTime >= now() then 'Feature Scheduled' when t.scheduleTime < now() then 'Missed Schedule' else 'Schedule' end as InterviewStatus,t.name as RecruiterName,t.workExperience,t.noticePeriod,t.currentSalary,NULL as joinstatus,t.jobType,t.preferedJobType,t.currentCompany,t.currentProcess,t.processType,t.clientType,t.expectedSalary,t.processPreference,t.shift,t.workLocationPreference,t.timeToCall,t.currentLocations,t.preferredWorkLocation,t.scheduleTime from (select u.id as candidate_id,ivs.emailId,ivs.company_id,ivs.scheduleTime,ivs.candidateName,ivs.mobileNumber,rr.name,ivs.workExperience,ivs.noticePeriod,ivs.currentSalary,NULL as joinstatus,ivs.jobType,ivs.preferedJobType,ivs.currentCompany,ivs.currentProcess,ivs.processType,ivs.clientType,ivs.expectedSalary,ivs.processPreference,ivs.shift,ivs.workLocationPreference,ivs.timeToCall,l.cityName as 'currentLocations',(select group_concat(l.cityName) from locations l where FIND_IN_SET(l.id,ivs.preferredWorkLocation)) as 'preferredWorkLocation' from interviewSchedule ivs left join users u on u.emailId=ivs.emailId left join recruiterList rr on rr.id=ivs.recruiterId left join locations l on l.id=ivs.currentLocation where ivs.emailId is not null and u.id not in(select i.createdBy from interview i inner join feedback_request fr on fr.interviewId=i.id and fr.candidateId=i.createdBy where i.companyId is not null and i.preInterviewId=" . $preInterviewId . ") and ivs.preInterviewId=" . $preInterviewId . " 
            union 
            select u.id as candidate_id,ivs.emailId,ivs.company_id,ivs.scheduleTime,ivs.candidateName,ivs.mobileNumber,rr.name,ivs.workExperience,ivs.noticePeriod,ivs.currentSalary,NULL as joinstatus,ivs.jobType,ivs.preferedJobType,ivs.currentCompany,ivs.currentProcess,ivs.processType,ivs.clientType,ivs.expectedSalary,ivs.processPreference,ivs.shift,ivs.workLocationPreference,ivs.timeToCall,l.cityName as 'currentLocations',(select group_concat(l.cityName) from locations l where FIND_IN_SET(l.id,ivs.preferredWorkLocation)) as 'preferredWorkLocation'  from interviewSchedule ivs left join users u on u.emailId=ivs.emailId left join recruiterList rr on rr.id=ivs.recruiterId left join locations l on l.id=ivs.currentLocation where ivs.emailId is not null and ivs.preInterviewId=" . $preInterviewId . " having candidate_id is null) as t order by t.scheduleTime DESC) as t2";

            // echo  $query; 
            // exit();
            $query_result = mysqli_query($databaseConnection, $query);
            if (mysqli_num_rows($query_result) >= 1) {
                $data = mysqli_fetch_all($query_result, MYSQLI_ASSOC);

                $to_encode = array(
                    'result' => "success",
                    'status' => 1,
                    'data' => $data,
                );
            } else {
                $to_encode = array(
                    'result' => "error",
                    'status' => 0,
                    'errorCode' => "in Error You are not having access this page."
                );
            }
        } else {


            $query = "select
	*
from
	(
	select
		*
	from
		(
		SELECT
			temp2.company,
			temp2.cmpy_name,
			temp2.serviceType,
			temp2.companyId,
			max(temp2.interviewSessionId) as interviewSessionId,
			(sum(temp2.attempted)-sum(temp2.rejectedIncomplete)) as completed,
			(sum(temp2.rejectedIncomplete))as incompleted,
			sum(temp2.attempted) as attempted,
			sum(temp2.assessmentCompleted) as assessmentCompleted,
			sum(temp2.assessmentOpen) as assessmentOpen,
			sum(temp2.assessmentpending) as assessmentpending,
			sum(temp2.internalreview) as internalreview,
			sum(temp2.rejected) as rejected,
			temp2.preInterviewId,
			temp2.hiringCompanies,
			temp2.interviewExpireDate,
			temp2.interviewStartDate,
			temp2.status
		from
			(
			SELECT
				temp.company,
				temp.cmpy_name,
				temp.serviceType,
				temp.companyId,
				DATE(from_unixtime(floor(temp.interviewSessionId / 1000))) as interviewSessionId,
				count(CASE WHEN temp.completion_status = 1 THEN temp.completion_status END) as completed,
				count(CASE WHEN temp.completion_status = 0 THEN temp.completion_status END) as incompleted,
				count(temp.completion_status) as attempted,
				count(temp.assessmentCompleted) as assessmentCompleted,
				count(temp.assessmentOpen) as assessmentOpen,
				count(temp.assessmentpending) as assessmentpending,
				count(temp.internalreview) as internalreview,
				count(temp.rejected) as rejected,
				count(temp.rejectedIncomplete) as rejectedIncomplete,
				temp.preInterviewId,
				temp.hiringCompanies,
				temp.interviewExpireDate,
				temp.interviewStartDate,
				temp.status
			from
				(
				select
					case
						when pr.interviewName is null then CONCAT(ac.name, '/', r.name)
						else pr.interviewName
					end as company,
					ac.name as cmpy_name,
					pr.serviceType,
					ac.id as companyId,
					fbr.interviewSessionId,
					(CASE
						WHEN fbr.review_status = 2 THEN fbr.review_status
					END) as assessmentCompleted,
					count(CASE WHEN cit.completion_status is not NULL THEN cit.completion_status END)AS completion_status,
					(CASE
						WHEN (fbr.review_status = 0) THEN fbr.review_status
					END) as assessmentOpen,
					(CASE
						WHEN fbr.review_status = 1 THEN fbr.review_status
					END) as assessmentpending,
					(CASE
						WHEN fbr.review_status =-2 THEN fbr.review_status
					END) as internalreview,
					(CASE
						WHEN fbr.review_status =-4
						and fbr.reasonOfRejection != 'incompleteInterview' THEN fbr.review_status
					END) as rejected,
					(CASE
						WHEN fbr.review_status =-4
						and fbr.reasonOfRejection = 'incompleteInterview' THEN fbr.review_status
					END) as rejectedIncomplete,
					pr.id as preInterviewId,
					pr.hiringCompanies,
					pr.interviewExpireDate,
					pr.interviewStartDate,
					pr.interviewStatus as status
				from
					feedback_request fbr
				JOIN (
					SELECT
						candidateId,
						MAX(interviewSessionId) AS latestSessionId
					FROM
						feedback_request
					GROUP BY
						candidateId
            ) AS latest ON
					fbr.candidateId = latest.candidateId
					AND fbr.interviewSessionId = latest.latestSessionId
				left outer join candidate_interview_transection cit on
					cit.interviewSessionId = fbr.interviewSessionId
					and cit.interviewId = fbr.interviewId
					and cit.candidateId = fbr.candidateId
				left outer join interview i on
					fbr.interviewId = i.id
				left join preInterview pr on
					pr.id = i.preInterviewId
					and pr.company_id = i.companyId
				left join interviewSchedule isc on
					isc.preInterviewId = pr.id
				left outer join relavant_role r on
					i.roleId = r.id
				left outer join aspiration_company ac on
					ac.id = i.companyId
				where
					r.name is not null
					and ac.name is not null
					and fbr.interviewSessionId is not null
					and pr.interviewStatus = 'Active' " . $jobnamefilter . " " . $hrcmpfilter . " " . $servicetypefilter . " " . $postedbyfilter . " " . $rawData . "
				group by
					pr.id,
					fbr.interviewSessionId ) as temp
			group by
				temp.preInterviewId) as temp2";

            $notAttendInterviews = "select case when pr.interviewName is null then ac.name else pr.interviewName end as company,ac.name as cmpy_name,pr.serviceType,pr.company_id as companyId,null as interviewSessionId,0 as completed,0 as incompleted,0 as attempted,0 as assessmentCompleted, 0 as assessmentOpen,0 as assessmentpending,0 as internalreview,0 as rejected,pr.id as preInterviewId,pr.hiringCompanies,pr.interviewExpireDate,pr.interviewStartDate,pr.interviewStatus from preInterview pr inner join aspiration_company ac on ac.id=pr.company_id where pr.id not in (select distinct(i.preInterviewId) from interview i inner join feedback_request fr on fr.interviewId=i.id where i.companyId is not null and i.companyId!=0 and i.preInterviewId is not null) and pr.interviewStatus='Active' " . $jobnamefilter . " " . $hrcmpfilter . " " . $servicetypefilter . "  " . $postedbyfilter . " " . $rawData2 . "";
            $data = $query . $filter_query . 'group by temp2.preInterviewId ) as temp4  union ' . $notAttendInterviews . ') as temp5 order by temp5.interviewStartDate desc ';
            // echo  $data;

            //  $yquery=$data . $limit_query;
            // echo $data;
            // exit();

            // echo $countData;
            if ($data != '') {
                $query = mysqli_query($databaseConnection, $data . $limit_query);
                $values = mysqli_fetch_all($query, MYSQLI_ASSOC);
                $total_data['data'] = $values;

                $preInterviewIds = array_column($values, 'preInterviewId');

                $promotionCount = [];

                // Iterate through each preInterviewId
                foreach ($preInterviewIds as $preInterviewId) {
                    // Execute the query to count promotions
                    $promotionQuery = "SELECT COUNT(*) as pCount FROM promotion WHERE preInterviewId = $preInterviewId AND archiveDate IS NULL";
                    $promotionResult = mysqli_query($databaseConnection, $promotionQuery);

                    // Fetch the count
                    $promotionCountRow = mysqli_fetch_assoc($promotionResult);
                    $promotion = $promotionCountRow['pCount'];

                    // Store the preInterviewId and its corresponding promotion count
                    $promotionCount[] = [
                        'preInterviewId' => $preInterviewId,
                        'promotionCount' => $promotion
                    ];
                }
                $total_data['promotionCount'] = $promotionCount;

                // count query
                $query2 = "select * from (SELECT temp2.preInterviewId from (SELECT temp.preInterviewId from  (select  pr.id as preInterviewId from feedback_request fbr left outer join candidate_interview_transection cit on cit.interviewSessionId = fbr.interviewSessionId and cit.interviewId = fbr.interviewId and cit.candidateId = fbr.candidateId left outer join interview i on fbr.interviewId = i.id left join preInterview pr on pr.id=i.preInterviewId and pr.company_id=i.companyId left join interviewSchedule isc on isc.preInterviewId=pr.id left outer join relavant_role r on i.roleId=r.id left outer join aspiration_company ac on ac.id=i.companyId where r.name is not null and ac.name is not null and fbr.interviewSessionId is not null and pr.interviewStatus='Active' " . $jobnamefilter . " " . $hrcmpfilter . " " . $servicetypefilter . "  " . $postedbyfilter . " " . $rawData . "  group by pr.id,fbr.interviewSessionId ) as temp group by temp.preInterviewId) as temp2";

                $notAttendInterviews2 = "select pr.id as preInterviewId from preInterview pr inner join aspiration_company ac on ac.id=pr.company_id where pr.id not in (select distinct(i.preInterviewId) from interview i inner join feedback_request fr on fr.interviewId=i.id where i.companyId is not null and i.companyId!=0 and i.preInterviewId is not null) and pr.interviewStatus='Active' " . $jobnamefilter . " " . $hrcmpfilter . "" . $servicetypefilter . "  " . $postedbyfilter . "  " . $rawData2 . " ";

                $countQuery = $query2;
                $countData = $countQuery . $filter_query . " group by temp2.preInterviewId) as temp4  union " . $notAttendInterviews2;
                // echo $countData;
                $count_query = mysqli_query($databaseConnection, $countData);
                // $preId = [];
                // while ($row = mysqli_fetch_assoc($count_query)) {
                // $preId[] = $row['preInterviewId'];
                // }
                // $preInterviewIdsString = implode(',', $preId);

                $total_data['count'] = mysqli_num_rows($count_query);

                $to_encode = $total_data;
            } else {
                $to_encode = array(
                    'result' => "error",
                    'status' => 0,
                    'errorCode' => "in Error You are not having access this page."
                );
            }
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving Student information"
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['getUserProfile'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if ($json) {
        $userId = $json['userId'];

        if ($userId != '') {
            $userDataQry = "SELECT CONCAT(u.firstName,' ',u.lastName) as userName,u.emailId,u.mobileNumber,s.stream,c.collegeName,pd.year,GROUP_CONCAT(DISTINCT fs.favourite_subject) as favouriteSubject,GROUP_CONCAT(DISTINCT fps.favourite_subject) as favouriteProgSkill,GROUP_CONCAT(DISTINCT ac.name) as targetCompanies,GROUP_CONCAT(DISTINCT l.name) as languageKnown,u.createdOn FROM users u INNER JOIN professionaldetails pd ON pd.candidateId = u.id LEFT JOIN colleges c ON pd.college = c.id LEFT JOIN stream s ON s.id = pd.specialization LEFT JOIN favourite_subject fs ON FIND_IN_SET(fs.id,pd.fav_subjects) LEFT JOIN favourite_subject fps ON FIND_IN_SET(fps.id,pd.fav_programming_skill) LEFT JOIN aspiration_company ac ON FIND_IN_SET(ac.id,pd.asp_companies) LEFT JOIN language l ON FIND_IN_SET(l.id,pd.languages) WHERE u.id IN (" . $userId . ");";
            $userData = mysqli_query($databaseConnection, $userDataQry);
            if (mysqli_num_rows($userData) > 0) {
                $to_encode = array(
                    'status' => 1,
                    'data' => mysqli_fetch_all($userData, MYSQLI_ASSOC),
                );
            } else {
                $to_encode = array(
                    'status' => -1,
                    'data' => 'Error While Update'
                );
            }
        } else {
            $to_encode = array(
                'status' => -1,
                'data' => 'Error While Update'
            );
        }
    } else {
        $to_encode = array(
            'data' => 'Unable to parse',
            'status' => -1
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['getUserPFDetails'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if ($json) {
        $userId = $json['userId'];
        $preinterviewId = $json['preinterviewId'];
        $emailId = $json['emId'];

        $interviewId = $json['interviewId'];
        // $interviewId = ''; //ss
        $fbr_Id = '';
        // $fbr_Id= 29784;
        $skillMatchResult = '';
        $profileMatchResult = '';
        $jobpreferences = '';

        if ($userId != '') {

            if ($preinterviewId != '') {

                $sql = "select count(isc.preInterviewId) as count from interviewSchedule isc left join users u on u.emailId=isc.emailId
                WHERE isc.preInterviewId In(" . $preinterviewId . ") and u.id IN (" . $userId . ")";
                $result = mysqli_query($databaseConnection, $sql);
                $rowCheck = mysqli_fetch_assoc($result)['count'];

                $count = $rowCheck;

                if ($count > 0) {
                    $filter = " isc.preInterviewId In(" . $preinterviewId . ") and u.id IN (" . $userId . ")
                  ";
                    $fquery = "pr.InterviewName as interviewName,isc.scheduleTime as scheduleTime,";
                } else {
                    $filter = "u.id IN (" . $userId . ")";
                    $fquery = "";
                }


                $userDataQry = "SELECT " . $fquery . " CONCAT(u.firstName,' ',u.lastName) as userName,u.full_details,u.emailId,u.mobileNumber,s.stream,case when pd.college!=188 then c.collegeName else pd.otherCollege end as collegeName,pd.*,pd.salary as currentSalary, GROUP_CONCAT(DISTINCT fs.favourite_subject SEPARATOR ', ') as favouriteSubject,GROUP_CONCAT(DISTINCT fps.favourite_subject) as favouriteProgSkill,GROUP_CONCAT(DISTINCT ac.name SEPARATOR ', ') as targetCompanies,u.gender,GROUP_CONCAT(DISTINCT l.name SEPARATOR ', ') as languageKnown,u.createdOn,ls.cityName as currentLoc,GROUP_CONCAT(DISTINCT lp.cityName SEPARATOR ', ') as preferredLoc, GROUP_CONCAT(DISTINCT rr.name SEPARATOR ', ') as roles,q.qualification as qual FROM interviewSchedule isc inner join preInterview pr on pr.id = isc.preInterviewId left join users u on u.emailId=isc.emailId left JOIN professionaldetails pd ON pd.candidateId = u.id LEFT JOIN colleges c ON pd.college = c.id LEFT JOIN stream s ON s.id = pd.specialization LEFT JOIN favourite_subject fs ON FIND_IN_SET(fs.id,pd.fav_subjects) LEFT JOIN favourite_subject fps ON FIND_IN_SET(fps.id,pd.fav_programming_skill) LEFT JOIN aspiration_company ac ON FIND_IN_SET(ac.id,pd.asp_companies) LEFT JOIN language l ON FIND_IN_SET(l.id,pd.languages) LEFT JOIN locations ls ON FIND_IN_SET(ls.id,pd.currentLocation) LEFT JOIN locations lp ON FIND_IN_SET(lp.id,pd.preferredWorkLocation) LEFT JOIN relavant_role rr ON FIND_IN_SET(rr.id,pd.preferredRole) LEFT JOIN qualification q ON FIND_IN_SET(q.id,pd.qualification) WHERE " . $filter . " ";

                $skill = "SELECT skillMatch($userId, $preinterviewId) AS skillMatchResult";
                $skillMatch = mysqli_query($databaseConnection, $skill);
                if ($skillMatch) {
                    $row = mysqli_fetch_assoc($skillMatch);
                    if ($row) {
                        $skillMatchResult = $row['skillMatchResult'];
                    }
                }
                $jobpreferences = "SELECT * from profilePreferences where preInterviewId in (" . $preinterviewId . ")";

                //added by shrikant : 8/1/2024
                $pSkill = "SELECT jobMatch('$emailId', $preinterviewId) AS profileMatchResult";
                $result1 = mysqli_query($databaseConnection, $pSkill);
                if ($result1) {
                    $row = mysqli_fetch_assoc($result1);
                    if ($row) {
                        $profileMatchResult = $row['profileMatchResult'];
                    }
                }

            } else {
                $userDataQry = "SELECT CONCAT(u.firstName,' ',u.lastName) as userName,u.full_details,u.emailId,u.mobileNumber,s.stream,case when pd.college!=188 then c.collegeName else pd.otherCollege end as collegeName,pd.*,GROUP_CONCAT(DISTINCT fs.favourite_subject SEPARATOR ', ') as favouriteSubject,GROUP_CONCAT(DISTINCT fps.favourite_subject) as favouriteProgSkill,GROUP_CONCAT(DISTINCT ac.name SEPARATOR ', ') as targetCompanies,u.gender,GROUP_CONCAT(DISTINCT l.name SEPARATOR ', ') as languageKnown,u.createdOn,ls.cityName as currentLoc,GROUP_CONCAT(DISTINCT lp.cityName SEPARATOR ', ') as preferredLoc,q.qualification as qual,pd.resume
                FROM users u
                INNER JOIN professionaldetails pd ON pd.candidateId = u.id
                LEFT JOIN colleges c ON pd.college = c.id
                LEFT JOIN stream s ON s.id = pd.specialization
                LEFT JOIN favourite_subject fs ON FIND_IN_SET(fs.id,pd.fav_subjects)
                LEFT JOIN favourite_subject fps ON FIND_IN_SET(fps.id,pd.fav_programming_skill)
                LEFT JOIN aspiration_company ac ON FIND_IN_SET(ac.id,pd.asp_companies)
                LEFT JOIN language l ON FIND_IN_SET(l.id,pd.languages)
                LEFT JOIN locations ls ON FIND_IN_SET(ls.id,pd.currentLocation)
                LEFT JOIN locations lp ON FIND_IN_SET(lp.id,pd.preferredWorkLocation)
                LEFT JOIN qualification q ON FIND_IN_SET(q.id,pd.qualification) WHERE u.id IN (" . $userId . ");";


                $jobpreferences = "SELECT * from profilePreferences where preInterviewId in (select preInterviewId from interview where id in (" . $interviewId . ") )";



                // echo $userDataQry;
                // exit();
            }
            $queryToFetch = "SELECT i.preinterviewId, pr.* 
            FROM interview i 
            LEFT JOIN preInterview pr ON i.preInterviewId = pr.id 
            WHERE i.id = $interviewId";

            $result = $databaseConnection->query($queryToFetch);

            if ($result && $result->num_rows > 0) {
                // Fetch the row
                $row = $result->fetch_assoc();

                // Extract preinterviewId
                $preinterviewIdExtract = $row['preinterviewId'];

            } else {
                echo "No results found or error in query.";
            }

            // get required skills names from ids
            $stmt = $databaseConnection->prepare("SELECT requiredSkills FROM preInterview WHERE id = ?");
            $stmt->bind_param("i", $preinterviewIdExtract);
            $stmt->execute();
            $stmt->bind_result($requiredSkills);
            $stmt->fetch();
            $stmt->close();

            if (empty($requiredSkills)) {
                $requiredSkillsArray = [];
            } else {
                // Process the IDs
                $skillsArray = explode(',', $requiredSkills);
                $skillsArray = array_map('intval', $skillsArray);
                $skillsList = implode(',', $skillsArray);

                // Query to fetch the skill names and IDs
                $query = "SELECT id, favourite_subject as name
                        FROM favourite_subject 
                        WHERE id IN ($skillsList)";
                $result = $databaseConnection->query($query);

                // Initialize an array to store the skills
                $skillsArray = [];

                if ($result && $result->num_rows > 0) {
                    // Fetch all rows as an array
                    while ($row = $result->fetch_assoc()) {
                        $skillsArray[] = $row;
                    }
                }

                // Assign the array to requiredSkillsArray
                $requiredSkillsArray = $skillsArray;
            }

            $candidateSkillsQuery = "SELECT * from candidate_skills where candidateId = " . $userId . ";";
            $candidateSkillsResult = mysqli_query($databaseConnection, $candidateSkillsQuery);
            $candidateSkills = mysqli_fetch_all($candidateSkillsResult, MYSQLI_ASSOC);

            $skillsNotesQuery = "select output from apmLogs where block = '2b' and iscId in(select id from interviewSchedule where candidate_id in (" . $userId . ")) order by id desc limit 1";
            //  echo $skillsNotesQuery;
            $skillsNotesData = mysqli_query($databaseConnection, $skillsNotesQuery);
            if (mysqli_num_rows($skillsNotesData) > 0) {
                $skillsNotes = mysqli_fetch_all($skillsNotesData, MYSQLI_ASSOC);
            } else {
                $skillsNotes = NULL;
            }

            $userData = mysqli_query($databaseConnection, $userDataQry);
            $jobpreferencesData = mysqli_query($databaseConnection, $jobpreferences);
            if (mysqli_num_rows($userData) > 0) {
                $to_encode = array(
                    'status' => 1,
                    'userData' => mysqli_fetch_all($userData, MYSQLI_ASSOC),
                    'skillMatchResult' => $skillMatchResult,
                    'profileMatchResult' => $profileMatchResult,
                    'jobpreferences' => mysqli_fetch_all($jobpreferencesData, MYSQLI_ASSOC),
                    'skillsNotes' => $skillsNotes,
                    'candidateSkills' => $candidateSkills,
                    'requiredSkillsArray' => $requiredSkillsArray
                );
            } else {
                $to_encode = array(
                    'status' => -1,
                    'data' => 'Error While Update'
                );
            }
        } else if (!$userId) {

            $intId = "SELECT id AS interviewId FROM interviewSchedule WHERE emailId = $emailId";
            $InterviewIdResult = mysqli_query($databaseConnection, $intId);

            if ($InterviewIdResult) {
                $row = mysqli_fetch_assoc($InterviewIdResult);
                if ($row) {
                    $interviewId = $row['interviewId'];
                }
            }

            $escapedEmailId = mysqli_real_escape_string($databaseConnection, $emailId);
            $escapedPreinterviewId = (int) $preinterviewId;


            $sql = "select count(isc.preInterviewId)as count from interviewSchedule isc left join users u on u.emailId=isc.emailId
            WHERE isc.preInterviewId In(" . $escapedPreinterviewId . ") and isc.emailId IN ('" . $escapedEmailId . "')";
            $result = mysqli_query($databaseConnection, $sql);

            if ($escapedPreinterviewId != '') {
                $rowCheck = mysqli_fetch_assoc($result)['count'];
                $count = $rowCheck;

                if ($count > 0) {
                    $filter = " isc.preInterviewId In(" . $escapedPreinterviewId . ") and isc.emailId IN ('" . $escapedEmailId . "')";
                    $fquery = "pr.InterviewName as interviewName,isc.scheduleTime as scheduleTime,";
                }
                // elseif($count == null)
                // {
                //     $filter = "isc.emailId IN ('".$escapedEmailId."')";
                //     $fquery="";
                // }
                else {
                    $filter = "isc.emailId IN ('" . $escapedEmailId . "')";
                    $fquery = "";
                }

                $userDataQry = "SELECT " . $fquery . "  CONCAT(u.firstName, ' ', u.lastName) AS userName,
                u.emailId,
                u.full_details,
                u.mobileNumber,
                isc.*,
                u.gender,
                GROUP_CONCAT(DISTINCT l.name SEPARATOR ', ') AS languageKnown,
                u.createdOn,
                ls.cityName AS currentLoc,
                GROUP_CONCAT(DISTINCT lp.cityName SEPARATOR ', ') AS preferredLoc,
                GROUP_CONCAT(DISTINCT rr.name SEPARATOR ', ') as roles
                FROM interviewSchedule isc
                INNER JOIN preInterview pr ON pr.id = isc.preInterviewId
                LEFT JOIN users u ON u.emailId = isc.emailId
                LEFT JOIN language l ON FIND_IN_SET(l.id, isc.languages)
                LEFT JOIN locations ls ON FIND_IN_SET(ls.id, isc.currentLocation)
                LEFT JOIN locations lp ON FIND_IN_SET(lp.id, isc.preferredWorkLocation)
                LEFT JOIN relavant_role rr ON FIND_IN_SET(rr.id,isc.preferredRole)
                WHERE " . $filter . " ";
                // echo  $userDataQry;

            }
            $userData = mysqli_query($databaseConnection, $userDataQry);

            if (mysqli_num_rows($userData) > 0) {
                $to_encode = array(
                    'status' => 1,
                    'userData' => mysqli_fetch_all($userData, MYSQLI_ASSOC),
                    'type' => 1,
                );
            } else {
                $to_encode = array(
                    'status' => -1,
                    'data' => 'Error While Update'
                );
            }

        } else {
            $to_encode = array(
                'status' => -1,
                'data' => 'Error While Update'
            );
        }
    } else {
        $to_encode = array(
            'data' => 'Unable to parse',
            'status' => -1
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['rescheduleInterviewTime'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if ($json) {


        if ($json['interviewScheduleId'] != '') {
            $updateQry = "update interviewSchedule set scheduleTime='" . $json['scheduledTime'] . "' where id=" . $json['interviewScheduleId'] . "";

            $result = mysqli_query($databaseConnection, $updateQry);
            if ($result) {
                $to_encode = array(
                    'status' => 1,
                    'data' => 'Data updated'
                );
            } else {
                $to_encode = array(
                    'status' => -1,
                    'data' => 'Error While Update'
                );
            }
        } else {
            $to_encode = array(
                'status' => -1,
                'data' => 'Error While Update'
            );
        }
    } else {
        $to_encode = array(
            'data' => 'Unable to parse',
            'status' => -1
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['updateskillMatchData'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    if (isset($json)) {

        $condition = "fbr.id in (select id from feedback_request) and ";

        $feedbackReportData = getskillMatch($databaseConnection, $condition);

        if (array_key_exists(0, $feedbackReportData)) {
            for ($i = 0; $i < count($feedbackReportData); $i++) {
                for ($j = 0; $j < count($feedbackReportData[$i]); $j++) {
                    $query = "INSERT INTO `skillMatch`(`feedbackRequestId`, `candidateId`, `subjectType`,`skillPercent`) VALUES ('" . $feedbackReportData[$i][$j]['feedbackRequestId'] . "','" . $feedbackReportData[$i][$j]['candidateId'] . "', NULLIF('" . $feedbackReportData[$i][$j]['subjectType'] . "', ''), NULLIF('" . $feedbackReportData[$i][$j]['skillPercent'] . "', ''))";
                    mysqli_query($databaseConnection, $query);
                }
            }
        }

        $to_encode = array(
            'data1' => $feedbackReportData,
            'status' => 1,
            'result' => "success"
        );
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while updating skillMatch table"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['shortlistedEmailToRecruiter'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    if (isset($json)) {
        $recruiter = $json['recruiter'];
        $subject = $json['subject'];
        $message = $json['body'];
        $Cc = $json['Cc'];
        $Bcc = $json['Bcc'];

        sendMultiUserSameMsg($recruiter, $Cc, $Bcc, $subject, $message);

        $to_encode = array(
            'status' => 1,
            'result' => "success sending"
        );
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while sending"
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['getProfileSummarycsvv'])) {

    //Akash 
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $roleId = $json['roleId'];


        $query = " SELECT
            u.firstName AS name,
            u.username AS email,
            rr.name AS role,
            rr.id AS roleId,
            pd.salary as salary,
            pd.workExperience as workExperience,
            pd.noticePeriod as noticePeriod
        FROM
            users u
        INNER JOIN
            professionaldetails pd ON pd.candidateId = u.id
        LEFT JOIN
            feedback_request fr ON fr.candidateId = pd.candidateId
        LEFT JOIN
            interview i ON i.id = fr.interviewId AND i.createdBy = fr.candidateId
        LEFT JOIN
            preInterview pr ON pr.id = i.preInterviewId
        LEFT JOIN
            scps_transaction scps ON scps.preInterviewId = pr.id
        LEFT JOIN
            relavant_role rr ON rr.id = scps.position
        WHERE
            fr.review_status = 2
            AND rr.id =" . $roleId . "
            AND rr.id IS NOT NULL
            AND pd.salary IS NOT NULL
            AND pd.noticePeriod IS NOT NULL
            AND pd.workExperience IS NOT NULL
        GROUP BY
            rr.id, u.username";

        $queryData = mysqli_query($databaseConnection, $query);
        $data = mysqli_fetch_all($queryData, MYSQLI_ASSOC);

        if (mysqli_num_rows($queryData) > 0) {
            $total_data['data'] = $data;
            $total_data['status'] = 1;
            $to_encode = $total_data;
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "in Error while retrieving Student information."
            );
        }


    } else {
        $to_encode = array(
            'result' => "error",
            'status' => 0,
            'errorCode' => "in Error while retrieving Student information."
        );
    }
    echo json_encode($to_encode);
}
// node-api
else if (isset($_GET['getQuestionConversionToJson'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    // echo $json;
    $sId = $json['subjectId'];
    $json = $json['jsonData'];
    // echo  $subjectId ;
    if ($json !== null) {
        //Prepare the INSERT query for temp_ques_jenkins table
        $tableName = "temp_ques_bulkUploading";

        // Check if the table exists
        $tableExistsQuery = "SHOW TABLES LIKE '$tableName'";
        $result = $databaseConnection->query($tableExistsQuery);

        if ($result->num_rows > 0) {
            // Table already exists, so drop it before creating a new one (Optional)
            $dropTableQuery = "DROP TABLE IF EXISTS $tableName";

            $resultdropTableQuery = mysqli_query($databaseConnection, $dropTableQuery);
            if ($resultdropTableQuery) {
                //echo "drop Query executed successfully.";
            } else {
                //echo "Error executing the query: " . mysqli_error($databaseConnection);
            }
        }

        // Create the table
        $createTableQuery = "CREATE TABLE $tableName (
            id INT(10) AUTO_INCREMENT PRIMARY KEY,
            matc INT(10),
            isfollowUp VARCHAR(200),
            followUp VARCHAR(200),
            Subject_name VARCHAR(200),
            subject_id INT(10),
            Concept_name VARCHAR(200),
            concept_id INT(10),
            Topic_name VARCHAR(200),
            topic_id INT(10),
            Interview_Qns mediumtext,
            Short_Expected_Ans mediumtext,
            Qns_Diagram VARCHAR(200),
            Key_Skill_to_be_assessed VARCHAR(200),
            keyskill_id VARCHAR(200),
            moduleName VARCHAR(500),
            Qns_Level VARCHAR(200),
            Expected_Time_to_Ans VARCHAR(200),
            Thinking_Time VARCHAR(200),
            Is_Whiteboard_Required VARCHAR(200),
            Tutorial_Link VARCHAR(200),
            Timeline_of_tutorial_video VARCHAR(200),
            Student_Instruction VARCHAR(200),
            Type_of_Qns VARCHAR(200),
            Qns_CreatorName VARCHAR(200),
            Qns_ReviewerName VARCHAR(200),
            Qns_Creator INT(200),
            Qns_Reviewer INT(200),
            idk1 mediumtext,
            idk2 mediumtext,
            idk1Ans mediumtext,
            idk2Ans mediumtext,
            visualContent TEXT,
            scenario TEXT
        )";

        if ($databaseConnection->query($createTableQuery) === TRUE) {
            //echo "Table $tableName created successfully.";
        } else {
            //echo "Error creating table: " . $databaseConnection->error;
        }
        // Define a function to normalize field names flexibly
        function normalizeFieldName($field)
        {
            if (!$field || !is_string($field)) return '';

            // Convert to lowercase for easier matching
            $normalized = strtolower(trim($field));

            // Remove content within parentheses
            $normalized = preg_replace('/\([^)]*\)/', '', $normalized);

            // Remove "Note:" sections and everything after
            $normalized = preg_replace('/note:.*$/i', '', $normalized);

            // Remove "For Office Use ONLY" sections
            $normalized = preg_replace('/for office use only.*$/i', '', $normalized);

            // Remove periods, colons, and other punctuation (keep spaces for word matching)
            $normalized = preg_replace('/[.:;,!?]/', '', $normalized);

            // Clean up extra whitespace
            $normalized = trim(preg_replace('/\s+/', ' ', $normalized));

            // Explicit mapping for known field name variations
            $mappings = [
                // Topic / Problem Title
                'problem title'                                        => 'Topic_name',
                'topic name'                                           => 'Topic_name',
                'topic'                                                => 'Topic_name',

                // Case Study
                'case study'                                           => 'Case_Study',

                // Question text
                'question'                                             => 'Interview_Qns_Text',
                'interview qns text'                                   => 'Interview_Qns_Text',
                'question text'                                        => 'Interview_Qns_Text',
                'interview questions text'                                   => 'Interview_Qns_Text',

                // Key Skill
                'key skill to be assessed'                             => 'Key_Skill_to',
                'key skill'                                            => 'Key_Skill_to',

                // Module Name (optional)
                'module name'                                          => 'Module_Name',
                'module'                                               => 'Module_Name',

                // Solution
                'detailed complete solution'                           => 'Detailed_Complete_Solution',
                'solution'                                             => 'Detailed_Complete_Solution',
                'complete solution'                                    => 'Detailed_Complete_Solution',

                // Whiteboard
                'is whiteboard required by student to answer this qns' => 'Is_Whiteboard_Required',
                'is whiteboard required'                               => 'Is_Whiteboard_Required',
                'whiteboard'                                           => 'Is_Whiteboard_Required',

                // Question Level
                'qns level'                                            => 'Qns_Level',
                'question level'                                       => 'Qns_Level',
                'level'                                                => 'Qns_Level',

                // Expected Time
                'expected time to ans mins'                            => 'Expected__Time',
                'expected time to ans'                                 => 'Expected__Time',
                'time to ans'                                          => 'Expected__Time',
                'expected time'                                        => 'Expected__Time',

                // Type of Question
                'type of qns'                                          => 'Type_of_Qns',
                'type of question'                                     => 'Type_of_Qns',
                'question type'                                        => 'Type_of_Qns',

                // Visual Content
                'visual content'                                       => 'Visual_Content',

                // Student Instruction
                'student instruction'                                  => 'Student_Instruction_It',

                // Question Number (follow-up logic)
                'question no'                                          => 'Question_No',
                'question number'                                      => 'Question_No',
                'qn no'                                                => 'Question_No',
                'q no'                                                 => 'Question_No',

                // Sequence
                'sequence'                                             => 'Sequence',
                'seq'                                                  => 'Sequence',

                // Match
                'match'                                                => 'Match',

                // Subject
                'subject name'                                         => 'Subject_name',

                // Diagram
                'qns diagram paste'                                    => 'Qns_Diagram_Paste',
                'qns diagram'                                          => 'Qns_Diagram_Paste',
                'diagram'                                              => 'Qns_Diagram_Paste',

                // IDK fields
                'idk1'                                                 => 'idk1',
                'idk2'                                                 => 'idk2',
                'idk1ans'                                              => 'idk1Ans',
                'idk1 ans'                                             => 'idk1Ans',
                'idk2ans'                                              => 'idk2Ans',
                'idk2 ans'                                             => 'idk2Ans',
            ];

            if (isset($mappings[$normalized])) {
                return $mappings[$normalized];
            }

            // Fallback: strip unwanted chars, take first 3 words joined by underscore
            $cleanField = preg_replace('/[^\w\s]/', '', $field);
            $words = array_values(array_filter(explode(' ', $cleanField), function ($w) {
                return strlen($w) > 0;
            }));
            return implode('_', array_slice($words, 0, 3));
        }
        // Array to store fields with invalid data
        $invalidFields = array();
        $visualContent = null; // Default value
        // Define a function to validate each field and store the value in respective variables
        function validateDataAndStore($field, $value)
        {
            // echo "field ". $field;
            global $match, $sequence, $questionNo, $subjectName, $topicName, $interviewQns, $qnsDiagram, $detailedSolution, $studentInstruction, $whiteboardRequired, $keySkill, $qnsLevel, $typeOfQns, $Expected_Time_to_Ans, $invalidFields, $idk1, $idk2, $idk1Ans, $idk2Ans, $visualContent, $scenario, $moduleName;
            switch ($field) {
                case "idk1":
                    if (is_string($value) && trim($value) !== '') {
                        $idk1 = trim($value);
                    } else {
                        $invalidFields[] = [
                            'field' => $field,
                            'sequence' => $sequence
                        ];
                    }
                    break;
                case "idk1Ans":
                    if (is_string($value) && trim($value) !== '') {
                        $idk1Ans = trim($value);
                    } else {
                        $invalidFields[] = [
                            'field' => $field,
                            'sequence' => $sequence
                        ];
                    }
                    break;
                case "idk2":
                    if (is_string($value) && trim($value) !== '') {
                        $idk2 = trim($value);
                    } else {
                        $invalidFields[] = [
                            'field' => $field,
                            'sequence' => $sequence
                        ];
                    }
                    break;
                case "idk2Ans":
                    if (is_string($value) && trim($value) !== '') {
                        $idk2Ans = trim($value);
                    } else {
                        $invalidFields[] = [
                            'field' => $field,
                            'sequence' => $sequence
                        ];
                    }
                    break;
                case "Match":
                    if (is_numeric($value) && intval($value) > 0) {
                        $match = $value;
                    } else {
                        $match = null;
                    }
                    break;
                case "Sequence":
                    if (is_numeric($value) && intval($value) > 0) {
                        $sequence = $value;
                    } else {
                        $invalidFields[] = [
                            'field' => $field,
                            'sequence' => $sequence
                        ];
                    }
                    break;
                case "Question_No":
                    if ((is_numeric($value) || is_string($value)) && trim($value) !== '') {
                        $questionNo = $value;
                    } else {
                        $invalidFields[] = [
                            'field' => $field,
                            'sequence' => $sequence
                        ];
                    }
                    break;
                case "Subject_name":
                    // if (is_string($value) && trim($value) !== '') {
                    //     $subjectName = trim($value);
                    // } else {
                    //     $invalidFields[] = [
                    //         'field' => $field,
                    //         'sequence' => $sequence
                    //     ];
                    // }
                    break;
                case "Topic_name":
                    if (is_string($value) && trim($value) !== '') {
                        $topicName = trim($value);
                    } else {
                        $invalidFields[] = [
                            'field' => $field,
                            'sequence' => $sequence
                        ];
                    }
                    break;
                case "Interview_Qns_Text":
                    if (is_string($value) && trim($value) !== '') {
                        $interviewQns = $value;
                    } else {
                        $invalidFields[] = [
                            'field' => $field,
                            'sequence' => $sequence
                        ];
                    }
                    break;
                case "Qns_Diagram_Paste":
                    if (
                        $value === "" || 
                        strtoupper(trim($value)) === "NA" || 
                        strtoupper(trim($value)) === "N/A"
                    ) {
                        $qnsDiagram = null;
                    } else {
                        $qnsDiagram = $value;
                    }
                    break;
                case "Detailed_Complete_Solution":

                    $detailedSolution = '';
                    if (is_string($value) && trim($value) !== '') {
                        $detailedSolution = $value;

                    } else {
                        $invalidFields[] = [
                            'field' => $field,
                            'sequence' => $sequence
                        ];
                    }
                    break;
                case "Student_Instruction_It_will":
                    if (is_string($value) && trim($value) !== '') {
                        $studentInstruction = $value;
                    } else {
                        $invalidFields[] = [
                            'field' => $field,
                            'sequence' => $sequence
                        ];
                    }
                    break;
                case "Is_Whiteboard_Required":
                    if ($value === "Yes" || $value === "No") {
                        $whiteboardRequired = $value;
                    } else {
                        $invalidFields[] = [
                            'field' => $field,
                            'sequence' => $sequence
                        ];
                    }
                    break;
                case "Key_Skill_to":
                    if (is_string($value) && trim($value) !== '') {
                        $keySkill = trim($value);
                    } else {
                        $invalidFields[] = [
                            'field' => $field,
                            'sequence' => $sequence
                        ];
                    }
                    break;
                case "Module_Name":
                    // Optional field: store null when empty / NA style values
                    $valLower = strtolower(trim((string)$value));
                    if (
                        trim((string)$value) === '' ||
                        $valLower === 'na' ||
                        $valLower === 'n/a' ||
                        $valLower === 'not available'
                    ) {
                        $moduleName = null;
                    } else {
                        $moduleName = trim((string)$value);
                    }
                    break;
                case "Qns_Level":
                    if (is_string($value) && trim($value) !== '') {
                        $normalizedLevel = trim($value);
                        if (strcasecmp($normalizedLevel, 'Intermediate') === 0) {
                            $normalizedLevel = 'Average';
                        } elseif (strcasecmp($normalizedLevel, 'Advance') === 0) {
                            $normalizedLevel = 'Advanced';
                        }
                        $qnsLevel = $normalizedLevel;
                    } else {
                        $invalidFields[] = [
                            'field' => $field,
                            'sequence' => $sequence
                        ];
                    }
                    break;
                case "Type_of_Qns":
                    if (is_string($value) && trim($value) !== '') {
                        $typeOfQns = $value;
                    } else {
                        $invalidFields[] = [
                            'field' => $field,
                            'sequence' => $sequence
                        ];
                    }
                    break;
                case "Expected__Time":
                    if (is_numeric($value) && intval($value) > 0) {
                        // $Expected_Time_to_Ans = $value;
                        $Expected_Time_to_Ans = $value;
                        // echo "Data type of value: " . gettype($Expected_Time_to_Ans);
                        // echo "Value assigned to Expected_Time_to_Ans: " . $Expected_Time_to_Ans; 
                    } else {
                        $invalidFields[] = [
                            'field' => $field,
                            'sequence' => $sequence
                        ];
                    }
                    break;
                case "Visual_Content":
                    // Allow empty values or normalize them to null
                    $valLower = strtolower(trim($value));
                    if (empty($value) || 
                        $valLower === 'na' || 
                        $valLower === 'not available' ||
                        $valLower === 'n/a' ||
                        $valLower === 'no') {
                        $visualContent = null;
                    } else {
                        $visualContent = trim($value);
                    }
                    break;
                case "Case_Study":
                    // Allow empty values or normalize them to null
                    if (empty($value) || 
                        strtolower(trim($value)) === 'na' || 
                        strtolower(trim($value)) === 'not available' ||
                        strtolower(trim($value)) === 'n/a') {
                        $scenario = null;
                    } else {
                        $scenario = trim($value);
                    }
                    break;
                default:
                    // For unknown fields, check if the field starts with "Student_Instruction"
                    if (strpos($field, "Student_Instruction") === 0) {
                        if (is_string($value) && trim($value) !== '') {
                            $studentInstruction = $value;
                        } else {
                            $invalidFields[] = [
                                'field' => $field,
                                'sequence' => $sequence
                            ];
                        }
                    } else {
                        // For all other cases, add them to invalid fields
                        $invalidFields[] = [
                            'field' => $field,
                            'sequence' => $sequence
                        ];
                    }
                    break;
            }

        }

        //$numberOfRowsToDisplay = 4; // Change this to the number of rows you want to display
        $subjectName = '';

        foreach ($json as $question) {
            // $question = $json[$i];
            $sequence = '';
            $match = null;
            $questionNo = '';
            $subjectName = '';
            $topicName = '';
            $interviewQns = '';
            $qnsDiagram = '';
            $detailedSolution = '';
            $studentInstruction = '';
            $whiteboardRequired = '';
            $keySkill = '';
            $qnsLevel = '';
            $typeOfQns = '';
            $isfollowUp = '';
            $followUp = '';
            $Short_Expected_Ans = '';
            $Expected_Time_to_Ans = '';
            $idk1 = '';
            $idk2 = '';
            $idk1Ans = '';
            $idk2Ans = '';
            $visualContent = null;
            $scenario = null;
            $moduleName = null;

            // Normalize all field names using the flexible normalizeFieldName function,
            // then validate and store each value. If a key appears multiple times after
            // normalization, the first non-empty value wins
            $normalizedQuestion = [];
            foreach ($question as $field => $value) {

                // Skip __EMPTY fields created by XLSX reader
                if (strpos($field, '__EMPTY') !== false) {
                    continue;
                }
                $normalizedField = normalizeFieldName($field);
                if ($normalizedField !== '') {
                    if (!isset($normalizedQuestion[$normalizedField]) || $normalizedQuestion[$normalizedField] === '') {
                        $normalizedQuestion[$normalizedField] = $value;
                    }
                }
            }

            foreach ($normalizedQuestion as $field => $value) {
                validateDataAndStore($field, $value);
            }
            // echo "match: $match<br>";
            // echo "sequence: $sequence<br>";
            // echo "questionNo: $questionNo<br>";
            // echo "subjectName: $subjectName<br>";
            // echo "topicName: $topicName<br>";
            // echo "interviewQns: $interviewQns<br>";
            // echo "Short_Expected_Ans: $Short_Expected_Ans<br>";
            // echo "detailedSolution: $detailedSolution<br>";
            // echo "qnsDiagram: $qnsDiagram<br>";
            // echo "keySkill: $keySkill<br>";
            // echo "qnsLevel: $qnsLevel<br>";
            // echo "Expected_Time_to_Ans: $Expected_Time_to_Ans<br>";
            // echo "whiteboardRequired: $whiteboardRequired<br>";
            // echo "studentInstruction: $studentInstruction<br>";
            // echo "typeOfQns: $typeOfQns<br>";
            // echo "idk1: $idk1<br>";
            // echo "idk2: $idk2<br>";


            if (is_numeric($match) && intval($match) > 0) {


            $queryToInsert = "INSERT INTO $tableName (
                matc, isfollowUp, followUp, Subject_name, Topic_name, Interview_Qns, Short_Expected_Ans, Qns_Diagram, Key_Skill_to_be_assessed, moduleName, Qns_Level, Expected_Time_to_Ans, Is_Whiteboard_Required, Student_Instruction, Type_of_Qns, idk1, idk2, idk1Ans, idk2Ans, visualContent, scenario
            ) VALUES (
                '" . mysqli_real_escape_string($databaseConnection, $match) . "',
                '" . mysqli_real_escape_string($databaseConnection, $sequence) . "',
                '" . mysqli_real_escape_string($databaseConnection, $questionNo) . "',
                '" . mysqli_real_escape_string($databaseConnection, $subjectName) . "',
                '" . mysqli_real_escape_string($databaseConnection, $topicName) . "',
                '" . mysqli_real_escape_string($databaseConnection, $interviewQns) . "',
                '" . mysqli_real_escape_string($databaseConnection, $detailedSolution) . "',
                " . (
                    $qnsDiagram === null ? "NULL": "'" . mysqli_real_escape_string($databaseConnection, $qnsDiagram) . "'"
                ) . ",
                '" . mysqli_real_escape_string($databaseConnection, $keySkill) . "',
                " . ($moduleName === null ? "NULL" : "'" . mysqli_real_escape_string($databaseConnection, $moduleName) . "'") . ",
                '" . mysqli_real_escape_string($databaseConnection, $qnsLevel) . "',
                '" . mysqli_real_escape_string($databaseConnection, $Expected_Time_to_Ans) . "',
                '" . mysqli_real_escape_string($databaseConnection, $whiteboardRequired) . "',
                '" . mysqli_real_escape_string($databaseConnection, $studentInstruction) . "',
                '" . mysqli_real_escape_string($databaseConnection, $typeOfQns) . "',
                '" . mysqli_real_escape_string($databaseConnection, $idk1) . "',
                '" . mysqli_real_escape_string($databaseConnection, $idk2) . "',
                '" . mysqli_real_escape_string($databaseConnection, $idk1Ans) . "',
                '" . mysqli_real_escape_string($databaseConnection, $idk2Ans) . "',
                " . ($visualContent === null ? "NULL": "'" . mysqli_real_escape_string($databaseConnection, $visualContent) . "'") . ",
                " . ($scenario === null ? "NULL": "'" . mysqli_real_escape_string($databaseConnection, $scenario) . "'") . "
            )";



            } else {

            $queryToInsert = "INSERT INTO $tableName (
                isfollowUp, followUp, Subject_name, Topic_name, Interview_Qns, Short_Expected_Ans, Qns_Diagram, Key_Skill_to_be_assessed, moduleName, Qns_Level, Expected_Time_to_Ans, Is_Whiteboard_Required, Student_Instruction, Type_of_Qns, idk1, idk2, idk1Ans, idk2Ans, visualContent, scenario
            ) VALUES (
                '" . mysqli_real_escape_string($databaseConnection, $sequence) . "',
                '" . mysqli_real_escape_string($databaseConnection, $questionNo) . "',
                '" . mysqli_real_escape_string($databaseConnection, $subjectName) . "',
                '" . mysqli_real_escape_string($databaseConnection, $topicName) . "',
                '" . mysqli_real_escape_string($databaseConnection, $interviewQns) . "',
                '" . mysqli_real_escape_string($databaseConnection, $detailedSolution) . "',
                " . (
                    $qnsDiagram === null
                    ? "NULL"
                    : "'" . mysqli_real_escape_string($databaseConnection, $qnsDiagram) . "'"
                ) . ",
                '" . mysqli_real_escape_string($databaseConnection, $keySkill) . "',
                " . ($moduleName === null ? "NULL" : "'" . mysqli_real_escape_string($databaseConnection, $moduleName) . "'") . ",
                '" . mysqli_real_escape_string($databaseConnection, $qnsLevel) . "',
                '" . mysqli_real_escape_string($databaseConnection, $Expected_Time_to_Ans) . "',
                '" . mysqli_real_escape_string($databaseConnection, $whiteboardRequired) . "',
                '" . mysqli_real_escape_string($databaseConnection, $studentInstruction) . "',
                '" . mysqli_real_escape_string($databaseConnection, $typeOfQns) . "',
                '" . mysqli_real_escape_string($databaseConnection, $idk1) . "',
                '" . mysqli_real_escape_string($databaseConnection, $idk2) . "',
                '" . mysqli_real_escape_string($databaseConnection, $idk1Ans) . "',
                '" . mysqli_real_escape_string($databaseConnection, $idk2Ans) . "',
                " . ($visualContent === null ? "NULL" : "'" . mysqli_real_escape_string($databaseConnection, $visualContent) . "'") . ",
                " . ($scenario === null ? "NULL" : "'" . mysqli_real_escape_string($databaseConnection, $scenario) . "'") . "
            )";


            }

            $qsult = mysqli_query($databaseConnection, $queryToInsert);
            if (!$qsult) {
                echo "Error in query: " . mysqli_error($databaseConnection);
            }

        }



        if (empty($invalidFields)) {
            mysqli_query($databaseConnection, "UPDATE temp_ques_bulkUploading SET isfollowUp = isfollowUp + (SELECT id FROM questions ORDER BY id DESC LIMIT 1) - 1;");
            mysqli_query($databaseConnection, "UPDATE temp_ques_bulkUploading SET isfollowUp = 'Y' ,followUp = 'Parent' WHERE followUp REGEXP '^[0-9]+$';");

            // Propagate parent scenario to child questions:
            // Iterate rows in insert order; when a parent is encountered its scenario is captured,
            // and each subsequent child row inherits that scenario if its own is null/empty.
            mysqli_query($databaseConnection, "SET @parentScenario = NULL;");
            mysqli_query($databaseConnection, "UPDATE temp_ques_bulkUploading SET scenario = CASE WHEN isfollowUp = 'Y' AND followUp = 'Parent' THEN (@parentScenario := scenario) ELSE COALESCE(NULLIF(TRIM(scenario), ''), @parentScenario) END ORDER BY id ASC;");


            $sidquery = "UPDATE `temp_ques_bulkUploading` SET `subject_id`='$sId'";
            mysqli_query($databaseConnection, $sidquery);

            mysqli_query($databaseConnection, "UPDATE temp_ques_bulkUploading tk INNER JOIN (SELECT tk.id as tkId,tk.Key_Skill_to_be_assessed,GROUP_CONCAT(DISTINCT ks.id) as ids,GROUP_CONCAT(DISTINCT ks.key_skill) as key_skill FROM temp_ques_bulkUploading tk INNER JOIN key_skill ks ON FIND_IN_SET(ks.key_skill,tk.Key_Skill_to_be_assessed) GROUP BY tk.id) as temp ON tk.id = temp.tkId SET tk.keyskill_id = temp.ids;");


            mysqli_query($databaseConnection, "INSERT INTO `topic`(`name`) SELECT temp_ques_bulkUploading.Topic_name FROM `temp_ques_bulkUploading` WHERE temp_ques_bulkUploading.Topic_name NOT IN (SELECT topic.name FROM topic GROUP BY topic.name) GROUP BY Topic_name ORDER BY Topic_name ASC;");

            mysqli_query($databaseConnection, "UPDATE `temp_ques_bulkUploading` SET temp_ques_bulkUploading.topic_id = (SELECT topic.id FROM topic WHERE temp_ques_bulkUploading.Topic_name = topic.name LIMIT 1);");

            mysqli_query($databaseConnection, "update temp_ques_bulkUploading set Qns_Level='Average' where Qns_Level='Intermediate';");
            mysqli_query($databaseConnection, "update temp_ques_bulkUploading set Qns_Level='Advanced' where Qns_Level='Advance';");

            mysqli_query($databaseConnection, "update temp_ques_bulkUploading set Is_Whiteboard_Required='N' where Is_Whiteboard_Required='No';");
            mysqli_query($databaseConnection, "update temp_ques_bulkUploading set Is_Whiteboard_Required='Y' where Is_Whiteboard_Required='Yes';");



            $matchQns = mysqli_query($databaseConnection, "SELECT * FROM temp_ques_bulkUploading WHERE matc IS NOT NULL");

            if (mysqli_num_rows($matchQns) > 0) {
                while ($row = mysqli_fetch_assoc($matchQns)) {
                    // Prepare the UPDATE query
                    $updateQuery = "UPDATE `questions` SET 
                        `quesDiagram` = ?,
                        `questionText` = ?,
                        `questionType` = ?,
                        `key_skill_id` = ?,
                        `topic_id` = ?,
                        `answerDuration` = ?,
                        `shortExpectedAns` = ?,
                        `questionLevel` = ?,
                        `isWbRequired` = ?,
                        `instruction` = ?,
                        `moduleName` = ?,
                        `updatedAt` = NOW(),
                        `isActive` = 'N',
                        `expertApproval` = 'Y',
                        `idk1` = ?,
                        `idk2` = ?,
                        `idk1Ans` = ?,
                        `idk2Ans` = ?,
                        `visualContent` = ?,
                        `scenario` = ?
                        WHERE `id` = ?";

                    // Prepare the statement
                    $stmt = mysqli_prepare($databaseConnection, $updateQuery);

                    // Bind parameters
                    mysqli_stmt_bind_param(
                        $stmt,
                        "sssssssssssssssssi",
                        $row["Qns_Diagram"],
                        $row["Interview_Qns"],
                        $row["Type_of_Qns"],
                        $row["keyskill_id"],
                        $row["topic_id"],
                        $row["Expected_Time_to_Ans"],
                        $row["Short_Expected_Ans"],
                        $row["Qns_Level"],
                        $row["Is_Whiteboard_Required"],
                        $row["Student_Instruction"],
                        $row["moduleName"],
                        $row["idk1"],
                        $row["idk2"],
                        $row["idk1Ans"],
                        $row["idk2Ans"],
                        $row["visualContent"],
                        $row["scenario"],
                        $row["matc"]
                    );

                    // Execute the statement
                    if (mysqli_stmt_execute($stmt)) {
                    } else {
                        // echo "Error updating record: " . mysqli_error($databaseConnection);
                    }

                    // Close the statement
                    mysqli_stmt_close($stmt);
                }
            }



            $queryToInsert = "INSERT INTO `questions` (`youtubeId`, `quesDiagram`, `questionText`, `questionType`, `key_skill_id`, `topic_id`, `answerDuration`, `followUp`, `isFollowUp`, `shortExpectedAns`, `questionLevel`, `isWbRequired`, `instruction`, `moduleName`, `eligibleStreamId`, `subjectId`, `conceptId`, `tutorialLink`, `questionCreator`, `questionReviewer`, `updatedAt`, `isActive`, `expertApproval`,`idk1`, `idk2`,`idk1Ans`, `idk2Ans`, `visualContent`, `scenario`)
            SELECT '314664775', Qns_Diagram, Interview_Qns, Type_of_Qns, keyskill_id, topic_id, Expected_Time_to_Ans, followUp, isfollowUp, Short_Expected_Ans, Qns_Level, Is_Whiteboard_Required, Student_Instruction, moduleName, 17, Subject_id, concept_id, Tutorial_Link, Qns_Creator, Qns_Reviewer, NOW(), 'N', 'Y', idk1, idk2, idk1Ans, idk2Ans, visualContent, scenario FROM `temp_ques_bulkUploading` WHERE matc IS NULL";

            // echo "SQL Query: $queryToInsert";

            mysqli_query($databaseConnection, $queryToInsert);

            mysqli_query($databaseConnection, "UPDATE questions q SET q.isFollowUp=CASE WHEN q.isFollowUp!='Y' THEN q.id-1 ELSE q.isFollowUp END WHERE q.subjectId='$sId' AND q.id NOT IN(select matc from temp_ques_bulkUploading where matc is not NULL);");

            $to_encode = array(
                'data' => 'success',
                'data1' => '',
                'status' => 1
            );

        } else {
            //  echo "Invalid data found in the following fields:\n";
            foreach ($invalidFields as $invalidField) {
                //    echo "Field: " . $invalidField['field'] . ", Sequence: " . $invalidField['sequence'] . "\n";
            }
            $to_encode = array(
                'data' => 'success',
                'data1' => $invalidFields,
                'status' => 1
            );
        }
    } else {
        // Handle the case when jsonData is not found or JSON decoding failed
        $to_encode = array(
            'data' => 'none',
            'status' => -1
        );
    }
    echo json_encode($to_encode);

}
else if (isset($_GET['payment'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userData = array();
        $userId = getDecrypt($json['userData'])->userId;

        $interviewId = isset($json['interviewId']) ? $json['interviewId'] : NULL;
        $subscriptionType = isset($json['subscriptionType']) ? $json['subscriptionType'] : NULL;
        $subscriptionPlan = isset($json['subscriptionPlan']) ? $json['subscriptionPlan'] : NULL;

        $data = "select id,emailId,firstName,lastName,mobileNumber,userName from `users` where id='" . $userId . "'";
        $query = mysqli_query($databaseConnection, $data);

        if (mysqli_num_rows($query) >= 1) {
            $userData = mysqli_fetch_all($query, MYSQLI_ASSOC);


            // $merchantId = 'PGTESTPAYUAT86';
            // $apiKey="96434309-7796-489d-8924-ab56988a6076";

            $merchantId = 'M10ZNZ1IRGYQ';
            $apiKey = "9550b7de-8c6f-4fa7-b6ce-55e11a35e1f5";


            $redirectUrl = $api_url . '/index.php?payment-redirect';

            // Set transaction details
            $transaction_id = uniqid();
            $user_id = $userData[0]['id'];
            $name = $userData[0]['firstName'];
            $email = $userData[0]['emailId'];
            $mobile = $userData[0]['mobileNumber'];
            $description = 'Payment for Goprac';
            $amount = 49;
            // $amount = 2; 
            if ($subscriptionType == 'practice') {
                if ($subscriptionPlan == '6m') {
                    $amount = 4999;
                } else if ($subscriptionPlan == '3m') {
                    $amount = 2999;
                } else {
                    $amount = 499;
                }
            }


            $paymentData = array(
                'merchantId' => $merchantId,
                'merchantTransactionId' => $transaction_id,
                "merchantUserId" => "MUID123",
                'amount' => $amount * 100,
                'redirectUrl' => $redirectUrl,
                'redirectMode' => "POST",
                'callbackUrl' => $redirectUrl,
                // "merchantOrderId"=>$order_id,
                "mobileNumber" => $mobile,
                // "message"=>$description,
                "email" => $email,
                "shortName" => $name,
                "paymentInstrument" => array(
                    "type" => "PAY_PAGE",
                )
            );


            $jsonencode = json_encode($paymentData);
            $payloadMain = base64_encode($jsonencode);
            $salt_index = 1; //key index 1
            $payload = $payloadMain . "/pg/v1/pay" . $apiKey;
            $sha256 = hash("sha256", $payload);
            $final_x_header = $sha256 . '###' . $salt_index;
            $request = json_encode(array('request' => $payloadMain));


            // https://api-preprod.phonepe.com/apis/pg-sandbox/pg/v1/pay

            // "https://api.phonepe.com/apis/hermes/pg/v1/pay"



            $curl = curl_init();
            curl_setopt_array($curl, [
                CURLOPT_URL => "https://api.phonepe.com/apis/hermes/pg/v1/pay",
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => "",
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => "POST",
                CURLOPT_POSTFIELDS => $request,
                CURLOPT_HTTPHEADER => [
                    "Content-Type: application/json",
                    "X-VERIFY: " . $final_x_header,
                    "accept: application/json"
                ],
            ]);

            $response = curl_exec($curl);
            $err = curl_error($curl);

            curl_close($curl);

            if ($err) {
                $to_encode = array(
                    'result' => "info",
                    'status' => 0,
                    'errorCode' => "cURL Error #:" . $err
                );

            } else {
                $res = json_decode($response);
                // var_dump($res);
                if (isset($res->success) && $res->success == '1') {
                    $paymentCode = $res->code;
                    $paymentMsg = $res->message;
                    $payUrl = $res->data->instrumentResponse->redirectInfo->url;

                    $sql = "INSERT INTO payment_transaction (user_id, transaction_id, interview_id, subscriptionType, `status`, amount, updated_at, pg_status) VALUES (?, ?, ?, ?, 'CHECKOUT', ?, NOW(),?)";

                    $stmt = mysqli_prepare($databaseConnection, $sql);
                    mysqli_stmt_bind_param($stmt, "isisis", $user_id, $transaction_id, $interviewId, $subscriptionType, $amount, $paymentCode);

                    if (mysqli_stmt_execute($stmt)) {
                        $to_encode = array(
                            'status' => 1,
                            "url" => $payUrl
                        );
                    } else {
                        $to_encode = array(
                            'result' => "info",
                            'status' => 0,
                            'errorCode' => "error saving tansaction details." . mysqli_error($databaseConnection)
                        );
                    }
                    mysqli_stmt_close($stmt);
                    mysqli_close($databaseConnection);
                } else {
                    $to_encode = array(
                        'result' => "info",
                        'status' => 0,
                        'errorCode' => "error getting pay link.",
                        'pg message' => $res->message
                    );
                }
            }

        } else {
            $to_encode = array(
                'result' => "info",
                'status' => 0,
                'errorCode' => "No users available."
            );
        }

    } else {
        $to_encode = array(
            'result' => "info",
            'status' => 0,
            'errorCode' => "No data avaialble."
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['payment-redirect'])) {
    $res = $_POST;

    // echo '<pre>';
    // var_dump($res);
    // echo '</pre>';

    if (!isset($res["code"])) {
        $to_encode = array(
            'result' => "error",
            'errorCode' => 'Method Does Not exist for payment'
        );
        echo json_encode($to_encode);

    } else {


        // $merchantId = 'PGTESTPAYUAT86';
        // $apiKey="96434309-7796-489d-8924-ab56988a6076";


        $merchantId = 'M10ZNZ1IRGYQ';
        $apiKey = "9550b7de-8c6f-4fa7-b6ce-55e11a35e1f5";

        $salt_index = 1; //key index 1
        $payload = '/pg/v1/status/' . $res["merchantId"] . '/' . $res["transactionId"] . $apiKey;
        $sha256 = hash("sha256", $payload);
        $final_x_header = $sha256 . '###' . $salt_index;
        // $request = json_encode(array('request'=>$payloadMain)); 


        $curl = curl_init();

        // https://api.phonepe.com/apis/hermes
        // https://api-preprod.phonepe.com/apis/pg-sandbox

        curl_setopt_array($curl, [
            CURLOPT_URL => "https://api.phonepe.com/apis/hermes/pg/v1/status/" . $res['merchantId'] . "/" . $res['transactionId'],
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "GET",
            CURLOPT_HTTPHEADER => [
                "Content-Type: application/json",
                "X-VERIFY: " . $final_x_header,
                "X-MERCHANT-ID:" . $res["merchantId"]
            ],
        ]);

        $response = curl_exec($curl);
        $err = curl_error($curl);
        curl_close($curl);

        if ($err) {
            echo "cURL Error #:" . $err;
        } else {

            $final = json_decode($response);
            if (isset($final)) {
                // var_dump($final);
                // exit();

                $success = $final->success;
                $message = $final->message;
                // Access nested data
                $transactionId = $final->data->merchantTransactionId;
                $pgStatus = $final->code;


                if ($final->code == "PAYMENT_SUCCESS") {
                    $pgtransactionId = $final->data->transactionId;

                    $select_sql = "SELECT * FROM payment_transaction WHERE transaction_id = ?";
                    $select_stmt = mysqli_prepare($databaseConnection, $select_sql);
                    mysqli_stmt_bind_param($select_stmt, "s", $transactionId);

                    if (mysqli_stmt_execute($select_stmt)) {
                        $result = mysqli_stmt_get_result($select_stmt);

                        // Fetch the returned rows
                        while ($row = mysqli_fetch_assoc($result)) {


                            $id = $row['id'];
                            $user_id = $row['user_id'];
                            $transaction_id = $row['transaction_id'];
                            $interview_id = $row['interview_id'];
                            $code = $row['status'];
                            $amount = $row['amount'];
                            $subscriptionType = $row['subscriptionType'];
                            // echo $user_id;

                            // Proceed to update payment status for this row
                            $update_sql = "UPDATE payment_transaction SET `status` ='PAID', `pg_status` = ?, pg_transaction_id = ? WHERE transaction_id = ?";
                            $update_stmt = mysqli_prepare($databaseConnection, $update_sql);

                            mysqli_stmt_bind_param($update_stmt, "sss", $pgStatus, $pgtransactionId, $transaction_id);

                            if (mysqli_stmt_execute($update_stmt)) {

                                // echo $interview_id;
                                // echo $subscriptionType;

                                if (isset($interview_id)) {

                                    $update2_sql = "UPDATE connect_mentor SET `connectInterest` = 'paid' WHERE `candidateId` = ? and `interviewId`= ?";
                                    $update2_stmt = mysqli_prepare($databaseConnection, $update2_sql);
                                    mysqli_stmt_bind_param($update2_stmt, "is", $user_id, $interview_id);
                                    mysqli_stmt_execute($update2_stmt);

                                    $select_sessionid_sql = "SELECT interviewsessionid FROM feedback_request WHERE interviewID = '$interview_id'";
                                    $result = mysqli_query($databaseConnection, $select_sessionid_sql);

                                    if ($result) {
                                        if (mysqli_num_rows($result) > 0) {
                                            $row = mysqli_fetch_assoc($result);
                                            $interviewsessionid = $row['interviewsessionid'];
                                            mysqli_free_result($result);
                                            header('Location:' . $frontend_url . '/review?i=' . $interview_id . '&c=' . $user_id . '&s=' . $interviewsessionid . '&v=2');
                                        } else {
                                            header('Location:' . $frontend_url);
                                        }
                                    } else {
                                        echo "Query failed: " . mysqli_error($databaseConnection);
                                    }

                                } else {
                                    if ($subscriptionType == 'practice') {

                                        echo $user_id;

                                        $userDataSql = "SELECT u.firstName, u.emailId, u.mobileNumber, pd.resume FROM users u LEFT JOIN professionaldetails pd ON u.id = pd.candidateId WHERE u.id = $user_id";
                                        echo $userDataSql;
                                        $userDataSqlresult = mysqli_query($databaseConnection, $userDataSql);

                                        var_dump($userDataSqlresult);

                                        if ($userDataSqlresult) {
                                            if (mysqli_num_rows($userDataSqlresult) > 0) {
                                                $userDataRow = mysqli_fetch_assoc($userDataSqlresult);
                                                $phone_number = $userDataRow['mobileNumber'];
                                                $email = $userDataRow['emailId'];
                                                $resume = $userDataRow['resume'];
                                                $name = $userDataRow['firstName'];

                                                // var_dump($userDataRow);

                                                $queryToInsert = "INSERT INTO `register`(`roleId`,`subjectId`,`name`,`phone_no`,`email`,`source`,`registeredTime`,`resume`) VALUES ('22','1045'," . ($name == "NULL" ? 'NULL' : ("'" . $name . "'")) . "," . ($phone_number == "NULL" ? 'NULL' : ("'" . $phone_number . "'")) . "," . ($email == "NULL" ? 'NULL' : ("'" . $email . "'")) . ",'homepage',now()," . ($resume == "NULL" ? 'NULL' : ("'" . $resume . "'")) . ")";
                                                // echo $queryToInsert;
                                                $result = mysqli_query($databaseConnection, $queryToInsert);
                                                if ($result) {

                                                    // var_dump($result);

                                                    // Assign Default Practice
                                                    $practiceFrequency = 'sunday 7:00 PM Once';
                                                    $preId = '904';
                                                    $candidPreId = "INSERT INTO candidateInterviewMapping(`candidateId`,`emailId`, `preInterviewId`, `createdAt`, `practiceFrequency`) VALUES(" . ($user_id === NULL ? "NULL" : "'" . $user_id . "'") . ",'" . $email . "', '" . $preId . "', NOW(), '" . $practiceFrequency . "')";
                                                    $candidPreIdInsert = mysqli_query($databaseConnection, $candidPreId);

                                                    // Assign Default Practice
                                                    if ($candidPreIdInsert > 0) {

                                                        $frequencyArray = explode(',', $practiceFrequency);

                                                        // Get the first value
                                                        $firstFrequency = trim($frequencyArray[0]);
                                                        list($day, $time, $period, $freq) = explode(' ', $firstFrequency);

                                                        $scheduletime = $time . ' ' . $period;

                                                        $now = new DateTime();
                                                        $currentDayOfWeek = $now->format('l');

                                                        $daysToAdd = (7 + array_search(ucfirst(strtolower($day)), ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']) - $now->format('w')) % 7;
                                                        if ($currentDayOfWeek === ucfirst(strtolower($day))) {
                                                            $daysToAdd = 0;
                                                        }

                                                        $now->modify("+{$daysToAdd} days");
                                                        $scheduledate = $now->format('d F Y');
                                                        $interviewName = '';
                                                        $interviewLink = '';
                                                        if ($preId != '') {
                                                            $Query = mysqli_query($databaseConnection, "SELECT id, interviewName FROM preInterview WHERE id = '" . $preId . "'");
                                                            $Result = mysqli_fetch_assoc($Query);

                                                            if ($Result['id'] != NULL) {
                                                                $interviewLink = 'https://goprac.com/job?p=' . $Result['id'];
                                                            }

                                                            if ($Result['interviewName'] != NULL) {
                                                                $interviewName = $Result['interviewName'];
                                                                $interviewName = str_replace(array("\n", "\r"), ' ', $interviewName);
                                                                $interviewName = preg_replace('/\s+/', ' ', $interviewName);
                                                            }
                                                        }

                                                        $data = array();
                                                        $data["subject"] = $interviewName;
                                                        $data["name"] = $name;
                                                        $data["scheduletime"] = $scheduletime;
                                                        $data["scheduledate"] = $scheduledate;
                                                        $data["interviewlink"] = $interviewLink;

                                                        if ($phone_number != '') {
                                                            //whatsAppMsg($databaseConnection, '9767479189', $data, "practiceAssign");
                                                            whatsAppMsg($databaseConnection, $phone_number, $data, "practiceAssign");
                                                        }
                                                    }

                                                }
                                                header('Location:' . $frontend_url . '/dashboard');

                                            } else {
                                                header('Location:' . $frontend_url);
                                            }

                                        }

                                    } else {
                                        header('Location:' . $frontend_url);
                                    }

                                }


                            } else {
                                echo "Error In update: " . mysqli_error($databaseConnection);
                            }

                            // Close the update statement
                            mysqli_stmt_close($update_stmt);

                        }
                    } else {
                        echo "Error In Insert: " . mysqli_error($databaseConnection);
                    }
                } else {
                    $select_sql = "SELECT * FROM payment_transaction WHERE transaction_id = ?";
                    $select_stmt = mysqli_prepare($databaseConnection, $select_sql);
                    mysqli_stmt_bind_param($select_stmt, "s", $transactionId);

                    if (mysqli_stmt_execute($select_stmt)) {
                        $result = mysqli_stmt_get_result($select_stmt);

                        // Fetch the returned rows
                        while ($row = mysqli_fetch_assoc($result)) {

                            $id = $row['id'];
                            $user_id = $row['user_id'];
                            $transaction_id = $row['transaction_id'];
                            $interview_id = $row['interview_id'];
                            $code = $row['status'];
                            $amount = $row['amount'];

                            // Proceed to update payment status for this row
                            $update_sql = "UPDATE payment_transaction SET `status` ='FAILED', `pg_status` = ?  WHERE transaction_id = ?";
                            $update_stmt = mysqli_prepare($databaseConnection, $update_sql);

                            mysqli_stmt_bind_param($update_stmt, "ss", $pgStatus, $transaction_id);

                            if (mysqli_stmt_execute($update_stmt)) {

                                $select_sessionid_sql = "SELECT interviewsessionid FROM feedback_request WHERE interviewID = '$interview_id'";
                                $result = mysqli_query($databaseConnection, $select_sessionid_sql);

                                if ($result) {
                                    if (mysqli_num_rows($result) > 0) {
                                        $row = mysqli_fetch_assoc($result);
                                        $interviewsessionid = $row['interviewsessionid'];
                                        mysqli_free_result($result);
                                        // header('Location:'.$frontend_url.'/review?i='.$interview_id.'&c='.$user_id.'&s='.$interviewsessionid);
                                        header('Location:' . $frontend_url . '/payment?i=' . $interview_id);
                                    } else {
                                        header('Location:' . $frontend_url);
                                    }
                                } else {
                                    echo "Query failed: " . mysqli_error($databaseConnection);
                                }
                            } else {
                                echo "Error In update: " . mysqli_error($databaseConnection);
                            }
                            // Close the update statement
                            mysqli_stmt_close($update_stmt);
                        }
                    } else {
                        echo "Error In Insert: " . mysqli_error($databaseConnection);
                    }
                }
            } else {
                echo 'error...';
            }
        }

    }
} elseif (isset($_GET['getPaymentStatus'])) {
    // node-api
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['candidateId'];
        $interviewId = isset($json['interviewId']) ? $json['interviewId'] : NULL;
        $subscriptionType = isset($json['subscriptionType']) ? $json['subscriptionType'] : NULL;

        if (isset($json['subscriptionType'])) {

            $sql = "select status from payment_transaction where user_id='" . $candidateId . "' and subscriptionType = '$subscriptionType' ORDER BY
            CASE WHEN status = 'PAID' THEN 0 ELSE 1 END, status";

        } else {

            $sql = "select status from payment_transaction where user_id='" . $candidateId . "' and interview_id=" . $interviewId . " ORDER BY
            CASE WHEN status = 'PAID' THEN 0 ELSE 1 END, status";
        }


        // echo $sql;

        $result = mysqli_query($databaseConnection, $sql);



        if (mysqli_num_rows($result) >= 1) {
            $row = mysqli_fetch_assoc($result);
            $status = $row['status'];
            $to_encode = array(
                'status' => 1,
                'result' => $status
            );
        } else {
            $to_encode = array(
                'status' => 0,
            );
        }


    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "out Error whire retrieving user information."
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getfulldetailStatus'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $candidateId = $json['candidateId'];
        $interviewId = $json['interviewId'];
        $currentLoggedId = $json['currentLoggedId'];

        $sql = "SELECT full_details FROM users WHERE id= " . $currentLoggedId . " ";

        // echo $sql;

        $result = mysqli_query($databaseConnection, $sql);

        if ($result) {
            if (mysqli_num_rows($result) >= 1) {
                $row = mysqli_fetch_assoc($result);

                $to_encode = array(
                    'status' => 1,
                    'result' => $row['full_details']
                );
            } else {
                $to_encode = array(
                    'status' => 0,
                    'result' => null // or specify a default value
                );
            }
        } else {
            $to_encode = array(
                'status' => -1,
                'result' => "error",
                'errorCode' => "Error executing SQL query."
            );
        }
    } else {
        $to_encode = array(
            'status' => -1,
            'result' => "error",
            'errorCode' => "Error while decoding JSON data."
        );
    }

    echo json_encode($to_encode);
} else if (isset($_GET['getInterviewNameById'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if ($json) {
        $id = $json['interviewId'];

        $queryToFetch = "SELECT `name` FROM `interview` WHERE id=" . $id . "";

        $queryToFetchData = mysqli_query($databaseConnection, $queryToFetch);
        if ($queryToFetchData) {
            $details = mysqli_fetch_all($queryToFetchData, MYSQLI_ASSOC);

        }

        $query2 = "SELECT * FROM feedback_request WHERE interviewId = $id ";
        $result2 = mysqli_query($databaseConnection, $query2);

        if ($result2) {
            if (mysqli_num_rows($result2) > 0) {
                $details2 = mysqli_fetch_all($result2, MYSQLI_ASSOC);
                $to_encode = array(
                    'status' => 1,
                    'data' => $details,
                    'data2' => $details2
                );
            } else {
                $to_encode = array(
                    'status' => 0,
                    'data' => $details
                );
            }
        } else {
            $to_encode = array(
                'status' => -2,
                'data' => $details
            );
        }

    }
    echo json_encode($to_encode);
}
//Akash
elseif (isset($_GET['publish'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $val = $json['val'];



        if ($val == 1) {
            $update = "UPDATE preInterview set publish='Y' where id = '" . implode(',', $json['preInterviewId']) . "'";
            $query = mysqli_query($databaseConnection, $update);
            if ($query) {
                $to_encode = array(
                    'result' => "success",
                    'status' => 1,
                );
            } else {
                $to_encode = array(
                    'result' => "error",
                    'status' => 0,
                    'query' => $update
                );
            }
        } else if ($val == 2) {
            $update = "UPDATE preInterview set publish='L' where id = '" . implode(',', $json['preInterviewId']) . "'";
            $query = mysqli_query($databaseConnection, $update);
            if ($query) {
                $to_encode = array(
                    'result' => "success",
                    'status' => 2,
                );
            } else {
                $to_encode = array(
                    'result' => "error",
                    'status' => 0,
                    'query' => $update
                );
            }

        }



    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while updating publish"
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['approveAlternateQuestions'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    if (isset($json)) {
        $questionId = trim($json['questionId']);

        if (!empty($questionId)) {
            // Make sure the ID is properly escaped or validated to prevent SQL injection
            $questionId = mysqli_real_escape_string($databaseConnection, $questionId);

            $update = "UPDATE questions SET alternateQuestionStatus = '4' WHERE id = '$questionId'";

            $query = mysqli_query($databaseConnection, $update);

            if ($query) {
                $to_encode = array(
                    'result' => "success",
                    'status' => 1,
                );
            } else {
                $to_encode = array(
                    'result' => "error",
                    'status' => 0,
                    'query' => $update
                );
            }
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "questionId not available."
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "Error while setting alternateQuestionStatus"
        );
    }

    echo json_encode($to_encode);
}
// node-api
elseif (isset($_GET['fetchAlternateQuestionsFlag'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {

        $questionIds = rtrim($json['questionIds'], ',');
        if ($questionIds) {
            $update = "UPDATE questions set alternateQuestionStatus='0' where id IN(" . $questionIds . ")";

            // echo $update;

            $query = mysqli_query($databaseConnection, $update);
            if ($query) {
                $to_encode = array(
                    'result' => "success",
                    'status' => 1,
                );
            } else {
                $to_encode = array(
                    'result' => "error",
                    'status' => 0,
                    'query' => $update
                );
            }
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "not available."
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "Error while setting alternateQuestionStatus"
        );
    }
    echo json_encode($to_encode);
}
elseif (isset($_GET['deleteQuestionsById'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {

        $questionIds = rtrim($json['questionIds'], ',');
        if ($questionIds) {
            $update = "UPDATE questions set deleted_at=NOW() where id IN(" . $questionIds . ")";

            // echo $update;

            $query = mysqli_query($databaseConnection, $update);
            if ($query) {
                $to_encode = array(
                    'result' => "success",
                    'status' => 1,
                );
            } else {
                $to_encode = array(
                    'result' => "error",
                    'status' => 0,
                    'query' => $update
                );
            }
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "not available."
            );
        }
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "Error while updating questions"
        );
    }
    echo json_encode($to_encode);
}
elseif (isset($_GET['getInterviewProfilepreffields'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {

        $preInterviewId = $json['preInterviewId'][0];

        $values = array();
        $filter6 = "select fieldValue as skills from profilePreferences p where preference='Mandatory' and fieldName='skills' and preInterviewId = " . $preInterviewId . " ";

        $filter6Result = mysqli_query($databaseConnection, $filter6);

        $values['profilepreferences'] = mysqli_fetch_all($filter6Result, MYSQLI_ASSOC);

        $to_encode = array(
            'data' => $values,
            'status' => 1
        );
        echo json_encode($to_encode);
    }
} elseif (isset($_GET['getprofilepreffields'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {

        $preInterviewId = $json['preInterviewId'];
        $values = array();
        $filter1 = "SELECT id,cityName FROM locations where id not in (512,518,513,516,514,515,517,519) ORDER BY cityName ASC;";
        $filter1Result = mysqli_query($databaseConnection, $filter1);

        $values['locationList'] = mysqli_fetch_all($filter1Result, MYSQLI_ASSOC);
        $filter9 = "select * from profilePreferences where preInterviewId = " . $preInterviewId . " ";
        $filter9Result = mysqli_query($databaseConnection, $filter9);

        $values['profilePrefFields'] = mysqli_fetch_all($filter9Result, MYSQLI_ASSOC);


        $to_encode = array(
            'data' => $values,
            'status' => 1
        );
        echo json_encode($to_encode);
    }
} else if (isset($_GET['showscheduledpopup'])) {
    $data = @file_get_contents("php://input");
    $preInterviewId = $_GET['preInterviewId'];

    if (!empty($preInterviewId)) {
        // Fetch missedstudent_details
        $missedStudentDetailsQry = mysqli_query($databaseConnection, "SELECT * FROM (SELECT u.id AS candidate_id, ivs.emailId, ivs.company_id, ivs.scheduleTime, ivs.candidateName, ivs.mobileNumber, ivs.id AS interviewScheduleId, ivs.preInterviewId FROM interviewSchedule ivs LEFT JOIN users u ON u.emailId = ivs.emailId WHERE ivs.emailId IS NOT NULL AND u.id NOT IN (SELECT i.createdBy FROM interview i INNER JOIN feedback_request fr ON fr.interviewId = i.id AND fr.candidateId = i.createdBy WHERE i.companyId IS NOT NULL AND i.preInterviewId IS NOT NULL AND i.preInterviewId ='" . $preInterviewId . "' ) AND ivs.preInterviewId ='" . $preInterviewId . "'  UNION SELECT u.id AS candidate_id, ivs.emailId, ivs.company_id, ivs.scheduleTime, ivs.candidateName, ivs.mobileNumber, ivs.id AS interviewScheduleId, ivs.preInterviewId FROM interviewSchedule ivs LEFT JOIN users u ON u.emailId = ivs.emailId WHERE ivs.emailId IS NOT NULL AND ivs.preInterviewId ='" . $preInterviewId . "'  HAVING candidate_id IS NULL) AS t WHERE t.scheduleTime < NOW() ORDER BY t.scheduleTime DESC");
        $missedStudentDetails = mysqli_fetch_all($missedStudentDetailsQry, MYSQLI_ASSOC);

        // Fetch featurestudent_details
        $featureStudentDetailsQry = mysqli_query($databaseConnection, "SELECT * FROM (SELECT u.id AS candidate_id, ivs.emailId, ivs.company_id, ivs.scheduleTime, ivs.candidateName, ivs.mobileNumber, ivs.id AS interviewScheduleId, ivs.preInterviewId FROM interviewSchedule ivs LEFT JOIN users u ON u.emailId = ivs.emailId WHERE ivs.emailId IS NOT NULL AND u.id NOT IN (SELECT i.createdBy FROM interview i INNER JOIN feedback_request fr ON fr.interviewId = i.id AND fr.candidateId = i.createdBy WHERE i.companyId IS NOT NULL AND i.preInterviewId IS NOT NULL AND i.preInterviewId ='" . $preInterviewId . "' ) AND ivs.preInterviewId ='" . $preInterviewId . "' UNION SELECT u.id AS candidate_id, ivs.emailId, ivs.company_id, ivs.scheduleTime, ivs.candidateName, ivs.mobileNumber, ivs.id AS interviewScheduleId, ivs.preInterviewId FROM interviewSchedule ivs LEFT JOIN users u ON u.emailId = ivs.emailId WHERE ivs.emailId IS NOT NULL AND ivs.preInterviewId IS NOT NULL AND ivs.preInterviewId ='" . $preInterviewId . "'  HAVING candidate_id IS NULL) AS t WHERE t.scheduleTime >= NOW() ORDER BY t.scheduleTime DESC");
        $featureStudentDetails = mysqli_fetch_all($featureStudentDetailsQry, MYSQLI_ASSOC);

        $scheduled = mysqli_num_rows($featureStudentDetailsQry) + mysqli_num_rows($missedStudentDetailsQry);
        $toEncode = array(
            'misseddata' => $missedStudentDetails,
            'featuredata' => $featureStudentDetails,
            'count' => $scheduled
        );

        echo json_encode($toEncode);
    } else {
        $toEncode = array(
            'status' => 0,
            'result' => 'error',
            'errorCode' => 'out Error while retrieving interview information.',
        );
        echo json_encode($toEncode);
    }
} else if (isset($_GET['showincompletepopup'])) {

    $data = @file_get_contents("php://input");
    $preInterviewId = $_GET['preInterviewId'];

    if (!empty($preInterviewId)) {
        // $preInterviewId = $json['preInterviewId'];
        $data = "select u.firstName,u.mobileNumber,u.emailId,fbr.interviewSessionId,i.preInterviewId from feedback_request fbr inner join interview i on i.id=fbr.interviewId inner join users u on u.id=fbr.candidateId where  i.preInterviewId='" . $preInterviewId . "' and fbr.review_status=-4 and fbr.reasonOfRejection='incompleteInterview'";

        $query = mysqli_query($databaseConnection, $data);

        if (mysqli_num_rows($query) >= 1) {
            $values = mysqli_fetch_all($query, MYSQLI_ASSOC);
            $to_encode = array('incompleteStudent' => $values);
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "no info",
                'errorCode' => "no job found",
                'query' => $data
            );
        }

    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving interview information."
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['showrejectpopup'])) {

    $data = @file_get_contents("php://input");
    $preInterviewId = $_GET['preInterviewId'];

    if (!empty($preInterviewId)) {
        // $preInterviewId = $json['preInterviewId'];

        $data = "select u.firstName,u.mobileNumber,u.emailId,fbr.interviewSessionId,fbr.reasonOfRejection,i.preInterviewId from feedback_request fbr inner join interview i on i.id=fbr.interviewId inner join users u on u.id=fbr.candidateId where i.preInterviewId='" . $preInterviewId . "' and fbr.review_status=-4 and fbr.reasonOfRejection!='incompleteInterview'";

        $query = mysqli_query($databaseConnection, $data);

        if (mysqli_num_rows($query) >= 1) {
            $values = mysqli_fetch_all($query, MYSQLI_ASSOC);
            $to_encode = array('rejectedStudent' => $values);
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "no info",
                'errorCode' => "no job found",
                'query' => $data
            );
        }

    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving interview information."
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['showinprogresspopup'])) {

    $data = @file_get_contents("php://input");

    $preInterviewId = $_GET['preInterviewId'];
    $userType = $_GET['userType'];
    if (!empty($preInterviewId)) {
        // if ($userType == 'corporate') {
        // $preInterviewId = $json['preInterviewId'];
        $data = "select u.firstName,u.mobileNumber,u.emailId,fbr.interviewSessionId,fbr.review_status,i.preInterviewId from feedback_request fbr inner join interview i on i.id=fbr.interviewId inner join users u on u.id=fbr.candidateId where i.preInterviewId='" . $preInterviewId . "' and fbr.review_status in(0,1,-2)";

        $query = mysqli_query($databaseConnection, $data);
        // }
        if (mysqli_num_rows($query) >= 1) {
            $values = mysqli_fetch_all($query, MYSQLI_ASSOC);
            $to_encode = array('inprogressStudent' => $values);
        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "no info",
                'errorCode' => "no job found",
                'query' => $data
            );
        }

    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving interview information."
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['interviewactivitypolling'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    // print_r($_GET);
    // print_r($_POST);

    $interviewId = $json['interviewId'];
    if (!empty($interviewId)) {
        $data = "select id from interview i  where i.id='" . $interviewId . "'";

        $query = mysqli_query($databaseConnection, $data);
        // }
        if (mysqli_num_rows($query) >= 1) {
            $values = mysqli_fetch_all($query, MYSQLI_ASSOC);

            $stmt = $databaseConnection->prepare("UPDATE interview SET last_activity_at = NOW() WHERE id = ?");
            $stmt->bind_param("i", $interviewId);
            if ($stmt->execute()) {
                // $to_encode = array('id' => $values);
                $to_encode = array(
                    'status' => 1,
                    'result' => "success",
                    'message' => "activity recorded"
                );
            } else {
                $to_encode = array(
                    'status' => 0,
                    'result' => "error",
                    // 'code' => $stmt->error,
                    'errorCode' => "out Error while retrieving interview information."
                );
            }

            $stmt->close();


        } else {
            $to_encode = array(
                'status' => 0,
                'result' => "no info",
                'errorCode' => "no interview found",
                'query' => $data
            );
        }

    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error",
            'errorCode' => "out Error while retrieving interview information."
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getjobname'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    $flag = $json['flag'];
    $companyflag = $json['company_id'];

    if ($json['userType'] == 'corporate') {

        $sql = "select interviewName as name,id,company_id,serviceType from preInterview where interviewName is not null and serviceType ='IAS' and id in (SELECT preinterviewId FROM preInterview_corporate WHERE userId='" . $json['userId'] . "')order by id desc";
    } else {
        if (!empty($json['company_id']) && $flag == 1) {
            if (is_array($json['company_id'])) {
                $roleId = implode(',', $json['company_id']);
            } else {
                $roleId = $json['company_id'];
            }
            // and serviceType !='IAS'
            $sql = "select interviewName as name,id,company_id,serviceType from preInterview where interviewName is not null  and company_id IN (" . $roleId . ")  order by id desc";
        } elseif (!empty($json['company_id']) && $flag == 0) {
            if (is_array($json['company_id'])) {
                $roleId = implode(',', $json['company_id']);
            } else {
                $roleId = $json['company_id'];
            }

            $sql = "select interviewName as name,id,company_id,serviceType from preInterview where interviewName is not null and interviewStatus ='Active' and company_id IN (" . $roleId . ")  order by id desc";
        } elseif ($companyflag == '' && $flag == 1) {

            $sql = "select interviewName as name,id,company_id,serviceType from preInterview where interviewName is not null order by id desc";
        } elseif ($flag == 3) {

            // $sql = "select interviewName as name,id,company_id,serviceType from preInterview where interviewName is not null and interviewStatus ='Active' and apmReady ='Y' order by id desc";
            $sql = "select pr.interviewName as name,pr.id,pr.company_id,pr.serviceType,pr.publish from preInterview pr inner join promotion p on pr.id=p.preInterviewId where pr.interviewName is not null and pr.interviewStatus ='Active' and pr.publish = 'Y' and p.jobpromotion = 'I' order by id desc";

        } elseif ($flag == 4) {

            // $sql = "select interviewName as name,id,company_id,serviceType from preInterview where interviewName is not null and interviewStatus ='Active' and apmReady ='Y' order by id desc";
            // $sql = "select pr.interviewName as name,pr.id,pr.company_id,pr.serviceType,pr.publish from preInterview pr where 1 order by id desc";
            $sql = "SELECT
                    pr.interviewName AS name,
                    pr.id,
                    pr.company_id,
                    pr.serviceType,
                    pr.publish
                FROM
                    preInterview pr
                LEFT JOIN
                    favourite_subject fs ON pr.interviewName = favourite_subject AND subjectType  = 'competency'
                WHERE
                    1
                ORDER BY
                    CASE WHEN fs.id IS NOT NULL THEN 0 ELSE 1 END,
                    pr.id DESC;";

        } else {

            $sql = "select interviewName as name,id,company_id,serviceType from preInterview where interviewName is not null and interviewStatus ='Active'  and interviewType!='Practice' order by id desc";
        }
    }

    // echo  $sql;
    // Execute the query
    $subject_query = mysqli_query($databaseConnection, $sql);
    $values = array();
    if ($subject_query) {
        if (mysqli_num_rows($subject_query) > 0) {
            $values['jobname'] = mysqli_fetch_all($subject_query, MYSQLI_ASSOC);
        } else {
            $to_encode = array(
                'result' => 'success',
                'status' => 0,
                'message' => 'no data found',
            );
        }
    }
    $rsql = "select * from recruiterList";
    $recruiter_query = mysqli_query($databaseConnection, $rsql);
    if ($recruiter_query) {
        if (mysqli_num_rows($recruiter_query) > 0) {
            $values['recruiterlist'] = mysqli_fetch_all($recruiter_query, MYSQLI_ASSOC);
        } else {
            $to_encode = array(
                'result' => 'success',
                'status' => 0,
                'message' => 'no data found',
            );
        }
    }

    $filter8 = "SELECT id,cityName FROM locations ORDER BY cityName ASC;";
    $filter8Result = mysqli_query($databaseConnection, $filter8);
    if ($filter8Result) {
        if (mysqli_num_rows($filter8Result) > 0) {
            $values['locationList'] = mysqli_fetch_all($filter8Result, MYSQLI_ASSOC);
        } else {
            $to_encode = array(
                'result' => 'success',
                'status' => 0,
                'message' => 'no data found',
            );
        }
    }
    $filter9 = "select favourite_subject as name,id from favourite_subject where active='Y' ";

    $filter9Result = mysqli_query($databaseConnection, $filter9);
    if ($filter9Result) {
        $values['skills'] = mysqli_fetch_all($filter9Result, MYSQLI_ASSOC);
    }

    // $departmentsSql = "SELECT * FROM departments";
    // $departments = mysqli_query($databaseConnection,$departmentsSql);
    // $values['departments'] = mysqli_fetch_all($departments,MYSQLI_ASSOC);

    // $subDepartmentsSql = "SELECT * FROM sub_departments ";
    // $filter2Result = mysqli_query($databaseConnection,$subDepartmentsSql);
    // $values['sub_departments'] = mysqli_fetch_all($filter2Result,MYSQLI_ASSOC);

    // $roleDepSubdepSql = "SELECT * FROM role_department_subdepartment";
    // $roleDepSubdep = mysqli_query($databaseConnection,$roleDepSubdepSql);
    // $values['roleDepSubdep'] = mysqli_fetch_all($roleDepSubdep,MYSQLI_ASSOC);

    // $filter2 = "SELECT * FROM relavant_role WHERE active = 'Y' ORDER BY id DESC";
    // $filter2Result = mysqli_query($databaseConnection,$filter2);
    // $values['roles'] = mysqli_fetch_all($filter2Result,MYSQLI_ASSOC);

    echo json_encode($values);
} elseif (isset($_GET['getPracticeFilter'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    $values = array();

    // roles
    $role_query = mysqli_query($databaseConnection, "SELECT DISTINCT rr.id, rr.name AS role FROM relavant_role rr INNER JOIN role_subject rs ON rr.id = rs.roleId WHERE rr.active = 'Y' order by rr.id;");

    $values['role'] = mysqli_fetch_all($role_query, MYSQLI_ASSOC);

    // competency skills / subjects
    $competencySkill_query = mysqli_query($databaseConnection, "SELECT DISTINCT skill.id, role.id as roleId, skill.favourite_subject AS name, CASE WHEN role.id is null then 'Other' ELSE role.name END as role
            FROM favourite_subject skill
            LEFT JOIN role_subject map ON map.subjectId = skill.id
            LEFT JOIN relavant_role role ON role.id = map.roleId
            WHERE skill.subjectType = 'competency' AND skill.active = 'Y'
            order by skill.id");

    $values['competencySkill'] = mysqli_fetch_all($competencySkill_query, MYSQLI_ASSOC);


    // $sql = "select interviewName as name,id from preInterview where interviewType='Practice' and interviewExpireDate > curDate() order by id desc";
    // $subject_query = mysqli_query($databaseConnection, $sql);

    // $sql1 = "select interviewName as name,id from preInterview where interviewType='Practice' order by id desc";

    // $subject_query1 = mysqli_query($databaseConnection, $sql1);

    // $values = array();
    // if ($subject_query) {
    //     if (mysqli_num_rows($subject_query) > 0) {
    //         $values['practiceList'] = mysqli_fetch_all($subject_query, MYSQLI_ASSOC);
    //         if ($subject_query1) {
    //             if (mysqli_num_rows($subject_query1) > 0) {
    //                 $values['jobList'] = mysqli_fetch_all($subject_query1, MYSQLI_ASSOC);
    //             }
    //         }
    //     } else {
    //         $to_encode = array(
    //             'result' => 'success',
    //             'status' => 0,
    //             'message' => 'no data found',
    //         );
    //     }
    // }

    echo json_encode($values);
} elseif (isset($_GET['getCompanyFilter'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    $sql = "select id, name as companyName from aspiration_company order by id desc";
    $subject_query = mysqli_query($databaseConnection, $sql);

    $values = array();
    if ($subject_query) {
        if (mysqli_num_rows($subject_query) > 0) {
            $values['companyList'] = mysqli_fetch_all($subject_query, MYSQLI_ASSOC);
        } else {
            $to_encode = array(
                'result' => 'success',
                'status' => 0,
                'message' => 'no data found',
            );
        }
    }

    echo json_encode($values);
} elseif (isset($_GET['getPendingInterview'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    $userId = $json['userId'];
    $userType = $json['userType'];
    $limit = $json['limit'];
    $start = ($json['page'] - 1) * $limit;
    $limit_query = $limit == 0 ? "" : " limit " . $start . "," . $limit;


    $sql = "select ac.name as company,pr.interviewStartDate, pr.interviewName as name,pr.id as preId,pr.company_id,pr.serviceType,pr.pendingInterviews, CASE
           WHEN pr.pendingInterviews = 'Y' AND pr.publish = 'N' THEN 'Interview Pending / APM Pending'
           WHEN pr.publish = 'N' THEN 'APM Pending'
           WHEN pr.pendingInterviews = 'Y' THEN 'Interview Pending'
           WHEN pr.pendingInterviews = 'NR' THEN 'No Interview'
           ELSE NULL END AS status from preInterview pr inner join aspiration_company ac on pr.company_id = ac.id where pr.interviewName is not null and (pr.pendingInterviews = 'Y' AND (pr.publish = 'N' OR pr.publish = 'Y'))  OR  (pr.pendingInterviews = 'NR' AND pr.publish = 'N') order by pr.interviewStartDate desc " . $limit_query . "";


    // echo $sql;
    // exit();
    $subject_query = mysqli_query($databaseConnection, $sql);
    $countData = "select pr.id as preId from preInterview pr inner join aspiration_company ac on pr.company_id = ac.id where pr.interviewName is not null and (pr.pendingInterviews = 'Y' AND (pr.publish = 'N' OR pr.publish = 'Y'))  OR  (pr.pendingInterviews = 'NR' AND pr.publish = 'N') order by pr.interviewStartDate desc";
    $count_query = mysqli_query($databaseConnection, $countData);

    $values = array();
    if ($subject_query) {
        if (mysqli_num_rows($subject_query) > 0) {
            $values['interviewpending'] = mysqli_fetch_all($subject_query, MYSQLI_ASSOC);
            // Iterate over each item in $values['interviewpending']
            foreach ($values['interviewpending'] as &$interview) {
                // Extract preId
                $preId = $interview['preId'];

                // Execute query to count schedules for this preId
                // $schedule_query = "SELECT id, candidateName, mobileNumber, scheduleTime, candidateJobStatus schedule_count FROM interviewSchedule WHERE preInterviewId = $preId and candidateStatus in ('Client Shortlist','Resume Shared','Interview Scheduled')";
                $schedule_query = "SELECT id, candidateName, mobileNumber, scheduleTime,firstScheduleDate, candidateStatus FROM interviewSchedule WHERE preInterviewId = $preId AND (candidateStatus IN ('Client Shortlisted', 'Profile Shared', 'Interview Scheduled', 'applied') OR (candidateStatus IS NULL AND scheduleTime IS NOT NULL))";

                // Perform the query
                $schedule_result = mysqli_query($databaseConnection, $schedule_query);


                // Check if query was successful
                if ($schedule_result) {

                    // Assign the schedule count to the current interview
                    $interview['schedule_info'] = mysqli_fetch_all($schedule_result, MYSQLI_ASSOC);
                    // $interview['schedule_Early'] = $schedule_row1['scheduleTime'];
                } else {
                    // Handle query error
                    // For example:
                    // echo "Error: " . mysqli_error($conn);
                }

                $schedule_queryStatus = "SELECT id, candidateName, mobileNumber, scheduleTime, 
      CASE 
          WHEN candidateStatus = 'Client Shortlist' THEN 'Client Shortlist'
          WHEN candidateStatus = 'Profile Shared' THEN 'Profile Shared'
          WHEN candidateStatus = 'applied' THEN 'applied'
          WHEN candidateStatus = 'Interview Scheduled' THEN 'Interview Scheduled' 
          WHEN ((scheduleTime != firstScheduleDate) AND(DATEDIFF(scheduleTime, NOW())) >= 1) THEN 'Re-Scheduled' 
          WHEN candidateStatus IS NULL THEN 'Interview Scheduled'
      END AS candidateJobStatus
      FROM interviewSchedule 
      WHERE preInterviewId = $preId AND (candidateStatus IN ('Client Shortlist', 'Profile Shared', 'Interview Scheduled','applied') OR (candidateStatus IS NULL AND scheduleTime IS NOT NULL)) order by scheduleTime desc";

                // Perform the query
                $schedule_queryStatusResult = mysqli_query($databaseConnection, $schedule_queryStatus);


                // Check if query was successful
                if ($schedule_queryStatusResult) {
                    $result = mysqli_fetch_assoc($schedule_queryStatusResult);
                    $interview['RescheduleCount'] = mysqli_num_rows($schedule_queryStatusResult);
                    //$interview['ScheduleCount'] = $result['InterviewScheduledCount'];

                } else {
                    $interview['RescheduleCount'] = '';
                    // $interview['ScheduleCount'] ='' ;


                }



            }
            $values['count'] = mysqli_num_rows($count_query);
        } else {
            $to_encode = array(
                'result' => 'success',
                'status' => 0,
                'message' => 'no data found',
            );
        }
    }
    echo json_encode($values);
} else if (isset($_GET['gettractionReportData'])) {
    // this method is added by arun on 23 Mar 2023 to fetch the work Report data
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if ($json) {
        $userId = $json['userId'];
        $userType = $json['userType'];
        $filterQry = '';
        $condition = '';

        $values = array();
        $values1 = array();
        $values3 = array();


        if ($json['serviceType'] != '' && $json['serviceType'] != null) {

            $condition .= " and pr.serviceType ='" . $json['serviceType'] . "'";

        }


        if ($json['scheduleFrom'] != "" && $json['scheduleTo'] == "") {
            $condition .= " and (date_format(pr.interviewStartDate,'%Y-%m-%d')) >= '" . $json['scheduleFrom'] . "'";

        }

        if ($json['scheduleFrom'] == "" && $json['scheduleTo'] != "") {
            $condition .= " and (date_format(pr.interviewStartDate,'%Y-%m-%d')) <= '" . $json['scheduleTo'] . "'";
        }

        if ($json['scheduleFrom'] != "" && $json['scheduleTo'] != "") {
            $condition .= " and (date_format(pr.interviewStartDate,'%Y-%m-%d')) >= '" . $json['scheduleFrom'] . "' and (date_format(pr.interviewStartDate,'%Y-%m-%d')) <= '" . $json['scheduleTo'] . "'";
        }

        $query1 = "SELECT DISTINCT pr.id AS preInterviewId 
                        FROM preInterview pr 
                        INNER JOIN aspiration_company ac ON ac.id = pr.company_id 
                        INNER JOIN interviewSchedule isc ON isc.preInterviewId = pr.id 
                        WHERE pr.id is not null AND pr.publish='Y' 
                        " . $condition . "
                        ORDER BY pr.id DESC ";

        //  echo $query1;
        //     exit();

        $_query1 = mysqli_query($databaseConnection, $query1);
        $values1['count'] = mysqli_num_rows($_query1);

        $query3 = "SELECT DISTINCT pr.id AS preInterviewId 
                    FROM preInterview pr 
                    INNER JOIN aspiration_company ac ON ac.id = pr.company_id 
                    INNER JOIN interviewSchedule isc ON isc.preInterviewId = pr.id 
                    WHERE pr.id is not null AND pr.apmReady='Y' 
                    " . $condition . "
                    ORDER BY pr.id DESC ";

        //  echo $query1;
        // exit();

        $_query3 = mysqli_query($databaseConnection, $query3);
        $values3['count'] = mysqli_num_rows($_query3);

        $resultArray = [];
        while ($row = mysqli_fetch_assoc($_query1)) {
            //Shrikant changed : 6/3/2024 Client Screen Reject
            //  $query2 = " select 
            //  t2.preInterviewId,
            //  t2.interviewId,
            //  count(distinct t2.emailId) as Scheduled ,
            //  COUNT(DISTINCT CASE WHEN t2.paymentstatus = 'Paid' THEN t2.emailId END) AS Paid,
            //  COUNT(DISTINCT CASE WHEN t2.paymentstatus = 'Checkout' THEN t2.emailId END) AS Checkout,
            //  COUNT(DISTINCT CASE WHEN t2.paymentstatus = 'Download' THEN t2.emailId END) AS Download,
            //  COUNT(DISTINCT CASE WHEN t2.paymentstatus = 'Viewed' THEN t2.emailId END) AS Viewed,
            //  count(distinct case when t2.clientShortlisted is not null then t2.emailId end) as clientShortlisted,
            //    count(distinct case when t2.shared is not null then t2.emailId end) as shared,
            //    count(distinct case when t2.Joined is not null then t2.emailId end) as Joined,
            //          count(distinct case when t2.Offered is not null then t2.emailId end) as Offered,
            //           count(distinct case when t2.dropOut is not null then t2.emailId end) as dropOut,
            //               count(distinct case when t2.recruiterreject is not null then t2.emailId end) as recruiterreject,
            //                     count(distinct case when t2.unAttended is not null then t2.emailId end) as unAttended,
            //                     count(distinct case when t2.forshared is not null then t2.emailId end) as forshared,
            //                     count(t2.suitability) as suitability ,
            //          count(distinct case when t2.interviewStatus in('Completed') then t2.emailId end) as Completed
            //           from (
            //              select t.* from (
            //              select fr.id as feedbackRequestId,isc.emailId,isc.interviewId,isc.scheduleTime,pr.id as preInterviewId,isc.recruiterId,(select rl.name from recruiterList rl left join users u on u.id=rl.corporateId where rl.id=isc.recruiterId) as recruiterName,(select concat(rl.name,'(',u.firstName,')') from recruiterList rl left join users u on u.id=rl.corporateId where rl.id=isc.recruiterId) as recruiter,
            //              CASE
            //              WHEN pay.status = 'PAID' THEN 'Paid'
            //              WHEN pay.status = 'CHECKOUT' THEN 'Checkout'
            //              WHEN dfr.viewedStatus = 'download' THEN 'Download'
            //              WHEN dfr.viewedStatus = 'Viewed' THEN 'Viewed'
            //              ELSE 'Not Viewed'
            //             END AS paymentstatus,
            //              case when pr.interviewName is null then (select name from aspiration_company where id=pr.company_id) else pr.interviewName end as interviewName,date_format(pr.interviewStartDate,'%Y-%c-%d') as 'postedOn', date_format(pr.interviewExpireDate,'%Y-%c-%d') as 'JobExpiryDate',
            //              case when (fr.id is not null and (fr.review_status=-4)) then 'Incomplete'  
            //              when (fr.id is not null and cit.completion_status is not null and fr.review_status in (0,1,-2)) then 'Assessment in Progress' 
            //              when (fr.id is not null and cit.completion_status is not null and fr.review_status=2) then 'Completed' 
            //              end as interviewStatus,
            //              case when (fr.id is not null and cit.completion_status is not null and fr.review_status=2) then fr.id end as 'Completed',
            //              case when (fr.id is null and (date_format(isc.recruiterScheduleDate,'%Y-%c-%d')=CURDATE())) then isc.emailId end as todaySchedule,   
            //              case when (fr.id is null and isc.scheduleTime>=now()) then isc.emailId end as futureScheduled,       
            //              case when ((fr.id is not null) and (isc.candidateStatus in('Profile Shared'))) then isc.emailId end  as 'shared',
            //              case when ((fr.id is not null) and (isc.candidateStatus in('Joined'))) then isc.emailId end as 'Joined',
            //              case when ((fr.id is not null) and (isc.candidateStatus in('Offered','Offer Dropped','Offer Accepted'))) then isc.emailId end as 'Offered',
            //              case when ((fr.id is not null) and (isc.candidateStatus in('Client Shortlisted'))) then isc.emailId end as 'clientShortlisted', 
            //              case when ((fr.id is not null) and (isc.candidateStatus in('Client Rejected','No Show','Offer Dropped','RNR','Recruiter Reject'))) then isc.emailId end  as 'dropOut',
            //              case when ((fr.id is not null ) and (isc.candidateStatus in('Client Rejected'))) then isc.emailId end  as 'clientreject',
            //              case when ((fr.id is not null ) and (isc.candidateStatus in('Recruiter Reject'))) then isc.emailId end  as 'recruiterreject',
            //              case when ((fr.id is not null and fr.review_status=2) and (isc.candidateStatus in('Client Rejected','No Show','Offer Dropped','Offer Accepted'))) then isc.emailId end  as 'forshared',
            //              case when ((fr.id is not null and fr.review_status=2) and (isc.candidateStatus in('UnAttended','Not Attended') or isc.candidateStatus is null)) then isc.emailId end  as 'unAttended', 
            //              case when (fr.suitability='Must meet') THEN  isc.emailId   end  as suitability ,    
            //              case when  (isc.candidateStatus is not null and isc.candidateStatus in('Profile Shared') and fr.id is not null )   
            //              then TIMESTAMPDIFF(DAY, isc.candidateStatusDate, NOW()) end as profileAge, 
            //              case when  (isc.candidateStatus is not null and isc.candidateStatus in('Client Shortlisted') and fr.id is not null )   
            //              then TIMESTAMPDIFF(DAY, isc.candidateStatusDate, NOW()) end as clientShortlistedAge,     
            //              case when (isc.candidateStatus is not null and isc.candidateStatusDate is not null and TIMESTAMPDIFF(DAY,isc.candidateStatusDate,now())>5 and fr.id is not null and (fr.review_status=-4)) then isc.emailId when (isc.candidateStatus is null and isc.candidateStatusDate is null and TIMESTAMPDIFF(DAY,fr.updatedAt,now())>5 and fr.id is not null and (fr.review_status=-4)) then isc.emailId end as IncompletedeadLead,                  
            //              pr.postedBy,pr.headcount,pr.targetResumeShared from interviewSchedule isc inner join preInterview pr on pr.id=isc.preInterviewId left join users u on u.emailId=isc.emailId left join interview i on i.id = isc.interviewId left join feedback_request fr on fr.interviewId=i.id left join candidate_interview_transection cit on cit.interviewId=i.id 
            //              LEFT JOIN detail_feedback_request dfr ON dfr.interviewId = i.id
            //              LEFT JOIN payment_transaction pay ON pay.interview_id = i.id
            //              where 1 and isc.emailId is not null and isc.preInterviewId=".$row['preInterviewId']." ".$condition." group by isc.emailId,fr.id desc order by isc.emailId,fr.review_status desc 
            //              ) as t group by t.interviewId) as t2 group by t2.preInterviewId ;";
            //shrikant commented : 28/3/2024
            //  $query2 = " select 
            //  t2.preInterviewId,
            //  t2.interviewId,
            //  count(distinct t2.emailId) as Scheduled ,
            //  COUNT(DISTINCT CASE WHEN t2.paymentstatus = 'Paid' THEN t2.emailId END) AS Paid,
            //  COUNT(DISTINCT CASE WHEN t2.paymentstatus = 'Checkout' THEN t2.emailId END) AS Checkout,
            //  COUNT(DISTINCT CASE WHEN t2.paymentstatus = 'Download' THEN t2.emailId END) AS Download,
            //  COUNT(DISTINCT CASE WHEN t2.paymentstatus = 'Viewed' THEN t2.emailId END) AS Viewed,
            //  count(distinct case when t2.clientShortlisted is not null then t2.emailId end) as clientShortlisted,
            //    count(distinct case when t2.shared is not null then t2.emailId end) as shared,
            //    count(distinct case when t2.Joined is not null then t2.emailId end) as Joined,
            //          count(distinct case when t2.Offered is not null then t2.emailId end) as Offered,
            //           count(distinct case when t2.dropOut is not null then t2.emailId end) as dropOut,
            //               count(distinct case when t2.recruiterreject is not null then t2.emailId end) as recruiterreject,
            //                     count(distinct case when t2.unAttended is not null then t2.emailId end) as unAttended,
            //                     count(distinct case when t2.forshared is not null then t2.emailId end) as forshared,
            //                     count(t2.suitability) as suitability ,
            //          count(distinct case when t2.interviewStatus in('Completed') then t2.emailId end) as Completed
            //           from (
            //              select t.* from (
            //              select fr.id as feedbackRequestId,isc.emailId,isc.interviewId,isc.scheduleTime,pr.id as preInterviewId,isc.recruiterId,(select rl.name from recruiterList rl left join users u on u.id=rl.corporateId where rl.id=isc.recruiterId) as recruiterName,(select concat(rl.name,'(',u.firstName,')') from recruiterList rl left join users u on u.id=rl.corporateId where rl.id=isc.recruiterId) as recruiter,
            //              CASE
            //              WHEN pay.status = 'PAID' THEN 'Paid'
            //              WHEN pay.status = 'CHECKOUT' THEN 'Checkout'
            //              WHEN dfr.viewedStatus = 'download' THEN 'Download'
            //              WHEN dfr.viewedStatus = 'Viewed' THEN 'Viewed'
            //              ELSE 'Not Viewed'
            //             END AS paymentstatus,
            //              case when pr.interviewName is null then (select name from aspiration_company where id=pr.company_id) else pr.interviewName end as interviewName,date_format(pr.interviewStartDate,'%Y-%c-%d') as 'postedOn', date_format(pr.interviewExpireDate,'%Y-%c-%d') as 'JobExpiryDate',
            //              case when ( (fr.review_status=-4)) then 'Incomplete'  
            //              when ( cit.completion_status is not null and fr.review_status in (0,1,-2)) then 'Assessment in Progress' 
            //              when ( cit.completion_status is not null and fr.review_status=2) then 'Completed' 
            //              end as interviewStatus,
            //              case when ( cit.completion_status is not null and fr.review_status=2) then fr.id end as 'Completed',
            //              case when (fr.id is null and (date_format(isc.recruiterScheduleDate,'%Y-%c-%d')=CURDATE())) then isc.emailId end as todaySchedule,   
            //              case when (isc.scheduleTime>=now()) then isc.emailId end as futureScheduled,       
            //              case when ((isc.candidateStatus in('Profile Shared'))) then isc.emailId end  as 'shared',
            //              case when ( (isc.candidateStatus in('Joined'))) then isc.emailId end as 'Joined',
            //              case when ( (isc.candidateStatus in('Offered','Offer Dropped','Offer Accepted'))) then isc.emailId end as 'Offered',
            //              case when ( (isc.candidateStatus in('Client Shortlisted'))) then isc.emailId end as 'clientShortlisted', 
            //              case when ((isc.candidateStatus in('Client Screen Reject','Client Duplicate Reject','Client Interview Reject','Candidate Withdrawal','No Show','Offer Dropped','RNR','Recruiter Reject'))) then isc.emailId end  as 'dropOut',
            //              case when ((isc.candidateStatus in('Client Screen Reject','Client Duplicate Reject','Client Interview Reject','Candidate Withdrawal'))) then isc.emailId end  as 'clientreject',
            //              case when ( (isc.candidateStatus in('Recruiter Reject'))) then isc.emailId end  as 'recruiterreject',
            //              case when ((fr.review_status=2) and (isc.candidateStatus in('Client Screen Reject','Client Duplicate Reject','Client Interview Reject','Candidate Withdrawal','No Show','Offer Dropped','Offer Accepted'))) then isc.emailId end  as 'forshared',
            //              case when (( fr.review_status=2) and (isc.candidateStatus in('UnAttended','Not Attended') or isc.candidateStatus is null)) then isc.emailId end  as 'unAttended', 
            //              case when (fr.suitability='Must meet') THEN  isc.emailId   end  as suitability ,    
            //              case when  (isc.candidateStatus is not null and isc.candidateStatus in('Profile Shared') and fr.id is not null )   
            //              then TIMESTAMPDIFF(DAY, isc.candidateStatusDate, NOW()) end as profileAge, 
            //              case when  (isc.candidateStatus is not null and isc.candidateStatus in('Client Shortlisted') and fr.id is not null )   
            //              then TIMESTAMPDIFF(DAY, isc.candidateStatusDate, NOW()) end as clientShortlistedAge,     
            //              case when (isc.candidateStatus is not null and isc.candidateStatusDate is not null and TIMESTAMPDIFF(DAY,isc.candidateStatusDate,now())>5 and fr.id is not null and (fr.review_status=-4)) then isc.emailId when (isc.candidateStatus is null and isc.candidateStatusDate is null and TIMESTAMPDIFF(DAY,fr.updatedAt,now())>5 and fr.id is not null and (fr.review_status=-4)) then isc.emailId end as IncompletedeadLead,                  
            //              pr.postedBy,pr.headcount,pr.targetResumeShared from interviewSchedule isc inner join preInterview pr on pr.id=isc.preInterviewId left join users u on u.emailId=isc.emailId left join interview i on i.id = isc.interviewId left join feedback_request fr on fr.interviewId=i.id left join candidate_interview_transection cit on cit.interviewId=i.id 
            //              LEFT JOIN detail_feedback_request dfr ON dfr.interviewId = i.id
            //              LEFT JOIN payment_transaction pay ON pay.interview_id = i.id
            //              where 1 and isc.emailId is not null and isc.preInterviewId=".$row['preInterviewId']." ".$condition." group by isc.emailId,fr.id desc order by isc.emailId,fr.review_status desc 
            //              ) as t group by t.interviewId,t.emailId) as t2 group by t2.preInterviewId ;";

            //Shrikant added : 28/3/2024
            $query2 = "select 
                                             t2.preInterviewId,
                                             t2.interviewId,
                                             count(distinct t2.emailId) as Scheduled ,
                                             count(DISTINCT CASE WHEN t2.interviewId is not null then t2.emailId end) as Taken,
                                             COUNT(DISTINCT CASE WHEN t2.paymentstatus = 'Paid' THEN t2.emailId END) AS Paid,
                                             COUNT(DISTINCT CASE WHEN t2.paymentstatus = 'Checkout' THEN t2.emailId END) AS Checkout,
                                             COUNT(DISTINCT CASE WHEN t2.paymentstatus = 'Pay' THEN t2.emailId END) AS Pay,
                                             COUNT(DISTINCT CASE WHEN t2.paymentstatus = 'Download' THEN t2.emailId END) AS Download,
                                             COUNT(DISTINCT CASE WHEN t2.paymentstatus = 'Viewed' THEN t2.emailId END) AS Viewed,
                                             count(distinct case when t2.clientShortlisted is not null then t2.emailId end) as clientShortlisted,
                                               count(distinct case when t2.shared is not null then t2.emailId end) as shared,
                                               count(distinct case when t2.Joined is not null then t2.emailId end) as Joined,
                                                     count(distinct case when t2.Offered is not null then t2.emailId end) as Offered,
                                                      count(distinct case when t2.dropOut is not null then t2.emailId end) as dropOut,
                                                          count(distinct case when t2.recruiterreject is not null then t2.emailId end) as recruiterreject,
                                                                count(distinct case when t2.unAttended is not null then t2.emailId end) as unAttended,
                                                                count(distinct case when t2.forshared is not null then t2.emailId end) as forshared,
                                                                count(t2.suitability) as suitability ,
                                                     count(distinct case when t2.interviewStatus in('Completed') then t2.emailId end) as Completed
                                                      from (
                                                         select t.* from (
                                                         select fr.id as feedbackRequestId,isc.emailId,isc.interviewId,isc.scheduleTime,pr.id as preInterviewId,isc.recruiterId,
                                                         CASE
                                                         WHEN pay.status = 'PAID' THEN 'Paid'
                                                         WHEN pay.status = 'CHECKOUT' THEN 'Checkout'
                                                         WHEN dfr.viewedStatus = 'pay' THEN 'Pay'
                                                         WHEN dfr.viewedStatus = 'download' THEN 'Download'
                                                         WHEN dfr.viewedStatus = 'Viewed' THEN 'Viewed'
                                                         ELSE 'Not Viewed'
                                                        END AS paymentstatus,
                                                         case when pr.interviewName is null then (select name from aspiration_company where id=pr.company_id) else pr.interviewName end as interviewName,date_format(pr.interviewStartDate,'%Y-%c-%d') as 'postedOn', date_format(pr.interviewExpireDate,'%Y-%c-%d') as 'JobExpiryDate',
                                                         case when ( (fr.review_status=-4)) then 'Incomplete'  
                                                         when ( cit.completion_status is not null and fr.review_status in (0,1,-2)) then 'Assessment in Progress' 
                                                         when ( cit.completion_status is not null and fr.review_status=2) then 'Completed' 
                                                         end as interviewStatus,
                                                         case when ( cit.completion_status is not null and fr.review_status=2) then fr.id end as 'Completed',
                                                         case when (fr.id is null and (date_format(isc.recruiterScheduleDate,'%Y-%c-%d')=CURDATE())) then isc.emailId end as todaySchedule,   
                                                         case when (isc.scheduleTime>=now()) then isc.emailId end as futureScheduled,       
                                                         case when ((isc.candidateStatus in('Profile Shared'))) then isc.emailId end  as 'shared',
                                                         case when ( (isc.candidateStatus in('Joined'))) then isc.emailId end as 'Joined',
                                                         case when ( (isc.candidateStatus in('Offered','Offer Dropped','Offer Accepted'))) then isc.emailId end as 'Offered',
                                                         case when ( (isc.candidateStatus in('Client Shortlisted'))) then isc.emailId end as 'clientShortlisted', 
                                                         case when ((isc.candidateStatus in('Client Screen Reject','Client Duplicate Reject','Client Interview Reject','Candidate Withdrawal','No Show','Offer Dropped','RNR','Recruiter Reject'))) then isc.emailId end  as 'dropOut',
                                                         case when ((isc.candidateStatus in('Client Screen Reject','Client Duplicate Reject','Client Interview Reject','Candidate Withdrawal'))) then isc.emailId end  as 'clientreject',
                                                         case when ( (isc.candidateStatus in('Recruiter Reject'))) then isc.emailId end  as 'recruiterreject',
                                                         case when ((fr.review_status=2) and (isc.candidateStatus in('Client Screen Reject','Client Duplicate Reject','Client Interview Reject','Candidate Withdrawal','No Show','Offer Dropped','Offer Accepted'))) then isc.emailId end  as 'forshared',
                                                         case when (( fr.review_status=2) and (isc.candidateStatus in('UnAttended','Not Attended') or isc.candidateStatus is null)) then isc.emailId end  as 'unAttended', 
                                                         case when (fr.suitability='Must meet') THEN  isc.emailId   end  as suitability ,    
                                                         case when  (isc.candidateStatus is not null and isc.candidateStatus in('Profile Shared') and fr.id is not null )   
                                                         then TIMESTAMPDIFF(DAY, isc.candidateStatusDate, NOW()) end as profileAge, 
                                                         case when  (isc.candidateStatus is not null and isc.candidateStatus in('Client Shortlisted') and fr.id is not null )   
                                                         then TIMESTAMPDIFF(DAY, isc.candidateStatusDate, NOW()) end as clientShortlistedAge,     
                                                         case when (isc.candidateStatus is not null and isc.candidateStatusDate is not null and TIMESTAMPDIFF(DAY,isc.candidateStatusDate,now())>5 and fr.id is not null and (fr.review_status=-4)) then isc.emailId when (isc.candidateStatus is null and isc.candidateStatusDate is null and TIMESTAMPDIFF(DAY,fr.updatedAt,now())>5 and fr.id is not null and (fr.review_status=-4)) then isc.emailId end as IncompletedeadLead,                  
                                                         pr.postedBy,pr.headcount,pr.targetResumeShared from interviewSchedule isc inner join preInterview pr on pr.id=isc.preInterviewId left join interview i on i.id = isc.interviewId left join feedback_request fr on fr.interviewId=i.id left join candidate_interview_transection cit on cit.interviewId=i.id 
                                                         LEFT JOIN detail_feedback_request dfr ON dfr.interviewId = i.id
                                                         LEFT JOIN payment_transaction pay ON pay.interview_id = i.id
                                                         where 1 and isc.emailId is not null and isc.preInterviewId=" . $row['preInterviewId'] . " " . $condition . " group by isc.emailId,fr.id desc order by isc.emailId,fr.review_status desc 
                                                         ) as t group by t.interviewId,t.emailId) as t2 group by t2.preInterviewId ;";


            //     $query2 = "SELECT
            //               t2.preInterviewId,
            //     COUNT(t2.emailId) AS Scheduled,
            //     COUNT(DISTINCT CASE WHEN t2.paymentstatus = 'Paid' THEN t2.emailId END) AS Paid,
            //     COUNT(DISTINCT CASE WHEN t2.paymentstatus = 'Checkout' THEN t2.emailId END) AS Checkout,
            //     COUNT(DISTINCT CASE WHEN t2.paymentstatus = 'Download' THEN t2.emailId END) AS Download,
            //     COUNT(DISTINCT CASE WHEN t2.paymentstatus = 'Viewed' THEN t2.emailId END) AS Viewed,
            //     COUNT(DISTINCT CASE WHEN t2.paymentstatus = 'Not Viewed' THEN t2.emailId END) AS NotViewed,
            //     COUNT(DISTINCT CASE WHEN t2.clientShortlisted IS NOT NULL THEN t2.emailId END) AS clientShortlisted,
            //     COUNT(DISTINCT CASE WHEN t2.shared IS NOT NULL THEN t2.emailId END) AS shared,
            //     COUNT(DISTINCT CASE WHEN t2.Joined IS NOT NULL THEN t2.emailId END) AS Joined,
            //     COUNT(DISTINCT CASE WHEN t2.Offered IS NOT NULL THEN t2.emailId END) AS Offered,
            //     COUNT(DISTINCT CASE WHEN t2.dropOut IS NOT NULL THEN t2.emailId END) AS dropOut,
            //     COUNT(DISTINCT CASE WHEN t2.recruiterreject IS NOT NULL THEN t2.emailId END) AS recruiterreject,
            //     COUNT(DISTINCT CASE WHEN t2.unAttended IS NOT NULL THEN t2.emailId END) AS unAttended,
            //     COUNT(DISTINCT CASE WHEN t2.forshared IS NOT NULL THEN t2.emailId END) AS forshared,
            //     COUNT(t2.suitability) AS suitability,
            //     COUNT(DISTINCT CASE WHEN t2.interviewStatus IN ('Completed') THEN t2.emailId END) AS Completed
            // FROM
            //     (
            //         SELECT
            //             t.* 
            //         FROM
            //             (
            //                 SELECT
            //                     fr.id AS feedbackRequestId,
            //                     isc.emailId,
            //                     isc.scheduleTime,
            //                     pr.id AS preInterviewId,
            //                     isc.recruiterId,
            //                     (SELECT rl.name FROM recruiterList rl LEFT JOIN users u ON u.id = rl.corporateId WHERE rl.id = isc.recruiterId) AS recruiterName,
            //                     (SELECT CONCAT(rl.name, '(', u.firstName, ')') FROM recruiterList rl LEFT JOIN users u ON u.id = rl.corporateId WHERE rl.id = isc.recruiterId) AS recruiter,
            //                    CASE
            //                             WHEN pay.status = 'PAID' THEN 'Paid'
            //                             WHEN pay.status = 'CHECKOUT' THEN 'Checkout'
            //                             WHEN dfr.viewedStatus = 'download' THEN 'Download'
            //                             WHEN dfr.viewedStatus = 'Viewed' THEN 'Viewed'
            //                             ELSE 'Not Viewed'
            //                         END AS paymentstatus,
            //                     CASE
            //                         WHEN pr.interviewName IS NULL THEN (SELECT name FROM aspiration_company WHERE id = pr.company_id)
            //                         ELSE pr.interviewName
            //                     END AS interviewName,
            //                     DATE_FORMAT(pr.interviewStartDate, '%Y-%c-%d') AS 'postedOn',
            //                     DATE_FORMAT(pr.interviewExpireDate, '%Y-%c-%d') AS 'JobExpiryDate',
            //                     CASE
            //                         WHEN (fr.id IS NOT NULL AND (fr.review_status = -4)) THEN 'Incomplete'
            //                         WHEN (fr.id IS NOT NULL AND cit.completion_status IS NOT NULL AND fr.review_status IN (0, 1, -2)) THEN 'Assessment in Progress'
            //                         WHEN (fr.id IS NOT NULL AND cit.completion_status IS NOT NULL AND fr.review_status = 2) THEN 'Completed'
            //                     END AS interviewStatus,
            //                     CASE
            //                         WHEN (fr.id IS NOT NULL AND cit.completion_status IS NOT NULL AND fr.review_status = 2) THEN fr.id
            //                     END AS 'Completed',
            //                     CASE
            //                         WHEN (fr.id IS NULL AND (DATE_FORMAT(isc.recruiterScheduleDate, '%Y-%c-%d') = CURDATE())) THEN isc.emailId
            //                     END AS todaySchedule,
            //                     CASE
            //                         WHEN (fr.id IS NULL AND isc.scheduleTime >= NOW()) THEN isc.emailId
            //                     END AS futureScheduled,
            //                     CASE
            //                         WHEN ((fr.id IS NOT NULL) AND (isc.candidateStatus IN ('Profile Shared'))) THEN isc.emailId
            //                     END AS 'shared',
            //                     CASE
            //                         WHEN ((fr.id IS NOT NULL) AND (isc.candidateStatus IN ('Joined'))) THEN isc.emailId
            //                     END AS 'Joined',
            //                     CASE
            //                         WHEN ((fr.id IS NOT NULL) AND (isc.candidateStatus IN ('Offered', 'Offer Dropped', 'Offer Accepted'))) THEN isc.emailId
            //                     END AS 'Offered',
            //                     CASE
            //                         WHEN ((fr.id IS NOT NULL) AND (isc.candidateStatus IN ('Client Shortlisted'))) THEN isc.emailId
            //                     END AS 'clientShortlisted',
            //                     CASE
            //                         WHEN ((fr.id IS NOT NULL) AND (isc.candidateStatus IN ('Client Rejected', 'No Show', 'Offer Dropped', 'RNR', 'Recruiter Reject'))) THEN isc.emailId
            //                     END AS 'dropOut',
            //                     CASE
            //                         WHEN ((fr.id IS NOT NULL) AND (isc.candidateStatus IN ('Client Rejected'))) THEN isc.emailId
            //                     END AS 'clientreject',
            //                     CASE
            //                         WHEN ((fr.id IS NOT NULL) AND (isc.candidateStatus IN ('Recruiter Reject'))) THEN isc.emailId
            //                     END AS 'recruiterreject',
            //                     CASE
            //                         WHEN ((fr.id IS NOT NULL AND fr.review_status = 2) AND (isc.candidateStatus IN ('Client Rejected', 'No Show', 'Offer Dropped', 'Offer Accepted'))) THEN isc.emailId
            //                     END AS 'forshared',
            //                     CASE
            //                         WHEN ((fr.id IS NOT NULL AND fr.review_status = 2) AND (isc.candidateStatus IN ('UnAttended', 'Not Attended') OR isc.candidateStatus IS NULL)) THEN isc.emailId
            //                     END AS 'unAttended',
            //                     CASE
            //                         WHEN (fr.suitability = 'Must meet') THEN isc.emailId
            //                     END AS suitability,
            //                     CASE
            //                         WHEN (isc.candidateStatus IS NOT NULL AND isc.candidateStatus IN ('Profile Shared') AND fr.id IS NOT NULL) THEN TIMESTAMPDIFF(DAY, isc.candidateStatusDate, NOW())
            //                     END AS profileAge,
            //                     CASE
            //                         WHEN (isc.candidateStatus IS NOT NULL AND isc.candidateStatus IN ('Client Shortlisted') AND fr.id IS NOT NULL) THEN TIMESTAMPDIFF(DAY, isc.candidateStatusDate, NOW())
            //                     END AS clientShortlistedAge,
            //                     CASE
            //                         WHEN (isc.candidateStatus IS NOT NULL AND isc.candidateStatusDate IS NOT NULL AND TIMESTAMPDIFF(DAY, isc.candidateStatusDate, NOW()) > 5 AND fr.id IS NOT NULL AND (fr.review_status = -4)) THEN isc.emailId
            //                         WHEN (isc.candidateStatus IS NULL AND isc.candidateStatusDate IS NULL AND TIMESTAMPDIFF(DAY, fr.updatedAt, NOW()) > 5 AND fr.id IS NOT NULL AND (fr.review_status = -4)) THEN isc.emailId
            //                     END AS IncompletedeadLead,
            //                     pr.postedBy,
            //                     pr.headcount,
            //                     pr.targetResumeShared
            //                 FROM
            //                     interviewSchedule isc
            //                     INNER JOIN preInterview pr ON pr.id = isc.preInterviewId
            //                     LEFT JOIN users u ON u.emailId = isc.emailId
            //                     LEFT JOIN interview i ON i.preInterviewId = pr.id AND i.createdBy = u.id
            //                     LEFT JOIN feedback_request fr ON fr.interviewId = i.id AND fr.candidateId = u.id
            //                     LEFT JOIN candidate_interview_transection cit ON cit.interviewId = i.id
            //                     LEFT JOIN detail_feedback_request dfr ON dfr.interviewId = i.id
            //                     LEFT JOIN payment_transaction pay ON pay.interview_id = i.id
            //                 WHERE
            //                     1
            //                     AND isc.emailId IS NOT NULL
            //                     AND isc.recruiterId IS NOT NULL
            //                     AND isc.preInterviewId =" . $row['preInterviewId'] . "
            //                     " . $condition . "
            //                 GROUP BY
            //                     isc.emailId,
            //                     fr.id DESC
            //                 ORDER BY
            //                     isc.emailId,
            //                     fr.review_status DESC
            //             ) AS t
            //         GROUP BY
            //             t.emailId
            //     ) AS t2
            // GROUP BY
            //     t2.preInterviewId;";                

            // echo $query2;
            // exit();

            $queryData = mysqli_query($databaseConnection, $query2);
            $queryResult = mysqli_fetch_all($queryData, MYSQLI_ASSOC);
            //Shrikant commented : 27/3/2024
            //$queryp="select JobInvited  from promotion  where preInterviewId=".$row['preInterviewId']." and jobpromotion='G'  and  JobInvited is not null ";
            //Shrikant added : 27/3/2024
            $queryp = "SELECT (
                                    (SELECT COALESCE(SUM(JobInvited), 0) FROM promotion WHERE preInterviewId = " . $row['preInterviewId'] . " AND jobpromotion = 'G' AND JobInvited IS NOT NULL) +
                                    (SELECT COALESCE(COUNT(DISTINCT emailId), 0) AS totalSchedule FROM interviewSchedule WHERE preInterviewId = " . $row['preInterviewId'] . " AND promotionSource IN ('lin', 'soc', 'ist')) +
                                    (SELECT COALESCE(COUNT(id), 0) AS naucount FROM marketing WHERE invited = 'Y' AND promotionType = 'Naukri' AND preInterviewId = " . $row['preInterviewId'] . ")
                                 ) AS JobInvited";
            $querypData = mysqli_query($databaseConnection, $queryp);
            $querypResult = mysqli_fetch_all($querypData, MYSQLI_ASSOC);
            if (!empty($querypResult) && isset($querypResult[0]['JobInvited'])) {
                $jobInvited = $querypResult[0]['JobInvited'];

                $queryResult[0]['JobInvited'] = $jobInvited;
            }

            $practicePreInterviewId = [];
            $totalInterviews = 0; // Initialize total interviews
            $totalInterviewUserCount = 0;

            // Query to get distinct practicePreInterviewId values
            $queryq = "SELECT DISTINCT practicePreInterviewId FROM jobPracticeMapping WHERE jobPreInterviewId = " . $row['preInterviewId'];
            $queryqData = mysqli_query($databaseConnection, $queryq);

            // Fetch and store the practicePreInterviewId values
            while ($resultRow = mysqli_fetch_assoc($queryqData)) {
                $practicePreInterviewId[] = $resultRow['practicePreInterviewId'];
            }

            // Iterate over each practicePreInterviewId to count the interviews
            foreach ($practicePreInterviewId as $pre_id) {
                $queryq = "SELECT COUNT(*) AS countRow FROM interview WHERE preInterviewId = " . $pre_id;
                $queryqData = mysqli_query($databaseConnection, $queryq);
                $queryqResult = mysqli_fetch_assoc($queryqData);

                // Check if result is not empty and add to totalInterviews
                if (!empty($queryqResult) && isset($queryqResult['countRow'])) {
                    $totalInterviews += $queryqResult['countRow'];
                }

                $queryq1 = "SELECT COUNT(DISTINCT fr.candidateId) AS countRow1 
                                    FROM interview i 
                                    INNER JOIN feedback_request fr ON i.id = fr.interviewId 
                                    WHERE i.preInterviewId = " . $pre_id;
                $queryqData1 = mysqli_query($databaseConnection, $queryq1);
                $queryqResult1 = mysqli_fetch_assoc($queryqData1);

                // Check if result is not empty and add to totalInterviews
                if (!empty($queryqResult1) && isset($queryqResult1['countRow1'])) {
                    $totalInterviewUserCount += $queryqResult1['countRow1'];
                }
            }

            $queryResult[0]['Practices'] = $totalInterviews;
            $queryResult[0]['Learners'] = $totalInterviewUserCount;
            $resultArray[] = $queryResult;
        }

        if (mysqli_num_rows($_query1) > 0) {
            $total_data['data'] = $resultArray;
            $total_data['count'] = mysqli_num_rows($queryData);
            $total_data['countPre'] = $values1;
            $total_data['countApm'] = $values3['count'];
            $total_data['status'] = 1;
            $to_encode = $total_data;
        } else {
            $to_encode = array(
                'result' => "error",
                'status' => 0,
                'errorCode' => "in Error while retrieving Student information."
            );
        }


    } else {
        $to_encode = array(
            'result' => "error",
            'status' => 0,
            'errorCode' => "in Error while retrieving Student information."
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['getResumeApm_old'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    if (isset($json)) {
        $preInterviewId = $json['preInterviewId'];
        $resumeLocation = $json['resumeLocation'];
        $resumeName = $json['resumeName'];
        $recruiterId = $json['recruiterId'];

        $resumeLocation = mysqli_real_escape_string($databaseConnection, $resumeLocation);
        $resumeName = mysqli_real_escape_string($databaseConnection, $resumeName);


        $query = "INSERT INTO resume_apm (date,resumeName,resumeLocation,preInterviewId,recruiterlistId)  VALUES (Now(), '$resumeName', '$resumeLocation','$preInterviewId',' $recruiterId')";
        // echo $query;
        $insert_query = mysqli_query($databaseConnection, $query);

        if ($insert_query) {
            $to_encode = array(
                'result' => 'success',
                'status' => 1,
            );
        } else {
            $to_encode = array(
                'result' => 'error',
                'status' => 0,
                'errorCode' => 'Error while inserting data into the database'
            );
        }
    } else {
        $to_encode = array(
            'result' => 'error',
            'status' => 0,
            'errorCode' => 'Error while decoding JSON'
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['getResumeApm'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    if (isset($json)) {
        $preInterviewId = $json['preInterviewId'];
        $resumeLocation = $json['resumeLocation'];
        $resumeName = $json['resumeName'];
        $recruiterId = $json['recruiterId'];

        $resumeLocation = mysqli_real_escape_string($databaseConnection, $resumeLocation);
        $resumeName = mysqli_real_escape_string($databaseConnection, $resumeName);

        // Check if resumeName already exists in resume_apm
        $check_query = "SELECT * FROM resume_apm WHERE preInterviewId = '$preInterviewId' and resumeName = '$resumeName'";
        $check_result = mysqli_query($databaseConnection, $check_query);

        if (mysqli_num_rows($check_result) > 0) {
            // Resume name exists, don't insert
            $to_encode = array(
                'result' => 'exist',
                'status' => 0,
                'errorCode' => 'Resume already exists'
            );
        } else {
            // Insert into resume_apm
            $query1 = "INSERT INTO resume_apm (date, resumeName, resumeLocation, preInterviewId, recruiterlistId)  
                       VALUES (Now(), '$resumeName', '$resumeLocation', '$preInterviewId', '$recruiterId')";
            $insert_query1 = mysqli_query($databaseConnection, $query1);

            // Check if resume_apm insert was successful
            if ($insert_query1) {
                $apmDashId = mysqli_insert_id($databaseConnection);
                // $query2 = "INSERT INTO interviewSchedule (apmStatus, apmDashId, preInterviewId, recruiterId, resume ) VALUES (0, '$apmDashId', '$preInterviewId', '$recruiterId', '$resumeLocation')"; // tempchange
                $query2 = "INSERT INTO interviewSchedule (apmDashId, preInterviewId, recruiterId, resume ) VALUES ('$apmDashId', '$preInterviewId', '$recruiterId', '$resumeLocation')";
                $insert_query2 = mysqli_query($databaseConnection, $query2);

                // Check if both inserts were successful
                if ($insert_query2) {
                    $to_encode = array(
                        'result' => 'success',
                        'status' => 1
                    );
                } else {
                    $to_encode = array(
                        'result' => 'error',
                        'status' => 0,
                        'errorCode' => 'Error inserting data into interviewSchedule'
                    );
                }
            } else {
                $to_encode = array(
                    'result' => 'error',
                    'status' => 0,
                    'errorCode' => 'Error inserting data into resume_apm'
                );
            }
        }
    } else {
        $to_encode = array(
            'result' => 'error',
            'status' => 0,
            'errorCode' => 'Error while decoding JSON'
        );
    }

    echo json_encode($to_encode);
} else if (isset($_GET['getResumeApmData'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    $userId = $json['userId'];
    $userType = $json['userType'];
    $limit = $json['limit'];
    $start = ($json['page'] - 1) * $limit;
    $limit_query = $limit == 0 ? "" : " limit " . $start . "," . $limit;
    $preId = $json['preInterviewId'];
    $selectedCityNames = isset($json['locations']) ? $json['locations'] : '';
    $selectedWorkExperience = isset($json['workExperiences']) ? $json['workExperiences'] : '';

    $preIdsArray = explode(',', $preId);
    // echo "preId : ";
    // print_r($preId);
    $fliterQry = '';
    if ($preIdsArray != '') {
        $preIdsString = implode("','", array_map('intval', $preIdsArray));
        $fliterQry = "WHERE rpm.preInterviewId IN ('" . $preIdsString . "')";
    } else {
        $fliterQry = '';
    }

    //echo $selectedCityNames;
    if ($selectedCityNames != '') {
        $selectedCityNamesArray = explode(',', $selectedCityNames);
        $selectedCityNamesString = "'" . implode("','", $selectedCityNamesArray) . "'";
        $cityFilter = !empty($selectedCityNamesString) ? "isc.currentLocation IN ($selectedCityNamesString)" : "";

        if (!empty($cityFilter)) {
            // Concatenate the city filter to $fliterQry using AND operator if $fliterQry is not empty
            $fliterQry .= !empty($fliterQry) ? " AND $cityFilter" : $cityFilter;
        }
    }

    //  if($selectedWorkExperience != ''){
    //     $selectedWorkExperienceArray = explode(',', $selectedWorkExperience);
    //     $selectedWorkExperienceArrayString = "'" . implode("','", $selectedWorkExperienceArray) . "'";
    //     $workFilter = !empty($selectedWorkExperienceArrayString) ? "isc.workExperience IN ($selectedWorkExperienceArrayString)" : "";

    //     if (!empty($workFilter)) {
    //         // Concatenate the city filter to $fliterQry using AND operator if $fliterQry is not empty
    //         $fliterQry .= !empty($fliterQry) ? " AND $workFilter" : $workFilter;
    //     }
    //  }
    if (!empty($selectedWorkExperience)) {

        $experienceValues = array_map('floatval', (array) $selectedWorkExperience);
        sort($experienceValues);

        $conditions = [];

        foreach ($experienceValues as $experience) {
            if ($experience == 11) {
                $conditions[] = "(isc.workExperience >= 11.0)";
            } else {
                // Calculate min and max for each selected experience value
                $minExperience = $experience;
                $maxExperience = $experience + 0.9;
                $conditions[] = "(isc.workExperience >= $minExperience AND isc.workExperience <= $maxExperience)";
            }

        }

        // Join conditions with OR for multiple selected experiences
        if (!empty($conditions)) {
            $fliterQry .= " AND (" . implode(" OR ", $conditions) . ")";
        }

    }
    // else {
    //     // Handle the case when candidateExperience is empty or invalid
    //     $condition5 .= "";
    // }
    $candidate_search = trim($json['candidate_search']);
    //echo "candidate_search: " .$candidate_search;
    if ($candidate_search != "") {
        $candidateSearchCondition = "";
        if (preg_match('/^[0-9]{10}+$/', $candidate_search)) {
            $candidateSearchCondition = "rpm.mobileNumber='" . $candidate_search . "'";
        } else if (filter_var($candidate_search, FILTER_VALIDATE_EMAIL)) {
            $candidateSearchCondition = "rpm.emailId='" . $candidate_search . "'";
        } else {
            $candidateSearchCondition = "(rpm.candidateName LIKE '%" . $candidate_search . "%' OR rpm.resumeName LIKE '%" . $candidate_search . "%' )";

        }

        if (!empty($fliterQry)) {
            $fliterQry .= " AND " . $candidateSearchCondition;
        } else {
            $fliterQry = " WHERE " . $candidateSearchCondition;
        }
    }
    //$fliterQry = rtrim($fliterQry, " \t\n\r\0\x0B");
    // echo $fliterQry;
    // $sql = "select rl.name as rname,rpm.recruiterlistId,rpm.resumeLocation,rpm.id,rpm.date,ROUND(rpm.apm, 2) as apm,rpm.preInterviewId,rpm.apmFlag,pr.interviewName from resume_apm rpm left join preInterview pr on rpm.preInterviewId = pr.id 
    // left join recruiterList rl on rpm.recruiterlistId = rl.id ".$fliterQry."order by rpm.id desc".$limit_query."";

    //Shrikant added : 5/4/2024
    // $sql = "select rl.name as rname, rpm.recruiterlistId, rpm.resumeLocation, rpm.id, rpm.candidateName, rpm.emailId, rpm.mobileNumber, rpm.noticePeriod, rpm.currentSalary, rpm.expectedSalary, rpm.workExperience, rpm.jobLocation, rpm.date, ROUND(rpm.apm, 2) as apm, rpm.preInterviewId, rpm.apmFlag, pr.interviewName from resume_apm rpm left join preInterview pr on rpm.preInterviewId = pr.id 
    // left join recruiterList rl on rpm.recruiterlistId = rl.id ".$fliterQry."order by rpm.id desc".$limit_query."";

    // $sql = "select rl.name as rname, rpm.recruiterlistId, rpm.resumeLocation, rpm.id, rpm.candidateName, rpm.emailId, rpm.mobileNumber, rpm.noticePeriod, rpm.currentSalary, rpm.expectedSalary, rpm.workExperience, rpm.jobLocation, rpm.date, ROUND(rpm.apm, 2) as apm, rpm.preInterviewId, rpm.apmFlag, pr.interviewName, isc.candidateStatus from resume_apm rpm left join preInterview pr on rpm.preInterviewId = pr.id 
    // left join recruiterList rl on rpm.recruiterlistId = rl.id left join interviewSchedule isc on rpm.emailId=isc.emailId and rpm.preInterviewId=isc.preInterviewId ".$fliterQry."order by rpm.id desc".$limit_query."";

    // $sql = "select rl.name as rname, rpm.recruiterlistId, rpm.resumeLocation, rpm.id, rpm.candidateName, rpm.emailId, rpm.mobileNumber, isc.noticePeriod, isc.currentSalary, isc.expectedSalary, isc.workExperience, isc.currentLocation as jobLocation, rpm.date, ROUND(rpm.apm, 2) as apm, rpm.preInterviewId, rpm.apmFlag, pr.interviewName, isc.candidateStatus from resume_apm rpm left join preInterview pr on rpm.preInterviewId = pr.id 
    // left join recruiterList rl on rpm.recruiterlistId = rl.id left join interviewSchedule isc on rpm.emailId=isc.emailId and rpm.preInterviewId=isc.preInterviewId ".$fliterQry."order by rpm.id desc".$limit_query."";

    //             ROUND(rpm.apm, 2) as apm,
    //rpm.apmFlag,
    $sql = "select 
            COALESCE(isc.candidateName,rpm.candidateName) as candidateName,
            COALESCE(isc.emailId,rpm.emailId) as emailId,
            COALESCE(isc.mobileNumber,rpm.mobileNumber) as mobileNumber,
            COALESCE(isc.resume,rpm.resumeLocation) as resumeLocation,
            COALESCE(isc.apm,rpm.apm) as apm,
            isc.id as iscId,
            isc.apmStatus,
            isc.noticePeriod,
            isc.currentSalary,
            isc.expectedSalary,
            isc.workExperience,
            isc.skillValues,
            isc.employmentStatus,
            isc.currentCompany,
            isc.scheduleTime,
            isc.candidateStatus,
            isc.offer,
            isc.offeredCTC,
            isc.submissionFlag,
            isc.verifyFlag,
            isc.jobMatch,
            isc.detailsStatus,
            isc.emailId,
            isc.comment,
            rpm.leadStatus,
            rpm.candidateId,
            rpm.recruiterlistId,
            rpm.resumeName,
            rpm.id,
            rpm.date,
            rpm.preInterviewId,
            rl.name as rname,
            l.cityName as jobLocation,
            pr.interviewName,
            pr.requiredSkills,
            pr.interviewStartDate as postedDate,
            pp1.fieldValue as companyWorkExperience,
            pr.pendingInterviews
        from resume_apm rpm
        left join preInterview pr on rpm.preInterviewId = pr.id
        left join recruiterList rl on rpm.recruiterlistId = rl.id
        left join interviewSchedule isc on rpm.id = isc.apmDashId and rpm.preInterviewId = isc.preinterviewId
        left join locations l on l.id=isc.currentLocation
        LEFT JOIN profilePreferences pp1 ON pp1.preInterviewId = pr.id and pp1.fieldName = 'workExperience' 
        " . $fliterQry . " group by rpm.id  order by rpm.id desc" . $limit_query . "";

    // echo $sql; 
    $subject_query = mysqli_query($databaseConnection, $sql);
    // $countData="select rpm.id from resume_apm rpm ".$fliterQry." order by rpm.id desc";
    $countData = "select rpm.id from resume_apm rpm  left join interviewSchedule isc on rpm.id = isc.apmDashId and  rpm.preInterviewId = isc.preinterviewId " . $fliterQry . " group by rpm.id  order by rpm.id desc";
    $count_query = mysqli_query($databaseConnection, $countData);

    $values = array();
    $apmValues = array();
    if ($subject_query) {
        if (mysqli_num_rows($subject_query) > 0) {
            // $values['ResumeApmData'] = mysqli_fetch_all($subject_query, MYSQLI_ASSOC);
            while ($row = mysqli_fetch_assoc($subject_query)) {
                $candidateSkills = $row['skillValues'];
                $jobSkills = $row['requiredSkills'];
                $candidateEmailId = $row['emailId'];
                // echo $candidateEmailId;

                // Convert the comma-separated strings into arrays
                if ($candidateSkills != '' && $candidateSkills != NULL) {
                    $candidateSkillsArray = array_map('trim', explode(',', $candidateSkills));
                } else {
                    $candidateSkillsArray = [];
                }

                if ($jobSkills != '' && $jobSkills != NULL) {
                    $jobSkillsArray = array_map('trim', explode(',', $jobSkills));
                } else {
                    $jobSkillsArray = [];
                }

                // Find the matching skills using array_intersect
                $matchingSkills = array_intersect($candidateSkillsArray, $jobSkillsArray);
                // Calculate the number of jobSkills
                $totalJobSkills = count($jobSkillsArray);
                // Calculate the number of matching skills
                $matchingSkillsCount = count($matchingSkills);
                $row['skillMatchCount'] = $matchingSkillsCount;
                // Output the ratio as a fraction
                $row['skillMatchRatio'] = $matchingSkillsCount . "/" . $totalJobSkills;

                if ($totalJobSkills > 0) {
                    $row['skillMatchPer'] = ($matchingSkillsCount / $totalJobSkills) * 100;
                } else {
                    $row['skillMatchPer'] = 0;
                }

                $matchingSkillsIds = implode(',', $matchingSkills);

                $matchSkillsStringQuery = "SELECT GROUP_CONCAT(fs.favourite_subject SEPARATOR ', ') AS skillNames
                               FROM favourite_subject fs
                               WHERE FIND_IN_SET(fs.id, '$matchingSkillsIds') > 0";

                $matchSkillsString = mysqli_query($databaseConnection, $matchSkillsStringQuery);

                if (mysqli_num_rows($matchSkillsString) > 0) {
                    $matchSkillsStringResult = mysqli_fetch_assoc($matchSkillsString);
                    $row['matchSkillNames'] = $matchSkillsStringResult['skillNames'];
                } else {
                    $row['matchSkillNames'] = '';
                }

                if (empty($jobSkills)) {
                    $row['requiredSkillsArray'] = [];
                } else {
                    // Process the IDs
                    $skillsArray = explode(',', $jobSkills);
                    $skillsArray = array_map('intval', $skillsArray);
                    $skillsList = implode(',', $skillsArray);

                    // Query to fetch the skill names and IDs
                    $query = "SELECT id, favourite_subject as name
                            FROM favourite_subject 
                            WHERE id IN ($skillsList)";
                    $result = $databaseConnection->query($query);

                    // Initialize an array to store the skills
                    $skillsArray = [];

                    if ($result && $result->num_rows > 0) {
                        // Fetch all rows as an array
                        while ($fsrow = $result->fetch_assoc()) {
                            $skillsArray[] = $fsrow;
                        }
                    }

                    // Assign the array to requiredSkillsArray
                    $row['requiredSkillsArray'] = $skillsArray;
                }

                $candidateSkillsQuery = "
                SELECT * 
                FROM candidate_skills 
                WHERE emailId = '" . $candidateEmailId . "';
                ";
                // echo $candidateSkillsQuery;
                $candidateSkillsResult = mysqli_query($databaseConnection, $candidateSkillsQuery);
                // Check if the query was successful and if there are rows in the result
                if ($candidateSkillsResult && mysqli_num_rows($candidateSkillsResult) > 0) {
                    $row['candidateSkillsArrayNew'] = mysqli_fetch_all($candidateSkillsResult, MYSQLI_ASSOC);
                } else {
                    // Handle case where no rows are returned
                    $row['candidateSkillsArrayNew'] = [];
                }
                // 
                $apmValues[] = $row;


            }
            $values['ResumeApmData'] = $apmValues;
            $values['count'] = mysqli_num_rows($count_query);
            $to_encode = array(
                'result' => 'success',
                'status' => 1,
                'data' => $values,
                'message' => 'data found',
            );
        } else {
            $to_encode = array(
                'result' => 'success',
                'status' => 0,
                'message' => 'no data found',
            );
        }
    } else {
        $to_encode = array(
            'result' => 'success',
            'status' => 0,
            'message' => 'no data found',
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getUpdateApmData'])) {
    $data = file_get_contents("php://input");
    $json = json_decode($data, true);

    if ($json !== null) {
        // Extract the data from the request
        $aId = isset($json['id']) ? $json['id'] : null;
        $preInterviewId = isset($json['preInterviewId']) ? $json['preInterviewId'] : null;
        $candidateName = isset($json['candidateName']) ? $json['candidateName'] : '';
        $emailId = isset($json['emailId']) ? $json['emailId'] : null;
        $mobileNumber = isset($json['mobileNumber']) ? $json['mobileNumber'] : null;
        $employmentStatus = isset($json['employmentStatus']) ? $json['employmentStatus'] : null;
        $noticePeriod = isset($json['noticePeriod']) ? $json['noticePeriod'] : null;
        $currentSalary = isset($json['currentSalary']) ? $json['currentSalary'] : '';
        $expectedSalary = isset($json['expectedSalary']) ? $json['expectedSalary'] : null;
        $workExperience = isset($json['workExperience']) ? $json['workExperience'] : null;
        $currentCompany = isset($json['currentCompany']) ? $json['currentCompany'] : null;
        $location = isset($json['location']) ? $json['location'] : null;
        $resumeLocation = isset($json['resumeLocation']) ? $json['resumeLocation'] : null;
        $offeredStatus = isset($json['offeredStatus']) ? $json['offeredStatus'] : null;
        $offeredCTCInput = isset($json['offeredCTCInput']) ? $json['offeredCTCInput'] : null;
        // $skillValues = isset($json['skillValues']) ? $json['skillValues'] : null;

        $comment = isset($json['comment']) ? $json['comment'] : null;

        $interviewDatetime = isset($json['interviewDatetime']) && isset($json['pendingInterviews'])
            ? ($json['pendingInterviews'] === 'NR' ? null : $json['interviewDatetime'])
            : null;

        $apm = isset($json['apm']) ? $json['apm'] : null;
        $recruiterId = isset($json['recruiterId']) ? $json['recruiterId'] : null;
        $candidateStatus = isset($json['candidateStatus']) ? $json['candidateStatus'] : null;

        $submissionFlagManually = isset($json['submissionFlagManually']) ? $json['submissionFlagManually'] : null;

        if (!empty($json['skills'])) {
            $skills_json = $json['skills'];
            $skills = $skills_json;
        } else {
            $skills = null;
        }
        // var_dump($skills);
        // exit();

        if ($apm == null || $apm == '' || $apm == -2) {
            $apmStatus = -1;
            $apm = 'NULL';
        } else {
            $apmStatus = 2;
        }

        $resumeLocationEdit = isset($json['resumeLocationEdit']) ? $json['resumeLocationEdit'] : null;
        $resumeUpdated = isset($json['resumeUpdated']) ? $json['resumeUpdated'] : 'N';

        if ($resumeLocationEdit !== null) {
            $resumeLocation = $resumeLocationEdit;
        }




        if (!empty($skills)) {
            foreach ($skills as $skill) {
                $skillId = (int) $skill['skillId'];
                $name = $databaseConnection->real_escape_string($skill['name']);
                $yoe = (int) $skill['years'];
                $projectDetails = isset($skill['projects']) && !empty($skill['projects']) ? $databaseConnection->real_escape_string($skill['projects']) : null;

                // Check if the skill already exists for the candidate
                $checkQuery = "
                    SELECT skillId 
                    FROM candidate_skills 
                    WHERE emailId = '$emailId' AND skillId = '$skillId';
                ";

                $result = $databaseConnection->query($checkQuery);

                if ($result && $result->num_rows > 0) {

                    // Update other skill details (yoe and projectDetails)
                    $updateQuery = "
                        UPDATE candidate_skills 
                        SET yoe = $yoe, projectDetails = " . ($projectDetails !== null ? "'$projectDetails'" : "NULL") . " 
                        WHERE skillId = '$skillId' AND emailId = '$emailId'
                    ";
                    $databaseConnection->query($updateQuery);
                } else {
                    // Skill does not exist, insert it
                    $insertQuery = "
                        INSERT INTO candidate_skills (skillId, name, yoe, projectDetails, emailId) 
                        VALUES ($skillId, '$name', $yoe, " . ($projectDetails !== null ? "'$projectDetails'" : "NULL") . ", '$emailId')
                    ";
                    // echo $insertQuery;
                    $databaseConnection->query($insertQuery);
                }

            }

            $checkQuery = "
                SELECT GROUP_CONCAT(skillId) AS skillValues 
                FROM candidate_skills 
                WHERE emailId = '$emailId';
            ";

            $result = mysqli_query($databaseConnection, $checkQuery);
            $skillValues = null;

            if ($result && mysqli_num_rows($result) > 0) {
                $row = mysqli_fetch_assoc($result);
                $skillValues = $row['skillValues'] ?? null;
            }


        } else {
            $skillValues = null;
        }

        // echo $skillValues;
        // exit();

        // Preliminary check for existing verified interviewSchedule record by emailId
        $checkExistingQuery = "SELECT apmDashId FROM interviewSchedule 
                    WHERE emailId = '$emailId' AND preInterviewId = '$preInterviewId' AND verifyFlag = 'Y' LIMIT 1";
        $existingResult = mysqli_query($databaseConnection, $checkExistingQuery);

        if ($existingResult && mysqli_num_rows($existingResult) > 0) {
            $existingRecord = mysqli_fetch_assoc($existingResult);

            if (!empty($existingRecord['apmDashId'])) {
                $aId = $existingRecord['apmDashId']; // Use the existing apmDashId
            }
        }

        // echo $aId;
        // exit();

        if ($aId !== null) {
            // Step 1: Update resume_apm table
            $query = "UPDATE resume_apm SET 
                candidateName = '$candidateName',
                emailId = '$emailId',
                mobileNumber = '$mobileNumber'
                WHERE id = '$aId' AND preInterviewId = '$preInterviewId'";

            $update_query = mysqli_query($databaseConnection, $query);
            if (!$update_query) {
                echo json_encode([
                    'result' => 'error',
                    'status' => 0,
                    'errorCode' => 'Error while updating resume_apm: ' . mysqli_error($databaseConnection)
                ]);
                exit;
            }

            // Update interviewSchedule table
            $sql = "UPDATE interviewSchedule SET
                verifyFlag = 'Y',
                candidateName = '$candidateName',
                employmentStatus = '$employmentStatus',
                noticePeriod = '$noticePeriod',
                currentSalary = '$currentSalary',
                expectedSalary = '$expectedSalary',
                workExperience = '$workExperience',
                currentCompany = '$currentCompany',
                currentLocation = '$location',
                mobileNumber = '$mobileNumber',
                emailId = '$emailId',
                resume = '$resumeLocation',
                promotionSource = 'ist',
                apm = $apm,
                recruiterId = '$recruiterId',
                skillValues = '$skillValues',
                offer = '$offeredStatus',
                offeredCTC = '$offeredCTCInput',
                comment = " . ($comment === null ? "NULL" : "'$comment'") . ",
                scheduleTime = " . ($interviewDatetime === null ? "NULL" : "'$interviewDatetime'");

            // Conditionally add submissionFlag if $submissionFlagManually is not null
            if ($submissionFlagManually !== null) {
                $sql .= ", submissionFlag = '$submissionFlagManually'";
            }

            // Add the WHERE clause to the query
            $sql .= " WHERE apmDashId = '$aId'";

            $updateSchedule = mysqli_query($databaseConnection, $sql);

            if (!$updateSchedule) {
                echo json_encode([
                    'result' => 'error',
                    'status' => 0,
                    'errorCode' => 'Error while updating interviewSchedule: ' . mysqli_error($databaseConnection)
                ]);
                exit;
            }
        } else {
            echo json_encode([
                'result' => 'error',
                'status' => 0,
                'errorCode' => 'Neither id nor preInterviewId is available'
            ]);
            exit;
        }

        // Step 2: Perform job match logic after initial update
        $query2 = "SELECT emailId, submissionFlag FROM interviewSchedule WHERE apmDashId='$aId'";
        $queryToCheckData2 = mysqli_query($databaseConnection, $query2);

        if (mysqli_num_rows($queryToCheckData2) > 0) {
            while ($row = mysqli_fetch_assoc($queryToCheckData2)) {

                $submissionFlag = $row['submissionFlag'];

                $jmSql = "SELECT jobMatch('$emailId', $preInterviewId) AS profileMatchResult";
                $jmResult = mysqli_query($databaseConnection, $jmSql);
                $jm = 'NA';
                if ($jmResult) {
                    $jmData = mysqli_fetch_assoc($jmResult);
                    if ($jmData) {
                        $jm = $jmData['profileMatchResult'];
                    }
                }

                if ($candidateStatus === null || in_array($candidateStatus, ['Interview Scheduled', 'Profile Mismatch', 'Profile Match'])) {
                    if ($jm === 'YES') {

                        $pendingInterviews = null;

                        // Query to fetch pendingInterviews
                        $pendingInterviewsQuery = "
                            SELECT pendingInterviews 
                            FROM preInterview 
                            WHERE id = '$preInterviewId';
                        ";

                        $pendingInterviewsResult = mysqli_query($databaseConnection, $pendingInterviewsQuery);

                        // Fetch pendingInterviews value if the query succeeds
                        if ($pendingInterviewsResult && mysqli_num_rows($pendingInterviewsResult) > 0) {
                            $row = mysqli_fetch_assoc($pendingInterviewsResult);
                            $pendingInterviews = $row['pendingInterviews'] ?? null;
                        }

                        // Determine candidate status based on pendingInterviews value
                        if ($pendingInterviews === null) {
                            $candidateStatus = null;
                        } else {
                            if ($pendingInterviews === 'NR') {
                                $candidateStatus = 'Profile Match';
                            } else {
                                $candidateStatus = 'Interview Scheduled';
                            }
                        }


                        // tempchange
                        // if ($resumeUpdated === 'Y') {
                        //     if ($submissionFlag === 'WA' || $submissionFlag === 'Y') {
                        //         // $apmStatus = 0;
                        //     } else {
                        //         // $apmStatus = 50;
                        //     }
                        // }
                    } elseif (in_array($jm, ['NO', 'NA'])) {
                        $candidateStatus = 'Profile Mismatch';
                    }
                }

                $sql = "UPDATE interviewSchedule SET  
                    candidateStatus=" . ($candidateStatus === null ? "NULL" : "'$candidateStatus'") . ",
                    jobMatch = '$jm',
                    apmStatus = '$apmStatus'
                    WHERE apmDashId='$aId'";

                $updateSchedule = mysqli_query($databaseConnection, $sql);

                if (!$updateSchedule) {
                    echo json_encode([
                        'result' => 'error',
                        'status' => 0,
                        'errorCode' => 'Error while updating interviewSchedule: ' . mysqli_error($databaseConnection)
                    ]);
                    exit;
                }
            }
        } else {
            echo json_encode([
                'status' => 1,
                'message' => 'Record not found in service dashboard'
            ]);
        }

        echo json_encode(['result' => 'success', 'status' => 1, 'message' => 'Data updated successfully.']);
    } else {
        echo json_encode([
            'result' => 'error',
            'status' => 0,
            'errorCode' => 'Error while decoding JSON'
        ]);
    }
} else if (isset($_GET['sendJobInvite'])) {
    $data = file_get_contents("php://input");
    $json = json_decode($data, true);

    if ($json !== null) {
        $aId = isset($json['id']) ? $json['id'] : null;
        $preInterviewId = isset($json['preInterviewId']) ? $json['preInterviewId'] : null;
        $candidateName = isset($json['candidateName']) ? $json['candidateName'] : '';
        $emailId = isset($json['emailId']) ? $json['emailId'] : null;
        $mobileNumber = isset($json['mobileNumber']) ? $json['mobileNumber'] : null;
        $interviewName = '';
        $companyName = '';
        $jobId = '';
        $interviewLink = '';
        $candidateId = $json['candidateId'];
        if ($aId !== null && $preInterviewId != '') {

            $Query_sql = "SELECT
                pr.id as jobId,
                ac.name as cName,
                pr.interviewName as interviewName,
                pp1.fieldValue as companyjobType,
                loc.cityName as companyJobLocation
            FROM
                preInterview pr
            LEFT JOIN aspiration_company ac ON
                pr.company_id = ac.id
            LEFT JOIN profilePreferences pp1 ON
                pp1.preInterviewId = pr.id
                and pp1.fieldName = 'jobType'
            LEFT JOIN profilePreferences pp3 ON
                pp3.preInterviewId = pr.id
                and pp3.fieldName = 'currentLocation'
            LEFT JOIN locations loc ON
                loc.id = pp3.fieldValue
            WHERE
                pr.id = '" . $preInterviewId . "'";

            // echo $Query_sql;

            $Query = mysqli_query($databaseConnection, $Query_sql);

            $Result = mysqli_fetch_assoc($Query);
            if ($Result['jobId'] != NULL) {
                $jobId = $Result['jobId'];
                if ($candidateId != null) {
                    $interviewLink = 'https://goprac.com/job?p=' . $Result['jobId'];
                } else {
                    $interviewLink = 'https://goprac.com/job?p=' . $Result['jobId'] . '&s=ist';
                }
            }
            if ($Result['interviewName'] != NULL) {
                $interviewName = $Result['interviewName'];
                // removes extra spaces otherwiste  whatsapp gives error
                $interviewName = str_replace(array("\n", "\r"), ' ', $interviewName);
                $interviewName = preg_replace('/\s+/', ' ', $interviewName);

                $companyName = $Result['cName'];
            }





            $user_sql = "SELECT
                            isc.workExperience AS user_workEx,
                            isc.currentSalary AS user_currentSalary,
                            isc.noticePeriod AS user_noticePeriod,
                            (
                            SELECT GROUP_CONCAT(favourite_subject) 
                            FROM favourite_subject fs 
                            WHERE FIND_IN_SET(fs.id, isc.skillValues)
                            ) AS skillsName
                        FROM
                            interviewSchedule isc
                        WHERE
                            isc.mobileNumber = '$mobileNumber' AND isc.preInterviewId = '" . $preInterviewId . "'";

            // echo $user_sql;

            $user_query = mysqli_query($databaseConnection, $user_sql);
            $user_result = mysqli_fetch_assoc($user_query);

            $data = array();

            $data["job_id"] = $jobId;
            $data["job_title"] = $interviewName;
            $data["job_companyName"] = $companyName;
            $data["job_location"] = $Result['companyJobLocation'];
            $data["job_type"] = $Result['companyjobType'];
            $data["interviewlink"] = $interviewLink;

            $data["user_name"] = $candidateName;
            $data["user_workEx"] = $user_result['user_workEx'];
            $data["user_skills"] = $user_result['skillsName'];
            $data["user_currentSalary"] = $user_result['user_currentSalary'];
            $data["user_noticePeriod"] = $user_result['user_noticePeriod'];

            // $data["user_name"] = 'Sourabh Shukla';
            // $data["user_workEx"] = '2 years';
            // $data["user_skills"] = 'javascript';
            // $data["user_currentSalary"] = '300000';
            // $data["user_noticePeriod"] = '2 months'; 

            // var_dump($data);
            // exit();

            // Check if all user data fields have values
            if (
                !empty($data["user_name"]) &&
                !empty($data["user_workEx"]) &&
                !empty($data["user_skills"]) &&
                !empty($data["user_currentSalary"]) &&
                !empty($data["user_noticePeriod"])
            ) {
                // Call the WhatsApp message function only if all fields are set
                // whatsAppMsg($databaseConnection,9906308210,$data,"manualConfirmation");
                whatsAppMsg($databaseConnection, $mobileNumber, $data, "manualConfirmation");
                $query = "UPDATE resume_apm SET 
                invitedDate = NOW(),
                invited = 'Y'
                WHERE id = '$aId' AND preInterviewId = '$preInterviewId'";

                $update_query = mysqli_query($databaseConnection, $query);

                if ($update_query) {
                    $updateStatus = array(
                        'result' => 'successfully send invite',
                        'status' => 1,
                    );
                } else {
                    $updateStatus = array(
                        'result' => 'error',
                        'status' => 0,
                        'errorCode' => 'Error while updating in db '
                    );
                }
            } else {
                $updateStatus = array(
                    'result' => 'error',
                    'code' => 'no_user_data_fields',
                    'status' => 0,
                    'errorCode' => 'Error while getting user data'
                );
            }

        }

    } else {
        $updateStatus = array(
            'result' => 'error',
            'status' => 0,
            'errorCode' => 'Error while decoding JSON'
        );
    }
    $to_encode = $updateStatus;
    echo json_encode($to_encode);
} else if (isset($_GET['sendJobInviteJD'])) {
    $data = file_get_contents("php://input");
    $json = json_decode($data, true);

    if ($json !== null) {
        $aId = isset($json['id']) ? $json['id'] : null;
        $preInterviewId = isset($json['preInterviewId']) ? $json['preInterviewId'] : null;
        $candidateName = isset($json['candidateName']) ? $json['candidateName'] : '';
        $emailId = isset($json['emailId']) ? $json['emailId'] : null;
        $mobileNumber = isset($json['mobileNumber']) ? $json['mobileNumber'] : null;
        $interviewName = '';
        $companyName = '';
        $jobId = '';
        $interviewLink = '';
        $candidateId = $json['candidateId'];
        if ($aId !== null && $preInterviewId != '') {

            $Query_sql = "SELECT
                pr.id as jobId,
                pr.JDsection as jd,
                ac.name as cName,
                pr.interviewName as interviewName,
                pp1.fieldValue as companyjobType,
                pp2.fieldValue as workEx,
                loc.cityName as companyJobLocation,
                rr.name as roleName
            FROM
                preInterview pr
            LEFT JOIN aspiration_company ac ON
                pr.company_id = ac.id
            LEFT JOIN profilePreferences pp1 ON
                pp1.preInterviewId = pr.id
                and pp1.fieldName = 'jobType'
            LEFT JOIN profilePreferences pp2 ON
                pp2.preInterviewId = pr.id
                and pp2.fieldName = 'workExperience'
            LEFT JOIN profilePreferences pp3 ON
                pp3.preInterviewId = pr.id
                and pp3.fieldName = 'currentLocation'
            LEFT JOIN locations loc ON
                loc.id = pp3.fieldValue
            LEFT JOIN relavant_role rr On rr.id=pr.roleId
            WHERE
                pr.id = '" . $preInterviewId . "'";

            // echo $Query_sql;

            $Query = mysqli_query($databaseConnection, $Query_sql);

            $Result = mysqli_fetch_assoc($Query);
            if ($Result['jobId'] != NULL) {
                $jobId = $Result['jobId'];
                if ($candidateId != null) {
                    $interviewLink = 'https://goprac.com/job?p=' . $Result['jobId'];
                } else {
                    $interviewLink = 'https://goprac.com/job?p=' . $Result['jobId'] . '&s=ist';
                }
            }
            if ($Result['interviewName'] != NULL) {
                $interviewName = $Result['interviewName'];
                // removes extra spaces otherwiste  whatsapp gives error
                $interviewName = str_replace(array("\n", "\r"), ' ', $interviewName);
                $interviewName = preg_replace('/\s+/', ' ', $interviewName);

                $companyName = $Result['cName'];
            }

            $data = array();

            $data["job_id"] = $jobId;
            $data["job_title"] = $interviewName;
            $data["job_companyName"] = $companyName;
            $data["job_location"] = $Result['companyJobLocation'];
            $data["job_type"] = $Result['companyjobType'];
            $data["job_workEx"] = $Result['workEx'];
            $data["roleName"] = $Result['roleName'];
            $data["interviewlink"] = $interviewLink;
            $data["user_name"] = $candidateName;


            // Check if all job data fields have values
            if (
                !empty($emailId) &&
                !empty($data["job_title"]) &&
                !empty($data["user_name"]) &&
                !empty($data["job_companyName"]) &&
                !empty($data["job_location"]) &&
                !empty($data["job_workEx"]) &&
                !empty($data["job_type"]) &&
                !empty($data["interviewlink"])
            ) {
                $dts = "Job Opportunity:" . $data["job_title"];
                $message = "
                Dear {$data['user_name']},
                <br/>
                <br/>
                Your skills and experience are a strong match for the below opportunity:
                <br/>
                <br/>
                Company: {$data['job_companyName']}
                <br/>
                Role: {$data['roleName']}
                <br/>
                Location: {$data['job_location']}
                <br/>
                Experience Required: {$data['job_workEx']} years
                <br/>
                Job Type: {$data['job_type']}
                <br/>
                <br/>
                Please complete your application to move forward with the process.
                <br/>
                Click to know more: <a href=\"{$data['interviewlink']}\">{$data['interviewlink']}</a>
                <br/>
                <br/>
                For any technical glitches, reach us at +91 6360060622.
                <br/>
                Good luck!
                <br/>
                Thanks & Regards,
                <br/>
                Nitin Rakesh Prasad
                <br/>
                Founder - GoPrac, Bangalore
                <br/>
                https://www.linkedin.com/in/nrp123/
            ";


                //
                sendEmailToUser($emailId, null, $dts, $message);

                $query = "UPDATE resume_apm SET 
                invitedDate = NOW(),
                invited = 'Y'
                WHERE id = '$aId' AND preInterviewId = '$preInterviewId'";

                $update_query = mysqli_query($databaseConnection, $query);

                if ($update_query) {
                    $updateStatus = array(
                        'result' => 'successfully send JD Email',
                        'status' => 1,
                    );
                } else {
                    $updateStatus = array(
                        'result' => 'error',
                        'status' => 0,
                        'errorCode' => 'Error while updating in db '
                    );
                }
            } else {
                $updateStatus = array(
                    'result' => 'error',
                    'code' => 'no_user_data_fields',
                    'status' => 0,
                    'errorCode' => 'Error while getting user data'
                );
            }

        }

    } else {
        $updateStatus = array(
            'result' => 'error',
            'status' => 0,
            'errorCode' => 'Error while decoding JSON'
        );
    }
    $to_encode = $updateStatus;
    echo json_encode($to_encode);
} else if (isset($_GET['sendPracticeAssign'])) {
    $data = file_get_contents("php://input");
    $json = json_decode($data, true);

    if ($json !== null) {
        $preInterviewId = isset($json['preInterviewId']) ? $json['preInterviewId'] : null;
        $emailId = isset($json['emailId']) ? $json['emailId'] : null;
        $interviewName = '';
        $interviewLink = '';
        $firstName = $json['candidateName'];
        $mobileNumber = $json['mobileNumber'];
        $scheduledate = '';
        $scheduletime = '';
        $candidateId = $json['candidateId'];
        // $practiceFrequency = $json['practiceFrequency'];

        // $frequencyArray = explode(',', $practiceFrequency);

        // Get the first value
        // $firstFrequency = trim($frequencyArray[0]);
        // list($day, $time, $period, $freq) = explode(' ', $firstFrequency);

        // $scheduletime = $time . ' ' . $period;

        // $now = new DateTime();
        // $currentDayOfWeek = $now->format('l');

        // $daysToAdd = (7 + array_search(ucfirst(strtolower($day)), ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']) - $now->format('w')) % 7;

        // if ($currentDayOfWeek === ucfirst(strtolower($day))) {
        //     $daysToAdd = 0;
        // }

        // $now->modify("+{$daysToAdd} days");
        // $scheduledate = $now->format('d F Y');

        if ($preInterviewId != '') {
            $Query = mysqli_query($databaseConnection, "SELECT id, interviewName FROM preInterview WHERE id = '" . $preInterviewId . "'");
            $Result = mysqli_fetch_assoc($Query);

            if ($Result['id'] != NULL) {
                $interviewLink = 'https://goprac.com/job?p=' . $Result['id'];
                if ($candidateId == null) {
                    $interviewLink .= '&s=ist';
                }
            }

            if ($Result['interviewName'] != NULL) {
                $interviewName = $Result['interviewName'];
                $interviewName = str_replace(array("\n", "\r"), ' ', $interviewName);
                $interviewName = preg_replace('/\s+/', ' ', $interviewName);
            }
        }

        // if ($candidateId != '') {
        //     $Query1 = mysqli_query($databaseConnection, "SELECT id, firstName, RIGHT(mobileNumber, 10) AS mobileNumber FROM users WHERE id = '" . $candidateId . "'");
        //     $Result1 = mysqli_fetch_assoc($Query1);

        //     if ($Result1['id'] != NULL) {
        //         $firstName = $Result1['firstName'];
        //         $mobileNumber = $Result1['mobileNumber'];
        //     }
        // }

        $data = array();
        $data["subject"] = $interviewName;
        $data["name"] = $firstName;
        // $data["scheduletime"] = $scheduletime;
        $data["scheduletime"] = null;
        // $data["scheduledate"] = $scheduledate;
        $data["scheduledate"] = null;
        $data["interviewlink"] = $interviewLink;

        if ($mobileNumber != '') {
            // whatsAppMsg($databaseConnection, '9767479189', $data, "practiceAssign");
            whatsAppMsg($databaseConnection, $mobileNumber, $data, "practiceAssign");
        }

        $updateStatus = array(
            'result' => 'Successfully sent practice assign',
            'status' => 1,
        );
    } else {
        $updateStatus = array(
            'result' => 'error',
            'status' => 0,
            'errorCode' => 'Error while decoding JSON'
        );
    }

    $to_encode = $updateStatus;
    echo json_encode($to_encode);
} else if (isset($_GET['getdetailsfromPromotion'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    if (isset($json)) {
        $preInterviewId = $json['preInterviewId'];
        $promotionType = $json['promotionType'];
        $jsonData = $json['jsonData'];
        $insertionCount = 0;
        $duplicateCount = 0;
        function convertToNumeric($string)
        {
            $string = strtolower($string);
            $string = str_replace(' ', '', $string);

            // Match patterns like "2 lakhs" or "2 lakh"
            if (preg_match('/([0-9.]+)\s*lakhs?/', $string, $matches)) {
                $numericValue = floatval($matches[1]) * 100000;
                return $numericValue;
            } else {

                $numericValue = preg_replace('/[^0-9.]/', '', $string);
                $numericValue = floatval($numericValue);
                return $numericValue;
            }
        }
        function convertWorkExperienceToNumeric($workExperience)
        {

            $workExperience = preg_replace('/[^a-zA-Z0-9.\s]/', '', $workExperience);

            // Extract numerical components (years and months)
            preg_match_all('/(\d+\.?\d*)/', $workExperience, $matches);
            $years = isset($matches[0][0]) ? floatval($matches[0][0]) : 0;
            $months = isset($matches[0][1]) ? floatval($matches[0][1]) : 0;

            $numericValue = $years + ($months / 12);
            $roundedNumericValue = number_format((float) $numericValue, 2, '.', '');

            return $roundedNumericValue;

        }


        if ($jsonData !== null) {
            foreach ($jsonData as $entry) {
                $userName = isset($entry['Name']) ? trim($entry['Name']) : null;
                $emailId = isset($entry['Email ID']) ? $entry['Email ID'] : null;
                $phoneNumber = isset($entry['Phone Number']) ? $entry['Phone Number'] : null;
                $phoneNumber = strtok($phoneNumber, ',');
                $phoneNumber = preg_replace("/[^0-9]/", "", $phoneNumber);
                if (strlen($phoneNumber) > 10) {
                    $phoneNumber = ltrim($phoneNumber, '0');
                }
                if (strlen($phoneNumber) !== 10) {
                    $phoneNumber = null;
                }
                $uploadAt = date('Y-m-d');
                $skills = isset($entry['Key Skills']) ? $entry['Key Skills'] : null;
                $skillIdsString = '';
                if ($skills !== null && !empty($skills)) {
                    // Split the skills string and trim any whitespace
                    $skillList = explode(',', $skills);
                    $skillList = array_map('trim', $skillList);

                    // Prepare an array to store skill IDs
                    $skillIds = array();

                    // Iterate through the skill list
                    foreach ($skillList as $skill) {
                        // Escape the skill to prevent SQL injection
                        $skill = mysqli_real_escape_string($databaseConnection, $skill);

                        // Query to fetch skill ID
                        $query = "SELECT id FROM favourite_subject WHERE favourite_subject = '$skill'";

                        // Execute the query
                        $result = mysqli_query($databaseConnection, $query);

                        if ($result && mysqli_num_rows($result) > 0) {
                            // Fetch the result and store the skill ID
                            if ($row = mysqli_fetch_assoc($result)) {
                                $skillIds[] = $row['id'];
                            }
                        }
                    }

                    // Convert the skill IDs array to a comma-separated string
                    if (!empty($skillIds)) {
                        $skillIdsString = implode(',', $skillIds);
                    }
                }

                //added shrikant:24/6/2024

                $locations = isset($entry['Current Location']) ? $entry['Current Location'] : null;
                $locationList = explode(',', $locations);
                $locationList = array_map('trim', $locationList);
                $locationIds = array();

                foreach ($locationList as $loc) {

                    $query1 = "SELECT id FROM locations WHERE cityName = '$loc'";
                    // echo  $query ;
                    $result1 = mysqli_query($databaseConnection, $query1);
                    if (mysqli_num_rows($result1) > 0) {
                        if ($row1 = mysqli_fetch_assoc($result1)) {
                            $locationIds[] = $row1['id'];
                        }
                    } else {
                        continue;
                    }
                }
                //$locationIdsString = implode(',', $locationIds);
                $locationIdsString = !empty($locationIds) ? implode(',', $locationIds) : '';


                // echo "locations : ".$locationIdsString;
                $currentSalary = isset($entry['Annual Salary']) ? convertToNumeric($entry['Annual Salary']) : null;
                $workExperience = isset($entry['Total Experience']) ? convertWorkExperienceToNumeric($entry['Total Experience']) : null;

                $sourceSalary = isset($entry['Annual Salary']) ? $entry['Annual Salary'] : null;
                $sourceExperience = isset($entry['Total Experience']) ? $entry['Total Experience'] : null;

                $checkQuery = "SELECT COUNT(*) AS count FROM marketing WHERE uploadAt = '$uploadAt' AND preInterviewId = '$preInterviewId' AND emailId = '$emailId' AND phoneNumber='$phoneNumber'";
                $checkResult = mysqli_query($databaseConnection, $checkQuery);
                $rowCount = mysqli_fetch_assoc($checkResult)['count'];
                //echo $checkQuery; 
                if ($rowCount == 0) {

                    //$query = "INSERT INTO marketing (userName, emailId, phoneNumber, uploadAt, preInterviewId,workExperience,currentSalary,skills,promotionType,sourceSkills,sourceSalary,sourceExperience,currentLocation,sourceLocation)  VALUES ('$userName', '$emailId', '$phoneNumber', '$uploadAt', '$preInterviewId','$workExperience','$currentSalary','$skillIdsString','$promotionType','$skills','$sourceSalary','$sourceExperience','$locationIdsString','$locations')";
                    // $query = "INSERT INTO marketing (userName, emailId, phoneNumber, uploadAt, preInterviewId,workExperience,currentSalary,promotionType,sourceSalary,sourceExperience,currentLocation,sourceLocation)  VALUES ('$userName', '$emailId', '$phoneNumber', '$uploadAt', '$preInterviewId','$workExperience','$currentSalary','$promotionType','$sourceSalary','$sourceExperience','$locationIdsString','$locations')";
                    $query = "INSERT INTO marketing (userName, emailId, phoneNumber, uploadAt, preInterviewId,workExperience,currentSalary,skills,promotionType,sourceSkills,sourceSalary,sourceExperience,currentLocation,sourceLocation)  VALUES ('$userName', '$emailId', '$phoneNumber', '$uploadAt', '$preInterviewId','$workExperience','$currentSalary','$skillIdsString','$promotionType','$skills','$sourceSalary','$sourceExperience','$locationIdsString','$locations')";

                    //echo $query;
                    $insert_query = mysqli_query($databaseConnection, $query);

                    if ($insert_query) {
                        $insertionCount++;

                    } else {
                        $to_encode = array(
                            'result' => 'error',
                            'status' => 0,
                            'errorCode' => 'Error while inserting data into the database'
                        );
                    }
                } else {

                    //$query = "UPDATE marketing SET userName='$userName', workExperience='$workExperience', currentSalary='$currentSalary', skills='$skillIdsString', currentLocation='$locationIdsString', sourceLocation='$locations', sourceSkills='$skills',sourceSalary='$sourceSalary',sourceExperience='$sourceExperience' WHERE uploadAt = '$uploadAt' AND preInterviewId = '$preInterviewId' AND emailId = '$emailId' AND phoneNumber='$phoneNumber'";
                    //$query = "UPDATE marketing SET userName='$userName', workExperience='$workExperience', currentSalary='$currentSalary', currentLocation='$locationIdsString', sourceLocation='$locations',sourceSalary='$sourceSalary',sourceExperience='$sourceExperience' WHERE uploadAt = '$uploadAt' AND preInterviewId = '$preInterviewId' AND emailId = '$emailId' AND phoneNumber='$phoneNumber'";
                    $query = "UPDATE marketing SET userName='$userName', workExperience='$workExperience', currentSalary='$currentSalary', skills='$skillIdsString', currentLocation='$locationIdsString', sourceLocation='$locations', sourceSkills='$skills',sourceSalary='$sourceSalary',sourceExperience='$sourceExperience' WHERE uploadAt = '$uploadAt' AND preInterviewId = '$preInterviewId' AND emailId = '$emailId' AND phoneNumber='$phoneNumber'";
                    $update_query = mysqli_query($databaseConnection, $query);

                    if ($update_query) {
                        $duplicateCount++;
                    } else {
                        $to_encode = array(
                            'result' => 'error',
                            'status' => 0,
                            'errorCode' => 'Error while updating data in the database'
                        );
                    }
                }
            }
            $to_encode = array(
                'result' => 'success',
                'status' => 1,
                'insertionCount' => $insertionCount,
                'duplicateCount' => $duplicateCount

            );
        } else {
            $to_encode = array(
                'result' => 'error',
                'status' => 0,
                'errorCode' => 'Error while decoding JSON'
            );
        }

        echo json_encode($to_encode);
    }
} elseif (isset($_GET['getInvitedCount'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    $userId = $json['userId'];
    $userType = $json['userType'];
    $preId = $json['preInterviewId'];


    $sql = "SELECT uploadAt, jobInvitedDate, preInterviewId, SUM(CASE WHEN invited = 'Y' THEN 1 ELSE 0 END) AS invited_count,COUNT(*) AS count FROM  marketing where preInterviewId = " . $preId . " GROUP BY uploadAt, preInterviewId order by uploadAt desc;";

    $subject_query = mysqli_query($databaseConnection, $sql);
    $values = array();
    if ($subject_query) {
        if (mysqli_num_rows($subject_query) > 0) {
            $values['invitationData'] = mysqli_fetch_all($subject_query, MYSQLI_ASSOC);
        } else {
            $to_encode = array(
                'result' => 'success',
                'status' => 0,
                'message' => 'no data found',
            );
        }
    }
    echo json_encode($values);
} elseif (isset($_GET['getPracticeAssignCount'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    $userId = $json['userId'];
    $userType = $json['userType'];
    $emailId = $json['emailId'];

    if (!empty($emailId)) {
        $sql = "select pr.interviewName as practiceName, cim.practiceFrequency from candidateInterviewMapping cim inner join preInterview pr on pr.id=cim.preInterviewId where emailId = '" . $emailId . "' order by cim.id desc";

        $subject_query = mysqli_query($databaseConnection, $sql);
        $values = array();
        if ($subject_query) {
            if (mysqli_num_rows($subject_query) > 0) {
                $values['PracticeAssignData'] = mysqli_fetch_all($subject_query, MYSQLI_ASSOC);
            } else {
                $to_encode = array(
                    'result' => 'success',
                    'status' => 0,
                    'message' => 'no data found',
                );
            }
        }
    } else {
        $values['PracticeAssignData'] = [];
        $to_encode = array(
            'result' => 'success',
            'status' => 1,
            'message' => 'candidateId is empty',
        );
    }


    echo json_encode($values);
} elseif (isset($_GET['getISTInviteCount'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    $userId = $json['userId'];
    $userType = $json['userType'];
    $preId = $json['preId'];

    if (!empty($preId)) {
        $sql = "SELECT count(rpm.id) as inviteCount, r.name as recruiterName,rpm.preInterviewId as preIntId, rpm.recruiterlistId as recId
        FROM resume_apm rpm
        LEFT JOIN recruiterList r ON r.id = rpm.recruiterlistId
        WHERE rpm.resumeLocation IS NOT NULL AND rpm.preInterviewId = '" . $preId . "'
        GROUP BY rpm.recruiterlistId";

        $subject_query = mysqli_query($databaseConnection, $sql);
        $values = array();
        if ($subject_query) {
            if (mysqli_num_rows($subject_query) > 0) {
                $subjectResult = mysqli_fetch_all($subject_query, MYSQLI_ASSOC);
                foreach ($subjectResult as &$row) {
                    if (empty($row['recruiterName'])) {
                        $row['recruiterName'] = 'IST Open';
                    }
                    $sql1 = "select count(isc.id) as applyCount from interviewSchedule isc where isc.submissionFlag = 'Y' and isc.recruiterId = '" . $row['recId'] . "' and isc.preInterviewId = '" . $row['preIntId'] . "'";
                    $subject_query1 = mysqli_query($databaseConnection, $sql1);
                    if (mysqli_num_rows($subject_query1) > 0) {
                        $subjectResult1 = mysqli_fetch_all($subject_query1, MYSQLI_ASSOC);
                        $row['applyCount'] = $subjectResult1[0]['applyCount'];
                    } else {
                        $row['applyCount'] = 0;
                    }
                }
                $values['ISTInviteData'] = $subjectResult;
            } else {
                $to_encode = array(
                    'result' => 'success',
                    'status' => 0,
                    'message' => 'no data found',
                );
            }
        }
    } else {
        $values['ISTInviteData'] = [];
        $to_encode = array(
            'result' => 'success',
            'status' => 1,
            'message' => 'preInterviewId is empty',
        );
    }

    echo json_encode($values);
} elseif (isset($_GET['getScheduleCount'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    $userId = $json['userId'];
    $userType = $json['userType'];
    $preId = $json['preInterviewId'];


    //$sql="SELECT id, candidateName, mobileNumber, scheduleTime, candidateStatus FROM interviewSchedule WHERE preInterviewId = $preId ";

    //$sql="SELECT id, candidateName, mobileNumber, scheduleTime, candidateStatus FROM interviewSchedule WHERE preInterviewId = $preId and (candidateStatus IN ('Client Shortlist', 'Resume Shared', 'Interview Scheduled') OR candidateStatus IS NULL)";
    $sql = "SELECT id, candidateName, mobileNumber, scheduleTime, candidateStatus, 
      CASE 
          WHEN candidateStatus = 'Client Shortlist' THEN 'Client Shortlist'
          WHEN candidateStatus = 'Profile Shared' THEN 'Profile Shared'
          WHEN candidateStatus = 'applied' THEN 'applied'
          WHEN candidateStatus = 'Interview Scheduled' THEN 'Interview Scheduled' 
          WHEN ((scheduleTime != firstScheduleDate) AND(DATEDIFF(scheduleTime, NOW())) >= 1) THEN 'Re-Scheduled' 
          WHEN candidateStatus IS NULL THEN 'Interview Scheduled'
      END AS candidateJobStatus
      FROM interviewSchedule 
      WHERE preInterviewId = $preId AND (candidateStatus IN ('Client Shortlist', 'Profile Shared', 'Interview Scheduled', 'applied') OR (candidateStatus IS NULL AND scheduleTime IS NOT NULL)) order by scheduleTime desc";
    $subject_query = mysqli_query($databaseConnection, $sql);
    $values = array();
    if ($subject_query) {
        if (mysqli_num_rows($subject_query) > 0) {
            $values['invitationData'] = mysqli_fetch_all($subject_query, MYSQLI_ASSOC);
        } else {
            $to_encode = array(
                'result' => 'success',
                'status' => 0,
                'message' => 'no data found',
            );
        }
    }
    echo json_encode($values);
} elseif (isset($_GET['getExistingValueForMalpractice'])) {

    $data = file_get_contents("php://input");
    $json = json_decode($data, true);

    if (isset($json)) {

        $questionId = $json['questionId'];
        $interviewSessionId = $json['interviewSessionId'];

        $feedbackRequestQuery = mysqli_query($databaseConnection, "SELECT id, review_status FROM feedback_request WHERE interviewSessionId = '" . $interviewSessionId . "'");
        $feedback_id = mysqli_fetch_assoc($feedbackRequestQuery);
        $feedbackRequestId = $feedback_id['id'];

        $sql = "SELECT observationValueId FROM expert_review_observation_details WHERE feedback_request_id = '" . $feedbackRequestId . "' AND questionId = '" . $questionId . "' AND observationValueId IN (308, 443, 442, 447) and expertReviewId is not null ";


        $result = mysqli_query($databaseConnection, $sql);

        if ($result) {
            if (mysqli_num_rows($result) >= 1) {
                $row = mysqli_fetch_assoc($result);

                $to_encode = array(
                    'status' => 1,
                    'observationId' => $row['observationValueId']
                );
            } else {
                $to_encode = array(
                    'status' => 0,
                    'observationId' => null // or specify a default value
                );
            }
        } else {
            $to_encode = array(
                'status' => -1,
                'observationId' => "error",
                'errorCode' => "Error executing SQL query."
            );
        }

    } else {
        $to_encode = array(
            'status' => -1,
            'observationId' => "error",
            'errorCode' => "Error while decoding JSON data."
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['calculateApm'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json) && isset($json['iscIds'])) {

        $iscIds = implode(',', $json['iscIds']);

        $newCompany = mysqli_query($databaseConnection, "update interviewSchedule set apmStatus=0 where id in(" . $iscIds . ")");

        if ($newCompany) {
            $to_encode = array(
                'result' => 'success',
                'status' => 1
            );
        } else {
            $to_encode = array(
                'result' => 'error while inserting',
                'status' => -1
            );
        }

    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "error in the given data",
            'status' => -1
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getupdateData'])) {
    $data = file_get_contents("php://input");
    $json = json_decode($data, true);

    if ($json !== null) {
        $candidateId = isset($json['candidateId']) ? $json['candidateId'] : null;
        $scheduleId = isset($json['scheduleId']) ? $json['scheduleId'] : null;
        $preId = isset($json['preId']) ? $json['preId'] : null;
        $noticePeriod = isset($json['noticePeriod']) ? $json['noticePeriod'] : '';
        $expectedSalary = isset($json['expectedSalary']) ? $json['expectedSalary'] : null;
        $currentSalary = isset($json['currentSalary']) ? $json['currentSalary'] : null;
        $location = isset($json['location']) && $json['location'] !== 'default' ? $json['location'] : '';
        $workExperience = isset($json['workExperience']) ? $json['workExperience'] : '';
        $skills = isset($json['skills']) ? $json['skills'] : '';
        $employmentStatus = isset($json['employmentStatus']) ? $json['employmentStatus'] : null;
        //$joiningPeriod = isset($json['joiningPeriod']) ? $json['joiningPeriod'] : '';
        $offeredStatus = isset($json['offeredStatus']) ? $json['offeredStatus'] : null;
        $offeredCTCInput = isset($json['offeredCTCInput']) ? $json['offeredCTCInput'] : null;
        $candiStatus = isset($json['candiStatus']) ? $json['candiStatus'] : null;
        $resumeUploadFlag = isset($json['resumeUploadFlag']) ? $json['resumeUploadFlag'] : null;
        $candidateEmailId = isset($json['candidateEmailId']) ? $json['candidateEmailId'] : null;
        if (empty($resumeUploadFlag)) {
            $resumeUploadFlag = null;
        }

        if ($candidateId !== null) {
            $query = "UPDATE professionaldetails SET 
                expectedSalary = '$expectedSalary',
                salary = '$currentSalary',
                currentLocation = '$location',
                noticePeriod = '$noticePeriod',workExperience='$workExperience',skills='$skills',employmentStatus='$employmentStatus',
                offer='$offeredStatus',offeredCTC='$offeredCTCInput' 
                WHERE candidateId = '$candidateId'";

            $insert_query = mysqli_query($databaseConnection, $query);

            if ($scheduleId !== null) {
                $query5 = "UPDATE interviewSchedule SET 
                    expectedSalary = '$expectedSalary',
                    currentSalary = '$currentSalary',
                    currentLocation = '$location',
                    noticePeriod = '$noticePeriod',workExperience='$workExperience',skillValues='$skills',employmentStatus='$employmentStatus',
                    offer='$offeredStatus',offeredCTC='$offeredCTCInput',verifyFlag = 'Y'
                    WHERE id = '$scheduleId'";

                $insert_query5 = mysqli_query($databaseConnection, $query5);
            }

            if ($candidateEmailId !== null && $preId !== null) {
                if ($candiStatus == 'Profile Match' || $candiStatus == 'Profile Mismatch' || $candiStatus == 'Interview Scheduled') {
                    $sql = "SELECT jobMatch('$candidateEmailId',$preId) as jobMatchResult";
                    $sqlResult = mysqli_query($databaseConnection, $sql);
                    $jobMatchResult = '';

                    if ($sqlResult) {
                        $resultData = mysqli_fetch_assoc($sqlResult);
                        if ($resultData) {
                            $jobMatchResult = $resultData['jobMatchResult'];
                        }

                        if ($jobMatchResult == 'NO' || $jobMatchResult == 'NA') {
                            $candiStatus = 'Profile Mismatch';
                            $resumeUploadFlag = 'NO';
                        } else {
                            $candiStatus = NULL;
                        }

                    }
                }
            }

            if ($insert_query) {
                $query7 = "UPDATE interviewSchedule SET 
                    candidateStatus = '$candiStatus'
                    WHERE id = '$scheduleId'";

                $insert_query7 = mysqli_query($databaseConnection, $query7);

                $to_encode = array(
                    'result' => 'success',
                    'status' => 1,
                    'rUploadFlag' => $resumeUploadFlag,
                    'candidateStatus' => $candiStatus,
                );
            } else {
                $to_encode = array(
                    'result' => 'error',
                    'status' => 0,
                    'errorCode' => 'Error while updating data into the database'
                );
            }

        } else if ($scheduleId !== null) {
            $query1 = "UPDATE interviewSchedule SET 
                expectedSalary = '$expectedSalary',
                currentSalary = '$currentSalary',
                currentLocation = '$location',
                noticePeriod = '$noticePeriod',workExperience='$workExperience',skillValues='$skills',employmentStatus='$employmentStatus',
                offer='$offeredStatus',offeredCTC='$offeredCTCInput',verifyFlag = 'Y'
                WHERE id = '$scheduleId'";

            $insert_query1 = mysqli_query($databaseConnection, $query1);

            if ($candidateEmailId !== null && $preId !== null) {
                if ($candiStatus == 'Profile Match' || $candiStatus == 'Profile Mismatch' || $candiStatus == 'Interview Scheduled') {
                    $sql = "SELECT jobMatch('$candidateEmailId',$preId) as jobMatchResult";
                    $sqlResult = mysqli_query($databaseConnection, $sql);
                    $jobMatchResult = '';

                    if ($sqlResult) {
                        $resultData = mysqli_fetch_assoc($sqlResult);
                        if ($resultData) {
                            $jobMatchResult = $resultData['jobMatchResult'];
                        }

                        if ($jobMatchResult == 'NO' || $jobMatchResult == 'NA') {
                            $candiStatus = 'Profile Mismatch';
                            $resumeUploadFlag = 'NO';
                        } else {
                            $candiStatus = NULL;
                        }

                    }
                }
            }

            if ($insert_query1) {
                $query8 = "UPDATE interviewSchedule SET 
                    candidateStatus = '$candiStatus'
                    WHERE id = '$scheduleId'";

                $insert_query8 = mysqli_query($databaseConnection, $query8);

                $to_encode = array(
                    'result' => 'success',
                    'status' => 1,
                    'rUploadFlag' => $resumeUploadFlag,
                    'candidateStatus' => $candiStatus,
                );
            } else {
                $to_encode = array(
                    'result' => 'error',
                    'status' => 0,
                    'errorCode' => 'Error while updating data into the database'
                );
            }

        } else {
            $to_encode = array(
                'result' => 'error',
                'status' => 0,
                'errorCode' => 'Neither candidateId nor scheduleId provided'
            );

            echo json_encode($to_encode);
        }
    } else {
        $to_encode = array(
            'result' => 'error',
            'status' => 0,
            'errorCode' => 'Error while decoding JSON'
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['getupdateComment'])) {
    $data = file_get_contents("php://input");
    $json = json_decode($data, true);

    if ($json !== null) {
        $candidateId = isset($json['candidateId']) ? $json['candidateId'] : null;
        $scheduleId = isset($json['scheduleId']) ? $json['scheduleId'] : null;
        $comment = isset($json['comment']) ? $json['comment'] : null;

        if ($scheduleId !== null && $comment !== null) {
            $query1 = "UPDATE interviewSchedule SET 
                comment = '$comment'
                WHERE id = '$scheduleId'";

            $insert_query1 = mysqli_query($databaseConnection, $query1);

            if ($insert_query1) {
                $to_encode = array(
                    'result' => 'success',
                    'status' => 1
                );
            } else {
                $to_encode = array(
                    'result' => 'error',
                    'status' => 0,
                    'errorCode' => 'Error while updating data into the database'
                );
            }

        } else {
            $to_encode = array(
                'result' => 'error',
                'status' => 0,
                'errorCode' => 'Neither candidateId nor scheduleId provided'
            );

            echo json_encode($to_encode);
        }
    } else {
        $to_encode = array(
            'result' => 'error',
            'status' => 0,
            'errorCode' => 'Error while decoding JSON'
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['updateBulkCandidateStatus'])) {
    $data = file_get_contents("php://input");
    $json = json_decode($data, true);
    $iscIdString = '';
    $filter = '';

    // $RecruiterEmail = "ananth@goprac.com";
    $RecruiterEmail = ($json['recruiterEmail'] != "") ? $json['recruiterEmail'] : "sushil@goprac.com";
    $cc = ($json['Cc'] != "") ? $json['Cc'] : NULL;
    $subjects = $json['subject'];
    $cs = ($json['cs']);
    $message = ($json['body']);
    $f2fBulkDate = $json['f2fBulkDate'] || $json['f2fBulkDate'] == 0 ? $json['f2fBulkDate'] : null;

    // print_r($f2fBulkDate);
    // exit();

    if (!empty($json['iscIds']) && $json['iscIds'] != ['0']) {

        if (is_array($json['iscIds'])) {
            $iscIdString = implode(",", $json['iscIds']);

            $filter = " WHERE isc.id IN (" . $iscIdString . ")";
        } else {
            $interviewnameString = $json['interviewname'];
            $filter = " WHERE isc.id IN (" . $iscIdString . ")";
        }

        $query = "UPDATE interviewSchedule isc SET candidateStatus = '" . $cs . "', candidateStatusDate = CURDATE(), resumeSharedDate = CURDATE()" . $filter;
        // echo  $query ;
        $insert_query = mysqli_query($databaseConnection, $query);

        // if (is_array($json['iscIds'])) {
        //     $iscIdString = implode(",", $json['iscIds']);
        // } else {
        //     $iscIdString = $json['iscIds']; // Ensure it's properly formatted
        // }

        // // Step 1: Fetch emailId and preInterviewId for the given iscIds
        // $emailQuery = "SELECT emailId, preInterviewId FROM interviewSchedule WHERE id IN ($iscIdString)";
        // $emailResult = mysqli_query($databaseConnection, $emailQuery);

        // $updatedCount = 0;

        // while ($row = mysqli_fetch_assoc($emailResult)) {
        //     $emailId = $row['emailId'];
        //     $preInterviewId = $row['preInterviewId'];

        //     // Step 2: Update each record separately
        //     $updateQuery = "UPDATE interviewSchedule 
        //                     SET candidateStatus = '$cs', 
        //                         candidateStatusDate = CURDATE(), 
        //                         resumeSharedDate = CURDATE() 
        //                     WHERE emailId = '$emailId' 
        //                     AND preInterviewId = '$preInterviewId'";

        //     $insert_query = mysqli_query($databaseConnection, $updateQuery);

        //     if ($insert_query) {
        //         $updatedCount++;
        //     } else {
        //         echo "Failed to update for Email: $emailId, Pre-Interview ID: $preInterviewId. Error: <br>";
        //         // echo "Failed to update for Email: $emailId, Pre-Interview ID: $preInterviewId. Error: " . mysqli_error($databaseConnection) . "<br>";
        //     }
        // }



        if ($cs == "Client Shortlisted") {
            foreach ($json['iscIds'] as $id) {

                $iscQuery = "SELECT preInterviewId,candidateName,emailId,mobileNumber FROM interviewSchedule WHERE id = $id";
                $iscQueryResult = mysqli_query($databaseConnection, $iscQuery);

                if ($iscQueryResult) {
                    $iscData = mysqli_fetch_assoc($iscQueryResult);

                    if ($iscData) {
                        $preInterviewId = $iscData['preInterviewId'];
                        $candidateName = $iscData['candidateName'];
                        $candidateEmailId = $iscData['emailId'];
                        $mobile = $iscData['mobileNumber'];

                        $roleQuery = "SELECT position as roleId, GROUP_CONCAT(subject) as subjectIds FROM scps_transaction WHERE preInterviewId = $preInterviewId";
                        $roleQueryResult = mysqli_query($databaseConnection, $roleQuery);
                        // echo  $roleQuery; 

                        if ($roleQueryResult) {
                            $roleData = mysqli_fetch_assoc($roleQueryResult);

                            if ($roleData) {
                                $roleId = $roleData['roleId'];
                                $subjectId = $roleData['subjectIds'];

                                $insertQuery1 = "INSERT INTO register (registeredTime, roleId, subjectId, name, email, phone_no, candidateStatus,preId,f2fDate) 
                                VALUES (NOW(), '$roleId', '$subjectId', '$candidateName', '$candidateEmailId', '$mobile', 'client shortlisted',$preInterviewId,'$f2fBulkDate')";

                                $result = mysqli_query($databaseConnection, $insertQuery1);

                            } else {
                                // echo "No data found for preInterviewId = $preIdInt";
                            }
                        } else {
                            // echo "Error executing query: " . mysqli_error($databaseConnection);
                        }

                    }
                }
            }

        }


        if ($insert_query) {
            $to_encode = array(
                'result' => 'success',
                'status' => 1,
            );
        } else {
            $to_encode = array(
                'result' => 'error',
                'status' => 0,
                'errorCode' => 'Error while inserting data into the database'
            );
        }

        echo json_encode($to_encode);

        if ($json['cs'] == 'Profile Shared') {
            // Send the email
            $to = $RecruiterEmail;
            // $to = 'sourabh13689@gmail.com';
            $messages = $message;
            // echo  $messages;
            sendEmailToUser($to, $cc, $subjects, $messages);
        }

    } else {
        $to_encode = array(
            'result' => 'error',
            'status' => 0,
            'errorCode' => 'Invalid or empty iscIds'
        );
        echo json_encode($to_encode);
    }
} elseif (isset($_GET['assignEmailTemplate'])) {
    $data = file_get_contents("php://input");
    $json = json_decode($data, true);

    $companyId = $json['companyId'];
    $emailTemplateColumns = $json['emailTemplateColumns'];

    if ($companyId !== null && $companyId !== '') {

        $sql = "SELECT * from companyEmailTemplate WHERE companyId = '$companyId'";
        $check_query = mysqli_query($databaseConnection, $sql);

        if (mysqli_num_rows($check_query) > 0) {
            $query = "UPDATE companyEmailTemplate SET companyEmailColumn ='$emailTemplateColumns' WHERE companyId = '$companyId'";
            $update_query = mysqli_query($databaseConnection, $query);

            if ($update_query) {
                $to_encode = array(
                    'result' => 'Email Template update Successfully',
                    'status' => 1,
                );
            } else {
                $to_encode = array(
                    'result' => 'error',
                    'status' => 0,
                    'errorCode' => 'Error while updating data into the database'
                );
            }
        } else {
            $query1 = "INSERT INTO companyEmailTemplate (companyId,companyEmailColumn) VALUES ('$companyId','$emailTemplateColumns')";
            $insert_query = mysqli_query($databaseConnection, $query1);

            if ($insert_query) {
                $to_encode = array(
                    'result' => 'Email Template Assign Successfully',
                    'status' => 1,
                );
            } else {
                $to_encode = array(
                    'result' => 'error',
                    'status' => 0,
                    'errorCode' => 'Error while updating data into the database'
                );
            }
        }

    } else {
        $to_encode = array(
            'result' => 'error',
            'status' => 0,
            'errorCode' => 'companyId not provided'
        );
        echo json_encode($to_encode);
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['getCompanyEmailTemplate'])) {
    $data = file_get_contents("php://input");
    $json = json_decode($data, true);

    $companyId = $json['companyId'];

    if ($companyId !== null && $companyId !== '') {

        $sql = "SELECT id, companyEmailColumn from companyEmailTemplate WHERE companyId = '$companyId'";
        $check_query = mysqli_query($databaseConnection, $sql);

        if (mysqli_num_rows($check_query) > 0) {
            $companyData = mysqli_fetch_assoc($check_query);
            if ($companyData) {
                $companyEmailColumns = $companyData['companyEmailColumn'];
            } else {
                $companyEmailColumns = '';
            }

            if ($check_query) {
                $to_encode = array(
                    'result' => 'get data',
                    'companyEmailColumns' => $companyEmailColumns,
                    'status' => 1,
                );
            } else {
                $to_encode = array(
                    'result' => 'error',
                    'status' => 0,
                    'errorCode' => 'Error while updating data into the database'
                );
            }
        } else {
            $to_encode = array(
                'result' => 'error',
                'status' => 0,
                'errorCode' => 'data not found'
            );

        }

    } else {
        $to_encode = array(
            'result' => 'error',
            'status' => 0,
            'errorCode' => 'companyId not provided'
        );
        echo json_encode($to_encode);
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['editAssignCompanyEmailTemplate'])) {
    $data = file_get_contents("php://input");
    $json = json_decode($data, true);

    $companyId = $json['companyId'];

    if ($companyId !== null && $companyId !== '') {

        $sql = "SELECT id, companyEmailColumn from companyEmailTemplate WHERE companyId = '$companyId'";
        $check_query = mysqli_query($databaseConnection, $sql);

        if (mysqli_num_rows($check_query) > 0) {
            $companyData = mysqli_fetch_assoc($check_query);
            if ($companyData) {
                $companyEmailColumns = $companyData['companyEmailColumn'];
            } else {
                $companyEmailColumns = '';
            }

            if ($check_query) {
                $to_encode = array(
                    'result' => 'get data',
                    'companyEmailColumns' => $companyEmailColumns,
                    'status' => 1,
                );
            } else {
                $to_encode = array(
                    'result' => 'error',
                    'status' => 0,
                    'errorCode' => 'Error while updating data into the database'
                );
            }
        } else {
            $to_encode = array(
                'result' => 'error',
                'status' => 0,
                'errorCode' => 'data not found'
            );

        }

    } else {
        $to_encode = array(
            'result' => 'error',
            'status' => 0,
            'errorCode' => 'companyId not provided'
        );
        echo json_encode($to_encode);
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['updateCandidateLeadStatus'])) {
    $data = file_get_contents("php://input");
    $json = json_decode($data, true);

    $apmId = $json['apmId'];
    $status = $json['lstatus'];


    if ($apmId !== null) {
        $query = "UPDATE resume_apm SET 
              leadStatus ='$status ' 
              WHERE id = '$apmId'";
    } else {
        $to_encode = array(
            'result' => 'error',
            'status' => 0,
            'errorCode' => 'Id not provided'
        );
        echo json_encode($to_encode);
    }

    $insert_query = mysqli_query($databaseConnection, $query);

    if ($insert_query) {
        $to_encode = array(
            'result' => 'success',
            'status' => 1,
        );
    } else {
        $to_encode = array(
            'result' => 'error',
            'status' => 0,
            'errorCode' => 'Error while inserting data into the database'
        );
    }

    echo json_encode($to_encode);
} else if (isset($_GET['review_ics'])) {
    // node-api
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    $to_encode = array();
    $to_encode['error'] = "0";
    if (isset($json) && isset($json['id'])) {
        $interviewSessionId = $json['id'];

        $candidate_sql = "SELECT candidateId, interviewId FROM feedback_request where interviewSessionId in('" . $interviewSessionId . "') order by id desc limit 1";
        // echo $candidate_sql;
        $candidate_query = mysqli_query($databaseConnection, $candidate_sql);
        if ($candidate_query) {
            $candidate = mysqli_fetch_all($candidate_query, MYSQLI_ASSOC);
            if (!empty($candidate)) {
                $to_encode['candidateId'] = $candidate[0]['candidateId'];
                $to_encode['interviewId'] = $candidate[0]['interviewId'];
            } else {
                $to_encode['error'] = "1";
            }
        } else {
            $to_encode['error'] = "1";

        }
    }
    echo json_encode($to_encode);
}
else if (isset($_GET['getDashboardDetatils'])) {
    // depricated
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    $userId = $json['userId'];
    // $userType = $json['userType'];
    $candidateId = $json['candidateId'];
    $filterQuery = '';
    $filterQuery1 = '';

    $candidate_sql = "select firstName, usertype, emailId from users where id = '" . $candidateId . "'";
    $candidate_query = mysqli_query($databaseConnection, $candidate_sql);
    $candidate = mysqli_fetch_all($candidate_query, MYSQLI_ASSOC);
    //  print_r($candidate);
    $candidateEmailId = $candidate[0]['emailId'];
    //  exit();


    if ($candidate[0]['usertype'] == 'corporate') {
        $filterQuery .= " AND fr.review_status IN (2) AND i.companyId NOT IN (SELECT company_id FROM preInterview WHERE userId NOT IN (" . $json['userId'] . ")) ";
        $filterQuery1 .= " AND fr.review_status IN (2) AND i.companyId NOT IN (SELECT company_id FROM preInterview WHERE userId NOT IN (" . $json['userId'] . ")) ";
    } else {
        $filterQuery .= " AND fr.review_status IN (2,1,0,-3,-4,-2) ";
        $filterQuery1 .= " AND fr.review_status IN (2,1,0,3,-3,-4,-2) ";
    }


    $sql = "SELECT  t.*,
        CASE 
            WHEN t.publish = 'Y' AND t.interviewStatus = 'Active' THEN 'Open'
            WHEN t.publish = 'Y' AND t.interviewStatus = 'Inactive' THEN 'Closed'
            WHEN t.publish = 'C' AND t.interviewStatus = 'Inactive' THEN 'Closed'
            WHEN t.publish = 'C' AND t.interviewStatus = 'Active' THEN 'Closed'
            WHEN t.publish = 'L' AND t.interviewStatus = 'Active' THEN 'Open'
            WHEN t.publish = 'L' AND t.interviewStatus = 'Inactive' THEN 'Closed'
            WHEN t.publish = 'N' AND t.interviewStatus = 'Active' THEN 'Open'
            WHEN t.publish = 'N' AND t.interviewStatus = 'Inactive' THEN 'Closed'
            ELSE 'Open' 
        END AS jobStatus,
        CASE 
           WHEN t.candidateStatus IS NULL AND (t.fr_id IS NOT NULL AND (t.review_status = 2)) THEN 'Assessment Completed' 
           WHEN ((t.fr_id IS NOT NULL AND t.completion_status IS NOT NULL AND t.review_status IN (0,1)) OR (t.fr_id IS NOT NULL AND t.completion_status IS NOT NULL AND t.review_status = -2)) THEN 'Assessment Awaited' 
           WHEN t.candidateStatus IS NULL AND (
               (t.fr_id IS NOT NULL AND (t.review_status = -4 AND t.reasonOfRejection = 'duplicateAttempt')) OR 
               (t.fr_id IS NOT NULL AND (t.review_status = -4 AND t.reasonOfRejection = 'limitedFreeAssessment')) OR 
               (t.fr_id IS NOT NULL AND (t.review_status = -4 AND t.reasonOfRejection = 'unauthorizedUser')) OR 
               (t.fr_id IS NOT NULL AND (t.review_status = -4 AND t.reasonOfRejection = 'incompleteInterview')) OR 
               (t.fr_id IS NOT NULL AND (t.review_status = -4 AND t.reasonOfRejection = 'technicalIssue')) OR 
               (t.fr_id IS NOT NULL AND (t.review_status = -4 AND t.reasonOfRejection NOT IN ('technicalIssue', 'incompleteInterview')))
           ) THEN 'Assessment Rejected' 
           WHEN t.candidateStatus IS NULL AND (t.fr_id IS NULL AND t.scheduleTime = 1) THEN 'Future Scheduled' 
           WHEN t.candidateStatus IS NULL AND (
               t.fr_id IS NULL AND 
               (t.scheduleTime != t.firstScheduleDate) AND 
               (DATEDIFF(t.scheduleTime, NOW())) >= 1
           ) THEN 'Re-Scheduled' 
           WHEN t.candidateStatus IS NULL AND t.scheduleTime IS NULL THEN 'Applied' 
           WHEN (t.fr_id IS NULL AND t.review_status IS NULL) THEN 'Not Attempted' 
           ELSE t.candidateStatus 
        END AS newcandidStatus, 
        CASE 
            WHEN (t.pendingInterviews = 'NR' ) THEN 'NA'
            WHEN (t.fr_id IS NOT NULL AND(t.review_status = 2) ) THEN 'Assessment Completed'
            WHEN ((t.fr_id IS NOT NULL OR t.completion_status IS NOT NULL) AND t.review_status IN (0, 1)) THEN 'Assessment in Progress'
            WHEN ((t.fr_id IS NOT NULL OR t.completion_status IS NOT NULL) AND t.review_status = -2) THEN 'Internal Review'
            WHEN (t.fr_id IS NOT NULL AND(t.review_status = -4 AND t.reasonOfRejection = 'incompleteInterview')) THEN 'Incomplete'
            WHEN (t.fr_id IS NOT NULL AND(t.review_status = -4 AND t.reasonOfRejection = 'technicalIssue')) THEN 'Technical Issue'
            WHEN (t.fr_id IS NOT NULL AND(t.review_status = -4 AND t.reasonOfRejection NOT IN ('technicalIssue','incompleteInterview'))) THEN 'Rejected'
            WHEN (t.fr_id IS NOT NULL AND(t.review_status = -4 AND t.reasonOfRejection = 'duplicateAttempt')) THEN 'duplicateAttempt'
            WHEN (t.fr_id IS NOT NULL AND(t.review_status = -4 AND t.reasonOfRejection = 'limitedFreeAssessment')) THEN 'limitedFreeAssessment'
            WHEN (t.fr_id IS NOT NULL AND(t.review_status = -4 AND t.reasonOfRejection = 'unauthorizedUser')) THEN 'unauthorizedUser'
            WHEN (t.fr_id IS NULL AND(t.scheduleTime != t.firstScheduleDate) AND(DATEDIFF(t.scheduleTime, NOW())) >= 1) THEN 'Re-Scheduled'
            WHEN (t.fr_id IS NULL AND t.scheduleTime = 1) THEN 'Future Scheduled'
            WHEN (t.fr_id IS NULL AND(t.scheduleTime = t.firstScheduleDate) AND(DATEDIFF(t.scheduleTime, NOW())) >= 1) THEN 'Future Scheduled'
            WHEN (t.fr_id IS NULL AND t.scheduleTime is not null and DATEDIFF(t.scheduleTime, NOW()) < 1 ) THEN 'Missed Scheduled' 
            WHEN (t.fr_id IS NULL AND t.review_status IS NULL AND t.scheduleTime IS NOT NULL) THEN 'Scheduled'
            WHEN (t.fr_id IS NULL AND t.review_status IS NULL AND t.scheduleTime IS NULL) THEN 'Job Invited'
        END AS interviewStatus,
        COALESCE(t.interviewName,(select name from aspiration_company where id= t.company_id)) as interviewName,
        (
            SELECT name from aspiration_company where id= t.company_id 
        ) as hiring_company,
        (
            SELECT 
                JSON_ARRAYAGG(
                    JSON_OBJECT(
                        'malpracticeValue', mt.malpracticeValue,
                        'interviewName', mt.interviewName,
                        'interviewSessionId', mt.interviewSessionId,
                        'count', mt.cnt
                    )
                )
            FROM (
                SELECT 
                    mv.candidateId,
                    mv.malpracticeValue,
                    pr.interviewName,
                    mv.interviewSessionId,
                    COUNT(*) AS cnt
                FROM feedback_request fr
                JOIN mergedVideos mv ON fr.interviewSessionId = mv.interviewSessionId
                JOIN AnswerTranscription at ON mv.mergeId = at.mergeId
                JOIN preInterview pr ON pr.id = fr.preInterviewId
                WHERE at.ansText IS NOT NULL
                AND mv.malpracticeValue IS NOT NULL
                AND mv.interviewSessionId = t.interviewSessionId
                    GROUP BY mv.malpracticeValue
            ) mt
        ) as malpractice_stats
        FROM (
                SELECT 
                m.interviewId AS interviewId, 
                fr.review_status, 
                fr.reasonOfRejection,
                isc.scheduleTime,
                isc.firstScheduleDate,
                cit.completion_status,
                fr.id as fr_id,
                m.candidateId, 
                pr.interviewName,
                pr.pendingInterviews,
                pr.company_id,
                m.interviewSessionId, 
                CONCAT('/review?i=', m.interviewId, '&c=', m.candidateId, '&s=', m.interviewSessionId) AS url,
                CONCAT('/job?p=',i.preInterviewId) AS jobUrl,  
                fr.suitability, 
                i.preInterviewId,
                isc.candidateStatus,
                isc.id as iscId,
                pr.publish,
                pr.interviewStatus,
                (
                    SELECT status 
                    FROM payment_transaction 
                    WHERE user_id = m.candidateId
                        AND interview_id =  m.interviewId
                        AND subscriptionType = 'job'
                    ORDER BY
                        CASE WHEN status = 'PAID' THEN 0 ELSE 1 END, 
                        status
                    LIMIT 1
                ) AS payment_status
                FROM mergedVideos m 
                INNER JOIN interview i ON m.interviewId = i.id 
                INNER JOIN feedback_request fr ON fr.candidateId = m.candidateId AND fr.interviewSessionId = m.interviewSessionId 
                JOIN interviewSchedule isc ON isc.candidate_id = m.candidateId and isc.interviewId=m.interviewId 
                LEFT JOIN candidate_interview_transection cit ON cit.interviewId = m.interviewId 
                left join preInterview pr on pr.id = i.preInterviewId
                WHERE pr.interviewType='job' AND m.candidateId =  " . $candidateId . " AND m.interviewSessionId IS NOT NULL 
                " . $filterQuery . "
                GROUP BY m.interviewSessionId 
                ORDER BY m.interviewSessionId DESC
            ) as t;
        ";

    // echo $sql; 
    // exit();
    $job_query = mysqli_query($databaseConnection, $sql);


    $apply_sql = "
        SELECT  t.*,
        CASE 
            WHEN t.publish = 'Y' AND t.interviewStatus = 'Active' THEN 'Open'
            WHEN t.publish = 'Y' AND t.interviewStatus = 'Inactive' THEN 'Closed'
            WHEN t.publish = 'C' AND t.interviewStatus = 'Inactive' THEN 'Closed'
            WHEN t.publish = 'C' AND t.interviewStatus = 'Active' THEN 'Closed'
            WHEN t.publish = 'L' AND t.interviewStatus = 'Active' THEN 'Open'
            WHEN t.publish = 'L' AND t.interviewStatus = 'Inactive' THEN 'Closed'
            WHEN t.publish = 'N' AND t.interviewStatus = 'Active' THEN 'Open'
            WHEN t.publish = 'N' AND t.interviewStatus = 'Inactive' THEN 'Closed'
            ELSE 'Open' 
        END AS jobStatus,
        CASE 
        WHEN t.candidateStatus IS NULL AND (t.fr_id IS NOT NULL AND (t.review_status = 2)) THEN 'Assessment Completed' 
        WHEN ((t.fr_id IS NOT NULL AND t.completion_status IS NOT NULL AND t.review_status IN (0,1)) OR (t.fr_id IS NOT NULL AND t.completion_status IS NOT NULL AND t.review_status = -2)) THEN 'Assessment Awaited' 
        WHEN t.candidateStatus IS NULL AND (
            (t.fr_id IS NOT NULL AND (t.review_status = -4 AND t.reasonOfRejection = 'duplicateAttempt')) OR 
            (t.fr_id IS NOT NULL AND (t.review_status = -4 AND t.reasonOfRejection = 'limitedFreeAssessment')) OR 
            (t.fr_id IS NOT NULL AND (t.review_status = -4 AND t.reasonOfRejection = 'unauthorizedUser')) OR 
            (t.fr_id IS NOT NULL AND (t.review_status = -4 AND t.reasonOfRejection = 'incompleteInterview')) OR 
            (t.fr_id IS NOT NULL AND (t.review_status = -4 AND t.reasonOfRejection = 'technicalIssue')) OR 
            (t.fr_id IS NOT NULL AND (t.review_status = -4 AND t.reasonOfRejection NOT IN ('technicalIssue', 'incompleteInterview')))
        ) THEN 'Assessment Rejected' 
        WHEN t.candidateStatus IS NULL AND (t.fr_id IS NULL AND t.scheduleTime = 1) THEN 'Future Scheduled' 
        WHEN t.candidateStatus IS NULL AND (
            t.fr_id IS NULL AND 
            (t.scheduleTime != t.firstScheduleDate) AND 
            (DATEDIFF(t.scheduleTime, NOW())) >= 1
        ) THEN 'Re-Scheduled' 
        WHEN (t.fr_id IS NULL AND t.review_status IS NULL AND t.candidateStatus in('applied')) THEN 'Submitted'
        WHEN t.candidateStatus IS NULL AND t.scheduleTime IS NULL THEN 'Submitted'
         WHEN t.candidateStatus IS NULL THEN 'Submitted' 
        ELSE t.candidateStatus 
        END AS newcandidStatus, 
        CASE 
            WHEN (t.pendingInterviews = 'NR' ) THEN 'NA'
            WHEN (t.fr_id IS NOT NULL AND(t.review_status = 2) ) THEN 'Assessment Completed'
            WHEN ((t.fr_id IS NOT NULL OR t.completion_status IS NOT NULL) AND t.review_status IN (0, 1)) THEN 'Assessment in Progress'
            WHEN ((t.fr_id IS NOT NULL OR t.completion_status IS NOT NULL) AND t.review_status = -2) THEN 'Internal Review'
            WHEN (t.fr_id IS NOT NULL AND(t.review_status = -4 AND t.reasonOfRejection = 'incompleteInterview')) THEN 'Incomplete'
            WHEN (t.fr_id IS NOT NULL AND(t.review_status = -4 AND t.reasonOfRejection = 'technicalIssue')) THEN 'Technical Issue'
            WHEN (t.fr_id IS NOT NULL AND(t.review_status = -4 AND t.reasonOfRejection NOT IN ('technicalIssue','incompleteInterview'))) THEN 'Rejected'
            WHEN (t.fr_id IS NOT NULL AND(t.review_status = -4 AND t.reasonOfRejection = 'duplicateAttempt')) THEN 'duplicateAttempt'
            WHEN (t.fr_id IS NOT NULL AND(t.review_status = -4 AND t.reasonOfRejection = 'limitedFreeAssessment')) THEN 'limitedFreeAssessment'
            WHEN (t.fr_id IS NOT NULL AND(t.review_status = -4 AND t.reasonOfRejection = 'unauthorizedUser')) THEN 'unauthorizedUser'
            WHEN (t.fr_id IS NULL AND(t.scheduleTime != t.firstScheduleDate) AND(DATEDIFF(t.scheduleTime, NOW())) >= 1) THEN 'Re-Scheduled'
            WHEN (t.fr_id IS NULL AND t.scheduleTime = 1) THEN 'Future Scheduled'
            WHEN (t.fr_id IS NULL AND(t.scheduleTime = t.firstScheduleDate) AND(DATEDIFF(t.scheduleTime, NOW())) >= 1) THEN 'Future Scheduled'
            WHEN (t.fr_id IS NULL AND t.scheduleTime is not null and DATEDIFF(t.scheduleTime, NOW()) < 1 ) THEN 'Missed Scheduled'
            WHEN (t.fr_id IS NULL AND t.review_status IS NULL AND t.scheduleTime IS NOT NULL) THEN 'Scheduled'
            WHEN (t.fr_id IS NULL AND t.review_status IS NULL AND t.scheduleTime IS NULL) THEN 'Job Invited'
        END AS interviewStatus,
        COALESCE(t.interviewName,(select name from aspiration_company where id= t.company_id)) as interviewName,(select name from aspiration_company where id= t.company_id) as hiring_company
        FROM (
        select 
            isc.interviewId AS interviewId,
            null as review_status,
            null as reasonOfRejection,
            isc.scheduleTime,
            isc.firstScheduleDate,
            null as completion_status,
            null as fr_id,
            isc.candidate_id as candidateId,
            pr.interviewName,
            pr.company_id,
            pr.pendingInterviews,
            null as interviewSessionId,
            null AS url,
            CONCAT('/job?p=', isc.preInterviewId) AS jobUrl,
            null as suitability,
            isc.preInterviewId,
            isc.candidateStatus,
            isc.id as iscId,
            pr.publish,
            pr.interviewStatus,
            null AS payment_status
        FROM interviewSchedule isc
        LEFT JOIN preInterview pr on pr.id = isc.preInterviewId
        WHERE
            pr.interviewType='job'
            and isc.candidate_id =  " . $candidateId . "
            and isc.submissionFlag IN('Y','WA')
            and isc.candidateStatus <> 'Error'
            and isc.interviewId is null
        GROUP BY
            isc.id
        ORDER BY
            isc.id DESC) as t;";

    // echo $apply_sql; 
    // exit();
    $apply_query = mysqli_query($databaseConnection, $apply_sql);

    $sqlcount = " select m.mergeId 
        FROM  mergedVideos m 
        INNER JOIN   
            interview i ON m.interviewId = i.id  
        INNER JOIN 
            feedback_request fr ON fr.candidateId = m.candidateId AND fr.interviewSessionId = m.interviewSessionId 
        JOIN 
            interviewSchedule isc ON isc.candidate_id = m.candidateId and isc.interviewId=m.interviewId 
        LEFT JOIN 
            candidate_interview_transection cit ON cit.interviewId = m.interviewId 
        left join preInterview pr on pr.id = i.preInterviewId
        WHERE 
            pr.interviewType='job' and
            m.candidateId =  " . $candidateId . "
            AND m.interviewSessionId IS NOT NULL 
            " . $filterQuery . "
        GROUP BY 
        m.interviewSessionId ;";
    $subject_countquery = mysqli_query($databaseConnection, $sqlcount);
    //for practice

    $psql = "SELECT
            cim.*,
            rr.name AS role,
            GROUP_CONCAT(fs.favourite_subject) AS subject,
            pr.interviewName AS product,
            fr.intScore
        FROM
            candidateInterviewMapping cim
        LEFT JOIN preInterview pr ON pr.id = cim.preInterviewId
        LEFT JOIN relavant_role rr ON rr.id = cim.role
        LEFT JOIN favourite_subject fs ON FIND_IN_SET(fs.id, cim.subject) > 0
           LEFT JOIN feedback_request fr ON fr.preInterviewId = cim.preInterviewId  AND fr.candidateId = cim.candidateId 
        AND fr.intScore = (
            SELECT MAX(intScore) 
            FROM feedback_request 
            WHERE preInterviewId = cim.preInterviewId and candidateId = cim.candidateId 
        )
        WHERE
            cim.id IN (
                SELECT MAX(cim_sub.id)
                FROM candidateInterviewMapping cim_sub
                LEFT JOIN preInterview pr_sub ON pr_sub.id = cim_sub.preInterviewId
                WHERE pr_sub.interviewType = 'Practice'
                AND cim_sub.candidateId = " . $candidateId . "
                GROUP BY cim_sub.preInterviewId
            )
        GROUP BY
            cim.id
        ORDER BY
            cim.id DESC;";

    // echo $psql;
    // exit();

    $practice_query = mysqli_query($databaseConnection, $psql);

    $psqlchild = "SELECT 
        t.*,
        CASE 
            WHEN (t.fr_id IS NOT NULL AND t.review_status in (2,3)) THEN 'Assessment Completed'
            WHEN ((t.fr_id IS NOT NULL OR t.completion_status IS NOT NULL) AND t.review_status IN (0, 1)) THEN 'Assessment in Progress'
            WHEN ((t.fr_id IS NOT NULL OR t.completion_status IS NOT NULL) AND t.review_status = -2) THEN 'Internal Review'
            WHEN (t.fr_id IS NOT NULL AND t.review_status = -4 AND t.reasonOfRejection = 'incompleteInterview') THEN 'Incomplete'
            WHEN (t.fr_id IS NOT NULL AND t.review_status = -4 AND t.reasonOfRejection = 'technicalIssue') THEN 'Technical Issue'
            WHEN (t.fr_id IS NOT NULL AND t.review_status = -4 AND t.reasonOfRejection NOT IN ('technicalIssue', 'incompleteInterview')) THEN 'Rejected'
            WHEN (t.fr_id IS NOT NULL AND t.review_status = -4 AND t.reasonOfRejection = 'duplicateAttempt') THEN 'duplicateAttempt'
            WHEN (t.fr_id IS NOT NULL AND t.review_status = -4 AND t.reasonOfRejection = 'limitedFreeAssessment') THEN 'limitedFreeAssessment'
            WHEN (t.fr_id IS NOT NULL AND t.review_status = -4 AND t.reasonOfRejection = 'unauthorizedUser') THEN 'unauthorizedUser'
            WHEN (t.fr_id IS NULL AND t.scheduleTime != t.firstScheduleDate AND DATEDIFF(t.scheduleTime, NOW()) >= 1) THEN 'Re-Scheduled'
            WHEN (t.fr_id IS NULL AND t.scheduleTime = 1) THEN 'Future Scheduled'
            WHEN (t.fr_id IS NULL AND t.scheduleTime = t.firstScheduleDate AND DATEDIFF(t.scheduleTime, NOW()) >= 1) THEN 'Future Scheduled'
            WHEN (t.fr_id IS NULL AND t.review_status IS NULL AND t.scheduleTime IS NOT NULL) THEN 'Scheduled'
            WHEN (t.fr_id IS NULL AND t.review_status IS NULL AND t.scheduleTime IS NULL) THEN 'Job Invited'
        END AS interviewStatus 
        FROM (
        SELECT
            fr.reportpdf1,
            fr.review_status, 
            fr.reasonOfRejection,
            isc.scheduleTime,
            isc.firstScheduleDate,
            cit.completion_status,
            fr.id AS fr_id,
            m.mergeId,
            m.candidateId,
            m.interviewId,
            i.preInterviewId,
            i.last_activity_at,
            m.interviewSessionId,
            CONCAT('/review?i=', m.interviewId, '&c=', m.candidateId, '&s=', m.interviewSessionId) AS url, 
            CASE 
                WHEN fr.suitability = 'Do not meet' THEN 'Below Industry Standard'
                WHEN fr.suitability = 'Must meet' THEN 'At par with Industry Standard'
                WHEN fr.suitability = 'Recommended to meet' THEN 'Close to Industry Standard'
                ELSE fr.suitability
            END AS suitability,
            pr.interviewType,
            pr.interviewName,
            pr.id,
            (
            SELECT status 
            FROM payment_transaction 
            WHERE user_id = m.candidateId
                AND subscriptionType = 'practice'
            ORDER BY
                CASE WHEN status = 'PAID' THEN 0 ELSE 1 END, 
                status
            LIMIT 1
            ) AS payment_status,
            (
                select
                    JSON_ARRAYAGG( JSON_OBJECT( 'malpracticeValue', mt.malpracticeValue, 'interviewName', mt.interviewName, 'interviewSessionId', mt.interviewSessionId, 'count', mt.cnt ) )
                from
                (
                select
                    mv.candidateId,
                    mv.malpracticeValue,
                    prv.interviewName,
                    mv.interviewSessionId,
                    COUNT(*) as cnt
                from feedback_request frv
                join mergedVideos mv on frv.interviewSessionId = mv.interviewSessionId
                join AnswerTranscription at on mv.mergeId = at.mergeId
                join preInterview prv on prv.id = frv.preInterviewId
                where
                    at.ansText is not null
                    and mv.malpracticeValue is not null
                    and mv.interviewSessionId = m.interviewSessionId
                group by mv.malpracticeValue ) mt
            ) as malpractice_stats
        FROM mergedVideos m 
        INNER JOIN interview i ON m.interviewId = i.id 
        INNER JOIN feedback_request fr ON fr.candidateId = m.candidateId AND fr.interviewSessionId = m.interviewSessionId 
        JOIN interviewSchedule isc ON isc.candidate_id = m.candidateId and isc.interviewId=m.interviewId 
        LEFT JOIN candidate_interview_transection cit ON cit.interviewId = m.interviewId 
        INNER JOIN preInterview pr ON pr.id = i.preInterviewId
        WHERE pr.interviewType='Practice' AND m.candidateId = " . $candidateId . "
        " . $filterQuery1 . "
        GROUP BY m.interviewId
        ORDER BY m.interviewSessionId DESC
        ) AS t;";

    // echo $psqlchild;
    // exit();
    $practicechild_query = mysqli_query($databaseConnection, $psqlchild);

    $recommendedJobs = "SELECT
            c.id,
            CASE
                WHEN c.id = 0 OR c.id IS NULL THEN pr.interviewName
                WHEN pr.interviewName IS NOT NULL THEN pr.interviewName
                ELSE c.name
            END AS `name`,
            c.name as company,
            pr.productId AS productId,
            st.sector AS sectorId,
            pr.targetAudience AS targetAudience,
            pr.duration AS duration,
            pr.categoryType AS categoryType,
            pr.interviewLevel AS interviewLevel,
            st.assessmenttype AS assessmenttype,
            pr.id AS preInterviewId,
            CASE
                WHEN pr.interviewExpireDate >= NOW() OR pr.interviewExpireDate IS NULL THEN 'Active'
                ELSE 'Inactive'
            END AS status,
            CASE
                WHEN st.preInterviewId IS NULL AND pr.jobCategory = 'interview' THEN 'dummy'
                ELSE 'real'
            END AS intCat,
            pp.fieldValue AS jobWorkExperience,
            pp2.fieldValue AS jobLocation,
            loc.cityName AS jobLocationName
        FROM preInterview pr
        LEFT JOIN scps_transaction st ON st.preInterviewId = pr.id
        LEFT JOIN aspiration_company c ON st.company = c.id
        LEFT JOIN sector s ON s.id = st.sector
        LEFT JOIN profilePreferences pp ON pr.id = pp.preInterviewId AND pp.fieldName = 'workExperience'
        LEFT JOIN profilePreferences pp2 ON pr.id = pp2.preInterviewId AND pp2.fieldName = 'currentLocation'
        LEFT JOIN locations loc ON loc.id = pp2.fieldValue
        WHERE 1
            AND pr.interviewExpireDate >= NOW()
            AND pr.publish IN ('Y', 'C')
            AND pr.serviceType != 'IAS'
            AND pr.id > 758
        GROUP BY
            pr.id
        ORDER BY
            pr.interviewExpireDate DESC,
            pr.id DESC
        LIMIT 50;
    ";
    $recommendedPractice = "SELECT
            pr.id,
            pr.interviewName AS `name`,
            pr.targetAudience AS targetAudience,
            pr.duration AS duration,
            pr.categoryType AS categoryType,
            pr.interviewLevel AS interviewLevel,
            pr.id AS preInterviewId,
            pr.YOE AS eligibility
        FROM preInterview pr
        WHERE 1
            AND pr.interviewType= 'Practice'
            AND pr.practiceType = 'freetrial'
        GROUP BY
            pr.id
        ORDER BY
            pr.id DESC
        LIMIT 15;";


    // barChartData
    $sql = "
            SELECT fr.id,i.preInterviewId, fr.intScore, fs.favourite_subject 
            FROM feedback_request fr
            LEFT JOIN interview i ON i.id = fr.interviewId
            LEFT JOIN preInterview pr ON pr.id = i.preInterviewId
            LEFT JOIN scps_transaction scps ON scps.preInterviewId = pr.id
            LEFT JOIN favourite_subject fs ON fs.id = scps.subject 
            WHERE 1
            AND pr.interviewType  = 'practice'
            AND fr.intScore IS NOT NULL 
            AND fr.review_status IN('2','3')
            AND i.preInterviewId IS NOT NULL
            AND fr.candidateId = '$candidateId'
            group by fr.interviewSessionId
            ORDER BY fr.id ASC
        ";
    $result = mysqli_query($databaseConnection, $sql);

    $barChartData = [];
    if ($result) {
        $counter = 1;
        while ($row = mysqli_fetch_assoc($result)) {
            $preInterviewId = $row['preInterviewId'];
            $competencySubject = $row['favourite_subject'];
            $intScore = (float) $row['intScore'];

            if (!isset($barChartData[$preInterviewId])) {
                // $barChartData[$preInterviewId] = [];

                $barChartData[$preInterviewId] = [
                    'name' => $competencySubject,
                    'labels' => [],
                    'scores' => [],
                    'benchmark' => 5.5
                ];
                $counter = 1;
            }
            $label = '' . $counter++;
            // $label = numberToOrdinal($counter++);
            $barChartData[$preInterviewId]['labels'][] = $label;
            $barChartData[$preInterviewId]['scores'][] = $intScore;
        }
        $finalChartData = array_values($barChartData);
    }
    // var_dump($barChartData);
    // exit();

    $values = array();
    $to_encode = array();

    if ($finalChartData) {
        $values['barChartData'] = $finalChartData;
    } else {
        $values['barChartData'] = [];
    }

    $recommendedJobsQuery = mysqli_query($databaseConnection, $recommendedJobs);

    if (!$recommendedJobsQuery) {
        // Handle query error
        $values['recommendedJobs'] = [];
    } else if (mysqli_num_rows($recommendedJobsQuery) >= 1) {
        $values['recommendedJobs'] = mysqli_fetch_all($recommendedJobsQuery, MYSQLI_ASSOC);
    } else {
        $values['recommendedJobs'] = [];
    }

    $recommendedPracticeQuery = mysqli_query($databaseConnection, $recommendedPractice);

    if (!$recommendedPracticeQuery) {
        // Handle query error
        $values['recommendedPractice'] = [];
    } else if (mysqli_num_rows($recommendedPracticeQuery) >= 1) {
        $values['recommendedPractice'] = mysqli_fetch_all($recommendedPracticeQuery, MYSQLI_ASSOC);
    } else {
        $values['recommendedPractice'] = [];
    }

    // id not in (512,518,513,516,514,515,517,519)
    $locations = "SELECT id,cityName FROM locations where 1  ORDER BY cityName ASC;";
    $locationsResult = mysqli_query($databaseConnection, $locations);
    $values['locations'] = mysqli_fetch_all($locationsResult, MYSQLI_ASSOC);

    $userType = "SELECT 
            CASE 
                WHEN MAX(CASE WHEN cu.placementSupport = 'y' THEN 1 ELSE 0 END) = 1 THEN 'y'
                WHEN MAX(CASE WHEN cu.placementSupport = 'n' THEN 1 ELSE 0 END) = 1 THEN 'n'
                ELSE NULL
            END AS placementSupport
            FROM users u
            LEFT JOIN candidateInterviewMapping cim ON cim.emailId = u.emailId
            LEFT JOIN preInterview_corporate map ON map.preInterviewId = cim.preInterviewId
            LEFT JOIN users cu ON cu.id = map.userId
            WHERE u.id = '$candidateId';";

    $userTypeResult = mysqli_query($databaseConnection, $userType);

    $row = mysqli_fetch_assoc($userTypeResult);
    $values['placementSupport'] = $row ? $row['placementSupport'] : 'NA';

    if ($job_query || $practice_query || $apply_query) {
        $values['candidate'] = $candidate[0];
        $values['jobInterview'] = mysqli_fetch_all($job_query, MYSQLI_ASSOC);
        $values['applyInterview'] = mysqli_fetch_all($apply_query, MYSQLI_ASSOC);
        $values['jobcount'] = mysqli_num_rows($subject_countquery);
        $practice_rows = mysqli_fetch_all($practice_query, MYSQLI_ASSOC);
        // modify each row to find role and subject if it is NULL, then replace it , role and subject is given in cim table if not we can get it from preInterview field in cim
        foreach ($practice_rows as &$rowprac) {
            $preInterviewId2 = null;
            $subjectId = null;
            $subject = null;
            $roleId = null;

            if (empty($rowprac['subject']) || empty($rowprac['role'])) {

                $preInterviewId2 = $rowprac['preInterviewId'];

                if (!empty($preInterviewId2)) {
                    $preInterview = "SELECT GROUP_CONCAT(fs.favourite_subject) AS subject, fs.id as subjectId from scps_transaction st inner join preInterview pr ON pr.id=st.preInterviewId
                    left join favourite_subject fs ON FIND_IN_SET(fs.id, st.subject) > 0
                    where pr.interviewType = 'Practice' and pr.id IN (" . $preInterviewId2 . ") group by fs.favourite_subject";

                    // echo $preInterview;
                    // exit();
                    $preInterviewResult = mysqli_query($databaseConnection, $preInterview);

                    if ($preInterviewResult) {
                        $row1 = mysqli_fetch_assoc($preInterviewResult);
                        if ($row1) {
                            $subject = $row1['subject'];
                            $subjectId = $row1['subjectId'];
                        }
                    }
                }

                if (!empty($subjectId)) {
                    $role_query = "SELECT rr.name as role FROM role_subject left join relavant_role rr on rr.id = role_subject.roleId where subjectId IN ($subjectId)";
                    // echo $role;
                    // exit();
                    $roleResult = mysqli_query($databaseConnection, $role_query);

                    if ($roleResult) {
                        $row2 = mysqli_fetch_assoc($roleResult);
                        if ($row2) {
                            $role = $row2['role'];
                        }
                    }
                }

                // subject
                if (empty($row['subject']) && !empty($subjectId)) {
                    $rowprac['subject'] = $subject;
                }

                // role
                if (empty($row['role']) && !empty($role)) {
                    $rowprac['role'] = $role;
                }

            }




        }
        $values['practiceInterview'] = $practice_rows;
        // $values['practiceInterview'] = mysqli_fetch_all($practice_query, MYSQLI_ASSOC);
        // $values['practiceInterviewchild'] = mysqli_fetch_all($practicechild_query, MYSQLI_ASSOC);
        $values['pracount'] = mysqli_num_rows($practice_query);

        if (mysqli_num_rows($practicechild_query) > 0) {
            while ($row = mysqli_fetch_assoc($practicechild_query)) {
                $fbrId = $row['fr_id'];
                $interviewId = $row['interviewId'];

                $pskillScore = skillWiseScore($databaseConnection, $interviewId);

                $skillsMap = [
                    'Domain Knowledge' => 'domain',
                    'Problem Solving Skill' => 'problemsolving',
                    'Fluency' => 'fluency'
                ];

                $result = [
                    'domain' => '',
                    'problemsolving' => '',
                    'fluency' => ''
                ];

                foreach ($pskillScore as $skill) {
                    $keySkillName = $skill['key_skill_name'];
                    if (isset($skillsMap[$keySkillName])) {
                        $result[$skillsMap[$keySkillName]] = $skill['score'];
                    }
                }

                $row['practiceScore'] = $result;

                //   $row['practiceScore'] = $pskillScore;

                $psqlScoreSpeaking = "SELECT MAX(er.overallRating) AS score FROM expert_review er INNER JOIN questions q ON er.questionId = q.id WHERE FIND_IN_SET('1', q.key_skill_id) > 0 and  er.overallRating != 'videoIssue' and er.interviewId=" . $interviewId . "";
                //    echo   $psqlScore;
                $practiceSpeakingScore_query = mysqli_query($databaseConnection, $psqlScoreSpeaking);

                $practiceSpeakingScore = mysqli_fetch_assoc($practiceSpeakingScore_query);
                if ($practiceSpeakingScore) {
                    $row['practiceSpeakingScore'] = $practiceSpeakingScore['score'];
                } else {
                    $row['practiceSpeakingScore'] = '';
                }

                $values['practiceInterviewchild'][] = $row;
            }
        } else {
            $values['practiceInterviewchild'] = mysqli_fetch_all($practicechild_query, MYSQLI_ASSOC);
        }




        $to_encode = array(
            'result' => 'success',
            'status' => 1,
            'data' => $values,
            'message' => 'data found',
        );
    } else {
        $to_encode = array(
            'result' => 'success',
            'status' => 0,
            'message' => 'no data found',
        );
    }
    echo json_encode($to_encode);
}
else if (isset($_GET['getDashboardData'])) {

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    $userId = $json['userId'];
    $candidateId = $json['candidateId'];

    $values = array();
    $to_encode = array();

    // if (!$candidateId) {
    //     echo json_encode([
    //         'result' => 'error',
    //         'message' => 'Missing candidateId'
    //     ]);
    //     exit;
    // }

    // Fetch candidate info
    $candidate_sql = "select firstName, usertype, emailId from users where id = '" . $candidateId . "'";
    $candidate_query = mysqli_query($databaseConnection, $candidate_sql);
    $candidate = mysqli_fetch_all($candidate_query, MYSQLI_ASSOC);
    $candidateEmailId = $candidate[0]['emailId'];
     $values['candidate'] = $candidate[0];
    //  exit();

    // Fetch locations -  id not in (512,518,513,516,514,515,517,519)
    $locations = "SELECT id,cityName FROM locations where 1  ORDER BY cityName ASC;";
    $locationsResult = mysqli_query($databaseConnection, $locations);
    $values['locations'] = mysqli_fetch_all($locationsResult, MYSQLI_ASSOC);

    // Determine placement support
    $userType = "SELECT 
            CASE 
                WHEN MAX(CASE WHEN cu.usertype = 'corporate' THEN 1 ELSE 0 END) = 1 THEN 'n'
                WHEN MAX(CASE WHEN cu.placementSupport = 'n' THEN 1 ELSE 0 END) = 1 THEN 'n'
                ELSE 'y'
            END AS placementSupport
            FROM users u
            LEFT JOIN candidateInterviewMapping cim ON cim.emailId = u.emailId
            LEFT JOIN preInterview_corporate map ON map.preInterviewId = cim.preInterviewId
            LEFT JOIN users cu ON cu.id = map.userId
            WHERE u.id = '$candidateId';";
           

    $userTypeResult = mysqli_query($databaseConnection, $userType);
    $row = mysqli_fetch_assoc($userTypeResult);
    $values['placementSupport'] = $row ? $row['placementSupport'] : 'NA';

    $to_encode = array(
        'result' => 'success',
        'status' => 1,
        'data' => $values,
        'message' => 'data found',
    );
    // $to_encode = array(
    //     'result' => 'success',
    //     'status' => 0,
    //     'message' => 'no data found',
    // );
    echo json_encode($to_encode);
}
else if (isset($_GET['getDashboardPracticeData'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    $userId = $json['userId'];
    $candidateId = $json['candidateId'];
    $filterQuery = '';

    $values = array();
    $to_encode = array();
    $finalChartData = null;

    $candidate_sql = "select firstName, usertype, emailId from users where id = '" . $candidateId . "'";
    $candidate_query = mysqli_query($databaseConnection, $candidate_sql);
    $candidate = mysqli_fetch_all($candidate_query, MYSQLI_ASSOC);
    $candidateEmailId = $candidate[0]['emailId'];
    //  exit();

    if ($candidate[0]['usertype'] == 'corporate') {
        $filterQuery .= " AND fr.review_status IN (2) AND i.companyId NOT IN (SELECT company_id FROM preInterview WHERE userId NOT IN (" . $json['userId'] . ")) ";
    } else {
        $filterQuery .= " AND fr.review_status IN (2,1,0,3,-3,-4,-2) ";
    }

    $psql = "SELECT
            cim.*,
            rr.name AS role,
            GROUP_CONCAT(fs.favourite_subject) AS subject,
            pr.interviewName AS product,
            fr.intScore
        FROM
            candidateInterviewMapping cim
        INNER JOIN (
            SELECT
                cim_sub.preInterviewId,
                MAX(cim_sub.id) AS max_id
            FROM candidateInterviewMapping cim_sub
            INNER JOIN preInterview pr_sub
                ON pr_sub.id = cim_sub.preInterviewId
            WHERE
                pr_sub.interviewType = 'Practice'
                AND cim_sub.candidateId = $candidateId
            GROUP BY cim_sub.preInterviewId
        ) latest_cim
        ON latest_cim.max_id = cim.id

        LEFT JOIN preInterview pr ON pr.id = cim.preInterviewId
        LEFT JOIN relavant_role rr ON rr.id = cim.role
        LEFT JOIN favourite_subject fs ON FIND_IN_SET(fs.id, cim.subject) > 0

        LEFT JOIN (
            SELECT candidateId, preInterviewId, MAX(intScore) AS maxScore
            FROM feedback_request
            GROUP BY candidateId, preInterviewId
        ) fr_max
        ON fr_max.candidateId = cim.candidateId
        AND fr_max.preInterviewId = cim.preInterviewId
        LEFT JOIN feedback_request fr
        ON fr.candidateId = fr_max.candidateId
        AND fr.preInterviewId = fr_max.preInterviewId
        AND fr.intScore = fr_max.maxScore
        GROUP BY
            cim.id
        ORDER BY
            cim.id DESC;";

    $practice_query = mysqli_query($databaseConnection, $psql);
    $practice_rows = mysqli_fetch_all($practice_query, MYSQLI_ASSOC);


        $psqlchild = "SELECT
            fr.reportpdf1,
            fr.review_status, 
            fr.reasonOfRejection,
            isc.scheduleTime,
            isc.firstScheduleDate,
            cit.completion_status,
            fr.id AS fr_id,
            m.mergeId,
            m.candidateId,
            m.interviewId,
            i.preInterviewId,
            i.last_activity_at,
            m.interviewSessionId,
            CONCAT('/review?i=', m.interviewId, '&c=', m.candidateId, '&s=', m.interviewSessionId) AS url, 
            CASE 
                WHEN fr.suitability = 'Do not meet' THEN 'Below Industry Standard'
                WHEN fr.suitability = 'Must meet' THEN 'At par with Industry Standard'
                WHEN fr.suitability = 'Recommended to meet' THEN 'Close to Industry Standard'
                ELSE fr.suitability
            END AS suitability,
            pr.interviewType,
            pr.interviewName,
            pr.id,
            (
            SELECT status 
            FROM payment_transaction 
            WHERE user_id = m.candidateId
                AND subscriptionType = 'practice'
            ORDER BY
                CASE WHEN status = 'PAID' THEN 0 ELSE 1 END, 
                status
            LIMIT 1
            ) AS payment_status,
            ms.malpractice_stats
        FROM mergedVideos m
        INNER JOIN interview i ON m.interviewId = i.id 
        INNER JOIN feedback_request fr ON fr.candidateId = m.candidateId AND fr.interviewSessionId = m.interviewSessionId 
        JOIN interviewSchedule isc ON isc.candidate_id = m.candidateId and isc.interviewId=m.interviewId 
        LEFT JOIN candidate_interview_transection cit ON cit.interviewId = m.interviewId 
        INNER JOIN preInterview pr ON pr.id = i.preInterviewId
        LEFT JOIN (
            SELECT
                t.interviewSessionId,
                JSON_ARRAYAGG(
                    JSON_OBJECT(
                        'malpracticeValue', t.malpracticeValue,
                        'interviewName', t.interviewName,
                        'interviewSessionId', t.interviewSessionId,
                        'count', t.cnt
                    )
                ) AS malpractice_stats
            FROM (
                SELECT
                    mv.interviewSessionId,
                    mv.malpracticeValue,
                    prv.interviewName,
                    COUNT(*) AS cnt
                FROM mergedVideos mv
                JOIN AnswerTranscription at
                    ON at.mergeId = mv.mergeId
                AND at.ansText IS NOT NULL
                JOIN feedback_request frv
                    ON frv.interviewSessionId = mv.interviewSessionId
                JOIN preInterview prv
                    ON prv.id = frv.preInterviewId
                WHERE mv.malpracticeValue IS NOT NULL
                GROUP BY
                    mv.interviewSessionId,
                    mv.malpracticeValue,
                    prv.interviewName
            ) t
            GROUP BY t.interviewSessionId
        ) ms
        ON ms.interviewSessionId = m.interviewSessionId
        WHERE pr.interviewType='Practice' AND m.candidateId = " . $candidateId . "
        " . $filterQuery . "
        GROUP BY m.interviewId, m.interviewSessionId
        ORDER BY m.interviewSessionId DESC";


    $practicechild_query = mysqli_query($databaseConnection, $psqlchild);

    $recommendedPractice = "SELECT
            pr.id,
            pr.interviewName AS `name`,
            pr.targetAudience AS targetAudience,
            pr.duration AS duration,
            pr.categoryType AS categoryType,
            pr.interviewLevel AS interviewLevel,
            pr.id AS preInterviewId,
            pr.YOE AS eligibility
        FROM preInterview pr
        WHERE 1
            AND pr.interviewType= 'Practice'
            AND pr.practiceType = 'freetrial'
        GROUP BY
            pr.id
        ORDER BY
            pr.id DESC
        LIMIT 15";
    
    // barChartData
    $sql = "SELECT fr.id,i.preInterviewId, fr.intScore, fs.favourite_subject 
            FROM feedback_request fr
            LEFT JOIN interview i ON i.id = fr.interviewId
            LEFT JOIN preInterview pr ON pr.id = i.preInterviewId
            LEFT JOIN scps_transaction scps ON scps.preInterviewId = pr.id
            LEFT JOIN favourite_subject fs ON fs.id = scps.subject 
            WHERE 1
            AND pr.interviewType  = 'practice'
            AND fr.intScore IS NOT NULL 
            AND fr.review_status IN('2','3')
            AND i.preInterviewId IS NOT NULL
            AND fr.candidateId = '$candidateId'
            group by fr.interviewSessionId
            ORDER BY fr.id ASC";
    $result = mysqli_query($databaseConnection, $sql);
    $barChartData = [];
    if ($result) {
        $counter = 1;
        while ($row = mysqli_fetch_assoc($result)) {
            $preInterviewId = $row['preInterviewId'];
            $competencySubject = $row['favourite_subject'];
            $intScore = (float) $row['intScore'];

            if (!isset($barChartData[$preInterviewId])) {
                $barChartData[$preInterviewId] = [
                    'name' => $competencySubject,
                    'labels' => [],
                    'scores' => [],
                    'benchmark' => 5.5
                ];
                $counter = 1;
            }
            $label = '' . $counter++;
            $barChartData[$preInterviewId]['labels'][] = $label;
            $barChartData[$preInterviewId]['scores'][] = $intScore;
        }
        $finalChartData = array_values($barChartData);
    }

    // var_dump($barChartData);
    // exit();


    if ($finalChartData) {
        $values['barChartData'] = $finalChartData;
    } else {
        $values['barChartData'] = [];
    }

    $recommendedPracticeQuery = mysqli_query($databaseConnection, $recommendedPractice);

    if (!$recommendedPracticeQuery) {
        // Handle query error
        $values['recommendedPractice'] = [];
    } else if (mysqli_num_rows($recommendedPracticeQuery) >= 1) {
        $values['recommendedPractice'] = mysqli_fetch_all($recommendedPracticeQuery, MYSQLI_ASSOC);
    } else {
        $values['recommendedPractice'] = [];
    }

        // modify each row to find role and subject if it is NULL, then replace it , role and subject is given in cim table if not we can get it from preInterview field in cim

        $values['candidate'] = $candidate[0];

    if (!empty($practice_rows)) {

        $missingPreInterviewIds = [];

        foreach ($practice_rows as $row) {
            if (
                (empty($row['subject']) || empty($row['role'])) &&
                !empty($row['preInterviewId'])
            ) {
                $missingPreInterviewIds[] = $row['preInterviewId'];
            }
        }

        $missingPreInterviewIds = array_unique($missingPreInterviewIds);

        $subjectMap = [];

        if (!empty($missingPreInterviewIds)) {
            $ids = implode(',', $missingPreInterviewIds);

            $subjectSql = "
                SELECT
                    pr.id AS preInterviewId,
                    GROUP_CONCAT(fs.favourite_subject) AS subject,
                    GROUP_CONCAT(fs.id) AS subjectIds
                FROM scps_transaction st
                INNER JOIN preInterview pr ON pr.id = st.preInterviewId
                LEFT JOIN favourite_subject fs
                    ON FIND_IN_SET(fs.id, st.subject) > 0
                WHERE pr.interviewType = 'Practice'
                AND pr.id IN ($ids)
                GROUP BY pr.id
            ";

            $subjectResult = mysqli_query($databaseConnection, $subjectSql);

            while ($row = mysqli_fetch_assoc($subjectResult)) {
                $subjectMap[$row['preInterviewId']] = $row;
            }
        }



        $roleMap = [];

        if (!empty($subjectMap)) {
            $allSubjectIds = [];

            foreach ($subjectMap as $data) {
                if (!empty($data['subjectIds'])) {
                    $allSubjectIds = array_merge(
                        $allSubjectIds,
                        explode(',', $data['subjectIds'])
                    );
                }
            }

            $allSubjectIds = array_unique($allSubjectIds);

            if (!empty($allSubjectIds)) {
                $ids = implode(',', $allSubjectIds);

                $roleSql = "
                    SELECT
                        rs.subjectId,
                        rr.name AS role
                    FROM role_subject rs
                    INNER JOIN relavant_role rr
                        ON rr.id = rs.roleId
                    WHERE rs.subjectId IN ($ids)
                ";

                $roleResult = mysqli_query($databaseConnection, $roleSql);

                while ($row = mysqli_fetch_assoc($roleResult)) {
                    $roleMap[$row['subjectId']] = $row['role'];
                }
            }
        }


        foreach ($practice_rows as &$rowprac) {

            if (empty($rowprac['subject']) || empty($rowprac['role'])) {

                $pid = $rowprac['preInterviewId'];

                if (isset($subjectMap[$pid])) {

                    if (empty($rowprac['subject'])) {
                        $rowprac['subject'] = $subjectMap[$pid]['subject'];
                    }

                    if (empty($rowprac['role'])) {
                        $subjectIds = explode(',', $subjectMap[$pid]['subjectIds']);
                        foreach ($subjectIds as $sid) {
                            if (isset($roleMap[$sid])) {
                                $rowprac['role'] = $roleMap[$sid];
                                break;
                            }
                        }
                    }
                }
            }
        }
        unset($rowprac);

        $values['practiceInterview'] = $practice_rows;
        $values['pracount'] = count($practice_rows);

        if (mysqli_num_rows($practicechild_query) > 0) {
            while ($row = mysqli_fetch_assoc($practicechild_query)) {
                $fbrId = $row['fr_id'];
                $interviewId = $row['interviewId'];

                $pskillScore = skillWiseScore($databaseConnection, $interviewId);

                $skillsMap = [
                    'Domain Knowledge' => 'domain',
                    'Problem Solving Skill' => 'problemsolving',
                    'Fluency' => 'fluency'
                ];

                $result = [
                    'domain' => '',
                    'problemsolving' => '',
                    'fluency' => ''
                ];

                foreach ($pskillScore as $skill) {
                    $keySkillName = $skill['key_skill_name'];
                    if (isset($skillsMap[$keySkillName])) {
                        $result[$skillsMap[$keySkillName]] = $skill['score'];
                    }
                }

                $row['practiceScore'] = $result;

                //   $row['practiceScore'] = $pskillScore;

                $psqlScoreSpeaking = "SELECT MAX(er.overallRating) AS score FROM expert_review er INNER JOIN questions q ON er.questionId = q.id WHERE FIND_IN_SET('1', q.key_skill_id) > 0 and  er.overallRating != 'videoIssue' and er.interviewId=" . $interviewId . "";
                //    echo   $psqlScore;
                $practiceSpeakingScore_query = mysqli_query($databaseConnection, $psqlScoreSpeaking);

                $practiceSpeakingScore = mysqli_fetch_assoc($practiceSpeakingScore_query);
                if ($practiceSpeakingScore) {
                    $row['practiceSpeakingScore'] = $practiceSpeakingScore['score'];
                } else {
                    $row['practiceSpeakingScore'] = '';
                }

                $values['practiceInterviewchild'][] = $row;
            }
        } else {
            $values['practiceInterviewchild'] = mysqli_fetch_all($practicechild_query, MYSQLI_ASSOC);
        }

        $to_encode = array(
            'result' => 'success',
            'status' => 1,
            'data' => $values,
            'message' => 'data found',
        );
    } else {
        $to_encode = array(
            'result' => 'success',
            'status' => 0,
            'message' => 'no data found',
        );
    }
    echo json_encode($to_encode);
}
else if (isset($_GET['getDashboardJobData'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    $userId = $json['userId'];
    $candidateId = $json['candidateId'];
    $filterQuery = '';

    $candidate_sql = "select firstName, usertype, emailId from users where id = '" . $candidateId . "'";
    $candidate_query = mysqli_query($databaseConnection, $candidate_sql);
    $candidate = mysqli_fetch_all($candidate_query, MYSQLI_ASSOC);
    $candidateEmailId = $candidate[0]['emailId'];
    //  exit();

    $rasOnlyFilter = " AND pr.serviceType = 'RAS' ";
    $isRASCandidate = false;

    $rasCandidateSql = "SELECT 1
        FROM feedback_request fr
        INNER JOIN preInterview pr ON pr.id = fr.preInterviewId
        WHERE fr.candidateId = " . intval($candidateId) . "
          AND pr.interviewType = 'job'
          AND pr.serviceType = 'RAS'
        LIMIT 1";
    $rasCandidateQuery = mysqli_query($databaseConnection, $rasCandidateSql);
    if ($rasCandidateQuery && mysqli_num_rows($rasCandidateQuery) > 0) {
        $isRASCandidate = true;
    }

    if ($candidate[0]['usertype'] == 'corporate') {
        $filterQuery .= " AND fr.review_status IN (2) AND i.companyId NOT IN (SELECT company_id FROM preInterview WHERE userId NOT IN (" . $json['userId'] . ")) ";
    } else {
        $filterQuery .= " AND fr.review_status IN (2,1,0,-3,-4,-2) ";
    }


    $sql = "SELECT  t.*,
        CASE 
            WHEN t.publish = 'Y' AND t.interviewStatus = 'Active' THEN 'Open'
            WHEN t.publish = 'Y' AND t.interviewStatus = 'Inactive' THEN 'Closed'
            WHEN t.publish = 'C' AND t.interviewStatus = 'Inactive' THEN 'Closed'
            WHEN t.publish = 'C' AND t.interviewStatus = 'Active' THEN 'Closed'
            WHEN t.publish = 'L' AND t.interviewStatus = 'Active' THEN 'Open'
            WHEN t.publish = 'L' AND t.interviewStatus = 'Inactive' THEN 'Closed'
            WHEN t.publish = 'N' AND t.interviewStatus = 'Active' THEN 'Open'
            WHEN t.publish = 'N' AND t.interviewStatus = 'Inactive' THEN 'Closed'
            ELSE 'Open' 
        END AS jobStatus,
        CASE 
           WHEN t.candidateStatus IS NULL AND (t.fr_id IS NOT NULL AND (t.review_status = 2)) THEN 'Assessment Completed' 
           WHEN ((t.fr_id IS NOT NULL AND t.completion_status IS NOT NULL AND t.review_status IN (0,1)) OR (t.fr_id IS NOT NULL AND t.completion_status IS NOT NULL AND t.review_status = -2)) THEN 'Assessment Awaited' 
           WHEN t.candidateStatus IS NULL AND (
               (t.fr_id IS NOT NULL AND (t.review_status = -4 AND t.reasonOfRejection = 'duplicateAttempt')) OR 
               (t.fr_id IS NOT NULL AND (t.review_status = -4 AND t.reasonOfRejection = 'limitedFreeAssessment')) OR 
               (t.fr_id IS NOT NULL AND (t.review_status = -4 AND t.reasonOfRejection = 'unauthorizedUser')) OR 
               (t.fr_id IS NOT NULL AND (t.review_status = -4 AND t.reasonOfRejection = 'incompleteInterview')) OR 
               (t.fr_id IS NOT NULL AND (t.review_status = -4 AND t.reasonOfRejection = 'technicalIssue')) OR 
               (t.fr_id IS NOT NULL AND (t.review_status = -4 AND t.reasonOfRejection NOT IN ('technicalIssue', 'incompleteInterview')))
           ) THEN 'Assessment Rejected' 
           WHEN t.candidateStatus IS NULL AND (t.fr_id IS NULL AND t.scheduleTime = 1) THEN 'Future Scheduled' 
           WHEN t.candidateStatus IS NULL AND (
               t.fr_id IS NULL AND 
               (t.scheduleTime != t.firstScheduleDate) AND 
               (DATEDIFF(t.scheduleTime, NOW())) >= 1
           ) THEN 'Re-Scheduled' 
           WHEN t.candidateStatus IS NULL AND t.scheduleTime IS NULL THEN 'Applied' 
           WHEN (t.fr_id IS NULL AND t.review_status IS NULL) THEN 'Not Attempted' 
           ELSE t.candidateStatus 
        END AS newcandidStatus, 
        CASE 
            WHEN (t.pendingInterviews = 'NR' ) THEN 'NA'
            WHEN (t.fr_id IS NOT NULL AND(t.review_status = 2) ) THEN 'Assessment Completed'
            WHEN ((t.fr_id IS NOT NULL OR t.completion_status IS NOT NULL) AND t.review_status IN (0, 1)) THEN 'Assessment in Progress'
            WHEN ((t.fr_id IS NOT NULL OR t.completion_status IS NOT NULL) AND t.review_status = -2) THEN 'Internal Review'
            WHEN (t.fr_id IS NOT NULL AND(t.review_status = -4 AND t.reasonOfRejection = 'incompleteInterview')) THEN 'Incomplete'
            WHEN (t.fr_id IS NOT NULL AND(t.review_status = -4 AND t.reasonOfRejection = 'technicalIssue')) THEN 'Technical Issue'
            WHEN (t.fr_id IS NOT NULL AND(t.review_status = -4 AND t.reasonOfRejection NOT IN ('technicalIssue','incompleteInterview'))) THEN 'Rejected'
            WHEN (t.fr_id IS NOT NULL AND(t.review_status = -4 AND t.reasonOfRejection = 'duplicateAttempt')) THEN 'duplicateAttempt'
            WHEN (t.fr_id IS NOT NULL AND(t.review_status = -4 AND t.reasonOfRejection = 'limitedFreeAssessment')) THEN 'limitedFreeAssessment'
            WHEN (t.fr_id IS NOT NULL AND(t.review_status = -4 AND t.reasonOfRejection = 'unauthorizedUser')) THEN 'unauthorizedUser'
            WHEN (t.fr_id IS NULL AND(t.scheduleTime != t.firstScheduleDate) AND(DATEDIFF(t.scheduleTime, NOW())) >= 1) THEN 'Re-Scheduled'
            WHEN (t.fr_id IS NULL AND t.scheduleTime = 1) THEN 'Future Scheduled'
            WHEN (t.fr_id IS NULL AND(t.scheduleTime = t.firstScheduleDate) AND(DATEDIFF(t.scheduleTime, NOW())) >= 1) THEN 'Future Scheduled'
            WHEN (t.fr_id IS NULL AND t.scheduleTime is not null and DATEDIFF(t.scheduleTime, NOW()) < 1 ) THEN 'Missed Scheduled' 
            WHEN (t.fr_id IS NULL AND t.review_status IS NULL AND t.scheduleTime IS NOT NULL) THEN 'Scheduled'
            WHEN (t.fr_id IS NULL AND t.review_status IS NULL AND t.scheduleTime IS NULL) THEN 'Job Invited'
        END AS interviewStatus,
        COALESCE(t.interviewName,(select name from aspiration_company where id= t.company_id)) as interviewName,
        (
            SELECT name from aspiration_company where id= t.company_id 
        ) as hiring_company,
        (
            SELECT 
                JSON_ARRAYAGG(
                    JSON_OBJECT(
                        'malpracticeValue', mt.malpracticeValue,
                        'interviewName', mt.interviewName,
                        'interviewSessionId', mt.interviewSessionId,
                        'count', mt.cnt
                    )
                )
            FROM (
                SELECT 
                    mv.candidateId,
                    mv.malpracticeValue,
                    pr.interviewName,
                    mv.interviewSessionId,
                    COUNT(*) AS cnt
                FROM feedback_request fr
                JOIN mergedVideos mv ON fr.interviewSessionId = mv.interviewSessionId
                JOIN AnswerTranscription at ON mv.mergeId = at.mergeId
                JOIN preInterview pr ON pr.id = fr.preInterviewId
                WHERE at.ansText IS NOT NULL
                AND mv.malpracticeValue IS NOT NULL
                AND mv.interviewSessionId = t.interviewSessionId
                    GROUP BY mv.malpracticeValue
            ) mt
        ) as malpractice_stats
        FROM (
                SELECT 
                m.interviewId AS interviewId, 
                fr.review_status, 
                fr.reasonOfRejection,
                isc.scheduleTime,
                isc.firstScheduleDate,
                cit.completion_status,
                fr.id as fr_id,
                m.candidateId, 
                pr.interviewName,
                pr.pendingInterviews,
                pr.company_id,
                m.interviewSessionId, 
                CONCAT('/review?i=', m.interviewId, '&c=', m.candidateId, '&s=', m.interviewSessionId) AS url,
                CONCAT('/job?p=',i.preInterviewId) AS jobUrl,  
                fr.suitability, 
                i.preInterviewId,
                isc.candidateStatus,
                isc.id as iscId,
                pr.publish,
                pr.interviewStatus,
                pr.serviceType,
                (
                    SELECT status 
                    FROM payment_transaction 
                    WHERE user_id = m.candidateId
                        AND interview_id =  m.interviewId
                        AND subscriptionType = 'job'
                    ORDER BY
                        CASE WHEN status = 'PAID' THEN 0 ELSE 1 END, 
                        status
                    LIMIT 1
                ) AS payment_status
                FROM mergedVideos m 
                INNER JOIN interview i ON m.interviewId = i.id 
                INNER JOIN feedback_request fr ON fr.candidateId = m.candidateId AND fr.interviewSessionId = m.interviewSessionId 
                JOIN interviewSchedule isc ON isc.candidate_id = m.candidateId and isc.interviewId=m.interviewId 
                LEFT JOIN candidate_interview_transection cit ON cit.interviewId = m.interviewId 
                left join preInterview pr on pr.id = i.preInterviewId
                WHERE pr.interviewType='job' AND m.candidateId =  " . $candidateId . " AND m.interviewSessionId IS NOT NULL 
                " . $rasOnlyFilter . "
                " . $filterQuery . "
                GROUP BY m.interviewSessionId 
                ORDER BY m.interviewSessionId DESC
            ) as t;
        ";

    // echo $sql; 
    // exit();
    $job_query = mysqli_query($databaseConnection, $sql);


    $apply_sql = "
        SELECT  t.*,
        CASE 
            WHEN t.publish = 'Y' AND t.interviewStatus = 'Active' THEN 'Open'
            WHEN t.publish = 'Y' AND t.interviewStatus = 'Inactive' THEN 'Closed'
            WHEN t.publish = 'C' AND t.interviewStatus = 'Inactive' THEN 'Closed'
            WHEN t.publish = 'C' AND t.interviewStatus = 'Active' THEN 'Closed'
            WHEN t.publish = 'L' AND t.interviewStatus = 'Active' THEN 'Open'
            WHEN t.publish = 'L' AND t.interviewStatus = 'Inactive' THEN 'Closed'
            WHEN t.publish = 'N' AND t.interviewStatus = 'Active' THEN 'Open'
            WHEN t.publish = 'N' AND t.interviewStatus = 'Inactive' THEN 'Closed'
            ELSE 'Open' 
        END AS jobStatus,
        CASE 
        WHEN t.candidateStatus IS NULL AND (t.fr_id IS NOT NULL AND (t.review_status = 2)) THEN 'Assessment Completed' 
        WHEN ((t.fr_id IS NOT NULL AND t.completion_status IS NOT NULL AND t.review_status IN (0,1)) OR (t.fr_id IS NOT NULL AND t.completion_status IS NOT NULL AND t.review_status = -2)) THEN 'Assessment Awaited' 
        WHEN t.candidateStatus IS NULL AND (
            (t.fr_id IS NOT NULL AND (t.review_status = -4 AND t.reasonOfRejection = 'duplicateAttempt')) OR 
            (t.fr_id IS NOT NULL AND (t.review_status = -4 AND t.reasonOfRejection = 'limitedFreeAssessment')) OR 
            (t.fr_id IS NOT NULL AND (t.review_status = -4 AND t.reasonOfRejection = 'unauthorizedUser')) OR 
            (t.fr_id IS NOT NULL AND (t.review_status = -4 AND t.reasonOfRejection = 'incompleteInterview')) OR 
            (t.fr_id IS NOT NULL AND (t.review_status = -4 AND t.reasonOfRejection = 'technicalIssue')) OR 
            (t.fr_id IS NOT NULL AND (t.review_status = -4 AND t.reasonOfRejection NOT IN ('technicalIssue', 'incompleteInterview')))
        ) THEN 'Assessment Rejected' 
        WHEN t.candidateStatus IS NULL AND (t.fr_id IS NULL AND t.scheduleTime = 1) THEN 'Future Scheduled' 
        WHEN t.candidateStatus IS NULL AND (
            t.fr_id IS NULL AND 
            (t.scheduleTime != t.firstScheduleDate) AND 
            (DATEDIFF(t.scheduleTime, NOW())) >= 1
        ) THEN 'Re-Scheduled' 
        WHEN (t.fr_id IS NULL AND t.review_status IS NULL AND t.candidateStatus in('applied')) THEN 'Submitted'
        WHEN t.candidateStatus IS NULL AND t.scheduleTime IS NULL THEN 'Submitted'
         WHEN t.candidateStatus IS NULL THEN 'Submitted' 
        ELSE t.candidateStatus 
        END AS newcandidStatus, 
        CASE 
            WHEN (t.pendingInterviews = 'NR' ) THEN 'NA'
            WHEN (t.fr_id IS NOT NULL AND(t.review_status = 2) ) THEN 'Assessment Completed'
            WHEN ((t.fr_id IS NOT NULL OR t.completion_status IS NOT NULL) AND t.review_status IN (0, 1)) THEN 'Assessment in Progress'
            WHEN ((t.fr_id IS NOT NULL OR t.completion_status IS NOT NULL) AND t.review_status = -2) THEN 'Internal Review'
            WHEN (t.fr_id IS NOT NULL AND(t.review_status = -4 AND t.reasonOfRejection = 'incompleteInterview')) THEN 'Incomplete'
            WHEN (t.fr_id IS NOT NULL AND(t.review_status = -4 AND t.reasonOfRejection = 'technicalIssue')) THEN 'Technical Issue'
            WHEN (t.fr_id IS NOT NULL AND(t.review_status = -4 AND t.reasonOfRejection NOT IN ('technicalIssue','incompleteInterview'))) THEN 'Rejected'
            WHEN (t.fr_id IS NOT NULL AND(t.review_status = -4 AND t.reasonOfRejection = 'duplicateAttempt')) THEN 'duplicateAttempt'
            WHEN (t.fr_id IS NOT NULL AND(t.review_status = -4 AND t.reasonOfRejection = 'limitedFreeAssessment')) THEN 'limitedFreeAssessment'
            WHEN (t.fr_id IS NOT NULL AND(t.review_status = -4 AND t.reasonOfRejection = 'unauthorizedUser')) THEN 'unauthorizedUser'
            WHEN (t.fr_id IS NULL AND(t.scheduleTime != t.firstScheduleDate) AND(DATEDIFF(t.scheduleTime, NOW())) >= 1) THEN 'Re-Scheduled'
            WHEN (t.fr_id IS NULL AND t.scheduleTime = 1) THEN 'Future Scheduled'
            WHEN (t.fr_id IS NULL AND(t.scheduleTime = t.firstScheduleDate) AND(DATEDIFF(t.scheduleTime, NOW())) >= 1) THEN 'Future Scheduled'
            WHEN (t.fr_id IS NULL AND t.scheduleTime is not null and DATEDIFF(t.scheduleTime, NOW()) < 1 ) THEN 'Missed Scheduled'
            WHEN (t.fr_id IS NULL AND t.review_status IS NULL AND t.scheduleTime IS NOT NULL) THEN 'Scheduled'
            WHEN (t.fr_id IS NULL AND t.review_status IS NULL AND t.scheduleTime IS NULL) THEN 'Job Invited'
        END AS interviewStatus,
        COALESCE(t.interviewName,(select name from aspiration_company where id= t.company_id)) as interviewName,(select name from aspiration_company where id= t.company_id) as hiring_company
        FROM (
        select 
            isc.interviewId AS interviewId,
            null as review_status,
            null as reasonOfRejection,
            isc.scheduleTime,
            isc.firstScheduleDate,
            null as completion_status,
            null as fr_id,
            isc.candidate_id as candidateId,
            pr.interviewName,
            pr.company_id,
            pr.pendingInterviews,
            null as interviewSessionId,
            null AS url,
            CONCAT('/job?p=', isc.preInterviewId) AS jobUrl,
            null as suitability,
            isc.preInterviewId,
            isc.candidateStatus,
            isc.id as iscId,
            pr.publish,
            pr.interviewStatus,
            pr.serviceType,
            null AS payment_status
        FROM interviewSchedule isc
        LEFT JOIN preInterview pr on pr.id = isc.preInterviewId
        WHERE
            pr.interviewType='job'
            " . $rasOnlyFilter . "
            and isc.candidate_id =  " . $candidateId . "
            and isc.submissionFlag IN('Y','WA')
            and isc.candidateStatus <> 'Error'
            and isc.interviewId is null
        GROUP BY
            isc.id
        ORDER BY
            isc.id DESC) as t;";

    // echo $apply_sql; 
    // exit();
    $apply_query = mysqli_query($databaseConnection, $apply_sql);

    $sqlcount = " select m.mergeId 
        FROM  mergedVideos m 
        INNER JOIN   
            interview i ON m.interviewId = i.id  
        INNER JOIN 
            feedback_request fr ON fr.candidateId = m.candidateId AND fr.interviewSessionId = m.interviewSessionId 
        JOIN 
            interviewSchedule isc ON isc.candidate_id = m.candidateId and isc.interviewId=m.interviewId 
        LEFT JOIN 
            candidate_interview_transection cit ON cit.interviewId = m.interviewId 
        left join preInterview pr on pr.id = i.preInterviewId
        WHERE 
            pr.interviewType='job'
            " . $rasOnlyFilter . "
            AND m.candidateId =  " . $candidateId . "
            AND m.interviewSessionId IS NOT NULL 
            " . $filterQuery . "
        GROUP BY 
        m.interviewSessionId ;";
    $subject_countquery = mysqli_query($databaseConnection, $sqlcount);

    $recommendedJobs = "SELECT
            c.id,
            CASE
                WHEN c.id = 0 OR c.id IS NULL THEN pr.interviewName
                WHEN pr.interviewName IS NOT NULL THEN pr.interviewName
                ELSE c.name
            END AS `name`,
            c.name as company,
            pr.productId AS productId,
            st.sector AS sectorId,
            pr.targetAudience AS targetAudience,
            pr.duration AS duration,
            pr.categoryType AS categoryType,
            pr.interviewLevel AS interviewLevel,
            st.assessmenttype AS assessmenttype,
            pr.id AS preInterviewId,
            CASE
                WHEN pr.interviewExpireDate >= NOW() OR pr.interviewExpireDate IS NULL THEN 'Active'
                ELSE 'Inactive'
            END AS status,
            CASE
                WHEN st.preInterviewId IS NULL AND pr.jobCategory = 'interview' THEN 'dummy'
                ELSE 'real'
            END AS intCat,
            pp.fieldValue AS jobWorkExperience,
            pp2.fieldValue AS jobLocation,
            loc.cityName AS jobLocationName
        FROM preInterview pr
        LEFT JOIN scps_transaction st ON st.preInterviewId = pr.id
        LEFT JOIN aspiration_company c ON st.company = c.id
        LEFT JOIN sector s ON s.id = st.sector
        LEFT JOIN profilePreferences pp ON pr.id = pp.preInterviewId AND pp.fieldName = 'workExperience'
        LEFT JOIN profilePreferences pp2 ON pr.id = pp2.preInterviewId AND pp2.fieldName = 'currentLocation'
        LEFT JOIN locations loc ON loc.id = pp2.fieldValue
        WHERE 1
            AND pr.interviewExpireDate >= NOW()
            AND pr.publish IN ('Y', 'C')
            AND pr.serviceType != 'IAS'
            AND pr.id > 758
        GROUP BY
            pr.id
        ORDER BY
            pr.interviewExpireDate DESC,
            pr.id DESC
        LIMIT 50;
    ";

    $values = array();
    $to_encode = array();


    $recommendedJobsQuery = mysqli_query($databaseConnection, $recommendedJobs);

    if (!$recommendedJobsQuery) {
        // Handle query error
        $values['recommendedJobs'] = [];
    } else if (mysqli_num_rows($recommendedJobsQuery) >= 1) {
        $values['recommendedJobs'] = mysqli_fetch_all($recommendedJobsQuery, MYSQLI_ASSOC);
    } else {
        $values['recommendedJobs'] = [];
    }

    // id not in (512,518,513,516,514,515,517,519)
    // $locations = "SELECT id,cityName FROM locations where 1  ORDER BY cityName ASC;";
    // $locationsResult = mysqli_query($databaseConnection, $locations);
    // $values['locations'] = mysqli_fetch_all($locationsResult, MYSQLI_ASSOC);

    // $userType = "SELECT 
    //         CASE 
    //             WHEN MAX(CASE WHEN cu.placementSupport = 'y' THEN 1 ELSE 0 END) = 1 THEN 'y'
    //             WHEN MAX(CASE WHEN cu.placementSupport = 'n' THEN 1 ELSE 0 END) = 1 THEN 'n'
    //             ELSE NULL
    //         END AS placementSupport
    //         FROM users u
    //         LEFT JOIN candidateInterviewMapping cim ON cim.emailId = u.emailId
    //         LEFT JOIN preInterview_corporate map ON map.preInterviewId = cim.preInterviewId
    //         LEFT JOIN users cu ON cu.id = map.userId
    //         WHERE u.id = '$candidateId';";

    // $userTypeResult = mysqli_query($databaseConnection, $userType);

    // $row = mysqli_fetch_assoc($userTypeResult);
    // $values['placementSupport'] = $row ? $row['placementSupport'] : 'NA';

    if ($job_query ||  $apply_query) {
        $values['candidate'] = $candidate[0];
        $values['jobInterview'] = mysqli_fetch_all($job_query, MYSQLI_ASSOC);
        $values['applyInterview'] = mysqli_fetch_all($apply_query, MYSQLI_ASSOC);
        $values['jobcount'] = mysqli_num_rows($subject_countquery);
        $values['rasCandidate'] = $isRASCandidate;
 
        $to_encode = array(
            'result' => 'success',
            'status' => 1,
            'data' => $values,
            'message' => 'data found',
        );
    } else {
        $to_encode = array(
            'result' => 'success',
            'status' => 0,
            'message' => 'no data found',
        );
    }
    echo json_encode($to_encode);
}
else if (isset($_GET['getDashboardDetatilsCheck'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    $userId = $json['userId'];
    // $userType = $json['userType'];
    $candidateId = $json['candidateId'];
    $filterQuery = '';
    $filterQuery1 = '';


    $candidate_sql = "select firstName, usertype, emailId from users where id = '" . $candidateId . "'";
    $candidate_query = mysqli_query($databaseConnection, $candidate_sql);
    $candidate = mysqli_fetch_all($candidate_query, MYSQLI_ASSOC);
    //  print_r($candidate);
    $candidateEmailId = $candidate[0]['emailId'];
    //  exit();




    $pd_sql = "SELECT    
        pd.resume
    FROM 
        professionaldetails pd
    WHERE 
        pd.candidateId = " . $candidateId . "
    ;";


    $pd_query = mysqli_query($databaseConnection, $pd_sql);

    if ($pd_query && mysqli_num_rows($pd_query) > 0) {
        $values['pd'] = mysqli_fetch_assoc($pd_query); // Fetch a single row
    } else {
        $values['pd'] = null; // No record found
    }

    $to_encode = array(
        'result' => 'success',
        'status' => 1,
        'data' => $values,
        'message' => 'data found',
    );

    echo json_encode($to_encode);
} else if (isset($_GET['showPracticedetailspopup'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    $userId = $json['userId'];
    $userType = $json['userType'];
    $candidateId = $json['candidateId'];
    $preInterviewId = $json['preInterviewId'];
    $filterQuery = '';

    if ($json['userType'] == 'corporate') {
        $filterQuery .= " AND fr.review_status IN (2) AND i.companyId NOT IN (SELECT company_id FROM preInterview WHERE userId NOT IN (" . $json['userId'] . ")) ";
    } else {
        $filterQuery .= " AND fr.review_status IN (2,1,0,-3,-4,-2) ";
    }


    $psql = "SELECT 
    t.*,
    CASE 
        WHEN (t.fr_id IS NOT NULL AND t.review_status = 2) THEN 'Assessment Completed'
        WHEN ((t.fr_id IS NOT NULL OR t.completion_status IS NOT NULL) AND t.review_status IN (0, 1)) THEN 'Assessment in Progress'
        WHEN ((t.fr_id IS NOT NULL OR t.completion_status IS NOT NULL) AND t.review_status = -2) THEN 'Internal Review'
        WHEN (t.fr_id IS NOT NULL AND t.review_status = -4 AND t.reasonOfRejection = 'incompleteInterview') THEN 'Incomplete'
        WHEN (t.fr_id IS NOT NULL AND t.review_status = -4 AND t.reasonOfRejection = 'technicalIssue') THEN 'Technical Issue'
        WHEN (t.fr_id IS NOT NULL AND t.review_status = -4 AND t.reasonOfRejection NOT IN ('technicalIssue', 'incompleteInterview')) THEN 'Rejected'
        WHEN (t.fr_id IS NOT NULL AND t.review_status = -4 AND t.reasonOfRejection = 'duplicateAttempt') THEN 'duplicateAttempt'
        WHEN (t.fr_id IS NOT NULL AND t.review_status = -4 AND t.reasonOfRejection = 'limitedFreeAssessment') THEN 'limitedFreeAssessment'
        WHEN (t.fr_id IS NOT NULL AND t.review_status = -4 AND t.reasonOfRejection = 'unauthorizedUser') THEN 'unauthorizedUser'
        WHEN (t.fr_id IS NULL AND t.scheduleTime != t.firstScheduleDate AND DATEDIFF(t.scheduleTime, NOW()) >= 1) THEN 'Re-Scheduled'
        WHEN (t.fr_id IS NULL AND t.scheduleTime = 1) THEN 'Future Scheduled'
        WHEN (t.fr_id IS NULL AND t.scheduleTime = t.firstScheduleDate AND DATEDIFF(t.scheduleTime, NOW()) >= 1) THEN 'Future Scheduled'
        WHEN (t.fr_id IS NULL AND t.review_status IS NULL AND t.scheduleTime IS NOT NULL) THEN 'Scheduled'
        WHEN (t.fr_id IS NULL AND t.review_status IS NULL AND t.scheduleTime IS NULL) THEN 'Job Invited'
    END AS interviewStatus 
FROM (
    SELECT    
        fr.review_status, 
        fr.reasonOfRejection,
        isc.scheduleTime,
        isc.firstScheduleDate,
        cit.completion_status,
        fr.id AS fr_id,
        m.mergeId,
        m.candidateId,
        m.interviewId,
        i.preInterviewId,
        m.interviewSessionId,
        CONCAT('/review?i=', m.interviewId, '&c=', m.candidateId, '&s=', m.interviewSessionId) AS url, 
        fr.suitability,
        pr.interviewType,
        pr.interviewName,
        pr.id
    FROM 
        mergedVideos m 
    INNER JOIN 
        interview i ON m.interviewId = i.id 
    INNER JOIN 
        feedback_request fr ON fr.candidateId = m.candidateId AND fr.interviewSessionId = m.interviewSessionId 
    JOIN 
        interviewSchedule isc ON isc.candidate_id = m.candidateId and isc.interviewId=m.interviewId 
    LEFT JOIN 
        candidate_interview_transection cit ON cit.interviewId = m.interviewId 
    INNER JOIN 
        preInterview pr ON pr.id = i.preInterviewId
    WHERE 
        m.candidateId = " . $candidateId . "
        AND i.preInterviewId= " . $preInterviewId . "
         " . $filterQuery . "
    GROUP BY 
        m.interviewId
    ORDER BY 
        m.interviewSessionId DESC
) AS t;";
    // echo $psql;
    $practice_query = mysqli_query($databaseConnection, $psql);

    $sqlcount = " select m.mergeId 
    FROM 
    mergedVideos m 
INNER JOIN 
    interview i ON m.interviewId = i.id 
INNER JOIN 
    feedback_request fr ON fr.candidateId = m.candidateId AND fr.interviewSessionId = m.interviewSessionId 
JOIN 
    interviewSchedule isc ON isc.candidate_id = m.candidateId and isc.interviewId=m.interviewId 
LEFT JOIN 
    candidate_interview_transection cit ON cit.interviewId = m.interviewId 
INNER JOIN 
    preInterview pr ON pr.id = i.preInterviewId
WHERE 
    m.candidateId = " . $candidateId . "
    AND i.preInterviewId= " . $preInterviewId . "
     " . $filterQuery . "
GROUP BY 
    m.interviewId ;";
    $subject_countquery = mysqli_query($databaseConnection, $sqlcount);

    $values = array();
    $to_encode = array();
    if ($practice_query) {

        $values['practicedetails'] = mysqli_fetch_all($practice_query, MYSQLI_ASSOC);
        $values['pdetailscount'] = mysqli_num_rows($subject_countquery);
        $to_encode = array(
            'result' => 'success',
            'status' => 1,
            'data' => $values,
            'message' => 'data found',
        );
    } else {

        $values['practicedetails'] = [];
        $to_encode = array(
            'result' => 'success',
            'status' => 0,
            'data' => $values,
            'message' => 'no data found',
        );
    }
    echo json_encode($to_encode);

} elseif (isset($_GET['getWaitingList'])) {
    $data = file_get_contents("php://input");
    $json = json_decode($data, true);

    $RecruiterEmail = "ananth@goprac.com";
    $subjects = 'Request for the Waiting List';
    $userId = $json['userId'];

    // Fetch candidate details from the users table
    $query = " select firstname,emailId,mobileNumber from users where id ='$userId'";
    $result = mysqli_query($databaseConnection, $query);
    $candidateData = mysqli_fetch_assoc($result);


    $candidateName = $candidateData['firstname'];
    $candidateEmail = $candidateData['emailId'];
    $candidatePhone = $candidateData['mobileNumber'];


    $query = "INSERT INTO candidateInterviewMapping (candidateId, waitingList) VALUES ('$userId','Y')";
    $insert_query = mysqli_query($databaseConnection, $query);

    if ($insert_query) {
        // Compose email message
        $messages = "<html>
                    <head>
                    </head>
                    <body>
                        <p style='font-weight:bold;color:black'>Dear Nitin,</p>
                        <p style='font-weight:bold;color:black'>Greetings from GoPrac!</p>   
                        <p style='font-weight:bold;color:black'>We recommend you to meet with the following candidates who have expressed interest in joining the waitinglist .</p>
                        <p style='font-weight:bold;color:black'>Candidate Details:</p>
                        <table style='border-collapse: collapse; border: 1px solid black;'>
                        <tr>
                            <th style='border: 1px solid black;'>Candidate Name</th>
                            <th style='border: 1px solid black;'>Phone No</th>
                            <th style='border: 1px solid black;'>Email ID</th>
                        </tr>
                        <tr>
                            <td style='border: 1px solid black;'>" . $candidateName . "</td>
                            <td style='border: 1px solid black;'>" . $candidatePhone . "</td>
                            <td style='border: 1px solid black;'>" . $candidateEmail . "</td>
                        </tr>
                        </table> 
                        <p style='font-weight:bold;color:black'>Do let us know if you need any further assistance. Thank you.</p> 
                        <p style='font-weight:bold;color:black'>Greetings!<br>GoPrac Team</p>
                    </body>
                    </html>";

        // Send email
        $to = $RecruiterEmail;
        $message = $messages;
        // $cc = ''; 
        // echo $message;
        sendEmailToUser($to, null, $subjects, $message);

        $to_encode = array(
            'result' => 'success',
            'status' => 1,
        );
    } else {
        $to_encode = array(
            'result' => 'error',
            'status' => 0,
            'errorCode' => 'Error while inserting data into the database'
        );
    }

    echo json_encode($to_encode);
} else if (isset($_GET['getPracticeReport'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    $userId = $json['userId'];
    $userType = $json['userType'];

    $limit = $json['limit'];
    $start = ($json['page'] - 1) * $limit;
    $limit_query = $limit == 0 ? "" : " limit " . $start . "," . $limit;
    $condition = '';
    $condition1 = '';
    if ($json['practicePreId'] != '') {
        $preId = implode(",", array_map('intval', $json['practicePreId']));
        $condition = " and cim.preInterviewId in (" . $preId . ")";
    }
    $candidateSearchCondition = '';

    $candidate_search = trim($json['candidate_search']);

    if ($candidate_search != "") {

        if (filter_var($candidate_search, FILTER_VALIDATE_EMAIL)) {
            $candidateSearchCondition = "and u.emailId='" . $candidate_search . "'";
        } else {
            $candidateSearchCondition = "and (u.firstname LIKE '%" . $candidate_search . "%')";
        }
    }

    if ($json['assignFrom'] != "" && $json['assignTo'] != "") {
        $condition1 = " and (date_format(pr.interviewStartDate,'%Y-%m-%d')) >= '" . $json['assignFrom'] . "' and (date_format(pr.interviewStartDate,'%Y-%m-%d')) <= '" . $json['assignTo'] . "'";
    } else if ($json['assignFrom'] != "") {
        $condition1 = " AND pr.interviewStartDate >= '" . $json['assignFrom'] . "' ";
    }

    $sql = "SELECT cim.id as cimId,
    cim.emailId as cimEmailId,
    cim.practiceStatus as PracticePostingStatus,
    cim.*,
    jpm.*,
    pr.interviewName as practiceName,
    cim.createdAt as practiceAssignDate,
    (
        SELECT max(candidateStatus) FROM interviewSchedule WHERE preInterviewId IN (jpm.jobPreInterviewId) AND candidate_id = cim.candidateId
    ) AS jobstatus,
    pd.resume,
    COALESCE(r.name, u.firstName) AS candidateName,
    COALESCE(r.email, u.emailId) AS emailId,
    COALESCE(r.phone_no, u.mobileNumber) AS mobileNumber,
    case when now() > (cim.contactDate + INTERVAL 24 HOUR) then 2  WHEN NOW() <= (cim.contactDate + INTERVAL 24 HOUR) THEN 1  else 0 end as olderFlag,
     COALESCE(isc.workExperience, pd.workExperience) AS yoe,
     fr.intScore
    from candidateInterviewMapping cim
    left join register r on r.email=cim.emailId
    left join preInterview pr on pr.id=cim.preInterviewId
    left join jobPracticeMapping jpm on jpm.practicePreInterviewId=cim.preInterviewId
    left join professionaldetails pd on pd.candidateId=cim.candidateId
    left join interviewSchedule isc on isc.preInterviewId=cim.preInterviewId AND isc.emailId = cim.emailId
    left join users u on u.emailId=cim.emailId OR u.id = cim.candidateId
    LEFT JOIN feedback_request fr ON fr.preInterviewId = cim.preInterviewId  AND fr.candidateId = cim.candidateId 
    AND fr.intScore = (
        SELECT MAX(intScore) 
        FROM feedback_request 
        WHERE preInterviewId = cim.preInterviewId and candidateId = cim.candidateId 
    )
    where  1 " . $condition . "" . $candidateSearchCondition . "" . $condition1 . " group by cim.id order by cim.id desc" . $limit_query . "";

    // echo $sql;
    // exit();

    $subject_query = mysqli_query($databaseConnection, $sql);

    $csql = "select cim.id from candidateInterviewMapping cim left join users u on u.emailId=cim.emailId left join preInterview pr on pr.id=cim.preInterviewId where  1 " . $condition . " " . $candidateSearchCondition . " " . $condition1 . "
    group by cim.id 
    order by cim.id desc ";
    //      echo $csql;
    // exit();

    $count_query = mysqli_query($databaseConnection, $csql);


    $values = array();
    $to_encode = array();
    if ($subject_query) {
        $values['practiceData'] = array();
        $values['practiceDatacount'] = mysqli_num_rows($count_query);
        if (mysqli_num_rows($subject_query) > 0) {
            while ($row = mysqli_fetch_assoc($subject_query)) {
                $preInterviewId = $row['preInterviewId'];
                $emailId = $row['cimEmailId'];

                $activeSql = "SELECT
                        DATE_FORMAT(isc.createdAt, '%d-%b-%Y') AS lastActiveDate
                    FROM
                        interviewSchedule isc
                    INNER JOIN
                        users u ON u.id = isc.candidate_id
                    WHERE
                        u.emailId = '" . $emailId . "'
                        AND isc.preInterviewId = $preInterviewId
                    ORDER BY
                        isc.createdAt DESC
                    LIMIT 1;";

                // echo $activeSql;
                // exit();
                $active_query = mysqli_query($databaseConnection, $activeSql);
                $activeSqldata = mysqli_fetch_assoc($active_query);
                if ($activeSqldata) {
                    $row['lastActiveDate'] = $activeSqldata['lastActiveDate'];
                } else {
                    $row['lastActiveDate'] = null;
                }

                $countSql = "SELECT
                COUNT(CASE WHEN sq.review_status IN (2, 3) THEN 1 ELSE NULL END) AS completed,
                COUNT(CASE WHEN sq.review_status NOT IN (2, 3) THEN 1 ELSE NULL END) AS attempted
             FROM (
                SELECT DISTINCT
                    fr.review_status,
                    m.interviewId
                FROM
                    mergedVideos m
                INNER JOIN
                    interview i ON m.interviewId = i.id
                INNER JOIN
                    feedback_request fr ON fr.candidateId = m.candidateId AND fr.interviewSessionId = m.interviewSessionId
                INNER JOIN
                    interviewSchedule isc ON isc.candidate_id = m.candidateId AND isc.interviewId = m.interviewId
                INNER JOIN users u ON u.id=m.candidateId
                WHERE
                    u.emailId = '" . $emailId . "'
                    AND i.preInterviewId = " . $preInterviewId . "
             ) AS sq";
                // echo $countSql;
                // exit();
                $count_query = mysqli_query($databaseConnection, $countSql);
                $countSqldata = mysqli_fetch_assoc($count_query);
                if ($countSqldata) {
                    $row['practiceCompleted'] = $countSqldata['completed'];
                    $row['practiceAttempted'] = $countSqldata['attempted'];

                }
                $assignedSql = "select id from candidateInterviewMapping where emailId='" . $emailId . "' and preInterviewId=" . $preInterviewId . " ";
                //  echo    $assignedSql;
                //  exit(); 
                $assigned_query = mysqli_query($databaseConnection, $assignedSql);

                if ($assigned_query) {
                    $row['practiceAssigned'] = mysqli_num_rows($assigned_query);

                }

                $values['practiceData'][] = $row;
            }
        }

        $to_encode = array(
            'result' => 'success',
            'status' => 1,
            'data' => $values,
            'message' => 'data found',
        );
    } else {
        $to_encode = array(
            'result' => 'success',
            'status' => 0,
            'message' => 'no data found',
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['getCompanyReport'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    $userId = $json['userId'];
    $userType = $json['userType'];

    $limit = $json['limit'];
    $start = ($json['page'] - 1) * $limit;
    $limit_query = $limit == 0 ? "" : " limit " . $start . "," . $limit;
    $condition = '';
    $condition1 = '';
    if ($json['companyPreId'] != '' && $json['companyPreId'] != null) {
        $companyId = implode(",", array_map('intval', $json['companyPreId']));
        $condition = " and ac.id in (" . $companyId . ")";
    }

    $sql = "select ac.id as cimId, ac.name as companyName, ce.id as companyEmailId from aspiration_company ac left join companyEmailTemplate ce on ce.companyId = ac.id where 1 " . $condition . " group by ac.id order by ac.id desc" . $limit_query . "";
    $subject_query = mysqli_query($databaseConnection, $sql);

    $csql = "select ac.id as cimId from aspiration_company ac where 1 " . $condition . " group by ac.id order by ac.id desc";

    $count_query = mysqli_query($databaseConnection, $csql);


    $values = array();
    $to_encode = array();
    if ($subject_query) {
        $values['companyData'] = array();
        $values['companyDatacount'] = mysqli_num_rows($count_query);
        if (mysqli_num_rows($subject_query) > 0) {
            $values['companyData'] = mysqli_fetch_all($subject_query, MYSQLI_ASSOC);
        }

        $to_encode = array(
            'result' => 'success',
            'status' => 1,
            'data' => $values,
            'message' => 'data found',
        );
    } else {
        $to_encode = array(
            'result' => 'success',
            'status' => 0,
            'message' => 'no data found',
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['getCandidateFeedbackData'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    $userId = $json['userId'];
    $userType = $json['userType'];

    $limit = $json['limit'];
    $start = ($json['page'] - 1) * $limit;
    $limit_query = $limit == 0 ? "" : " limit " . $start . "," . $limit;

    $candidateSearchCondition = '';

    $candidate_search = trim($json['candidate_search']);

    if ($candidate_search != "") {
        if (preg_match('/^[0-9]{10}+$/', $candidate_search)) {
            $candidateSearchCondition = "and u.mobileNumber='" . $candidate_search . "'";
        } else {
            $candidateSearchCondition = "and (u.firstname LIKE '%" . $candidate_search . "%')";
        }
    }



    $condition1 = '';

    // $condition='';

    if ($json['practicePreId'] != '') {
        $preId = implode(",", array_map('intval', $json['practicePreId']));
        $condition1 = " and sub.preId in (" . $preId . ")";
    }

    if ($json['paymentStatus'] != "null") {

        $condition1 .= "AND sub.newpaymentstatus IN ('" . $json['paymentStatus'] . "') ";

    }


    $sql = "select sub.* from (
    SELECT 	pr.id as preId,u.firstName AS candidateName, u.mobileNumber AS mobileNo, pr.interviewName, rt.userInterface AS platformExpRating, rt.questionQuality AS questionQualityRating, rt.ratingsSubmitTime AS ratingDate, fb.isAgree AS feedbackReportRating, fb.otherFeedback AS feedbackReportComments, pt.status AS paymentStatus,CASE WHEN pt.status = 'PAID' THEN 'Paid' WHEN pt.status = 'CHECKOUT' THEN 'Checkout' WHEN dfr.viewedStatus = 'download' THEN 'Download'WHEN dfr.viewedStatus = 'Viewed' THEN 'Viewed' ELSE 'Not Viewed'END AS newpaymentstatus, fr.review_status, CONCAT('https://goprac.com/review?i=', fr.interviewId, '&c=',fr.candidateId, '&s=', fr.interviewSessionId) as interviewUrl, fr.requestDate as feedbackDate, fr.interviewSessionId 
    FROM ratings rt
    INNER JOIN users u ON rt.candidateId = u.id
    INNER JOIN feedback_request fr on fr.interviewSessionId = rt.interviewSessionId
    LEFT JOIN feedbackonfeedback fb ON fb.interviewSessionId = rt.interviewSessionId
    INNER JOIN interviewSchedule isc ON isc.emailId = u.emailId INNER JOIN interview i ON i.id=fr.interviewId
    INNER JOIN preInterview pr ON pr.id = i.preInterviewId LEFT JOIN payment_transaction pt ON pt.interview_id = rt.interviewId
    LEFT JOIN detail_feedback_request dfr ON dfr.interviewId = rt.interviewId 
        where 1 " . $candidateSearchCondition . " 
        GROUP BY rt.interviewSessionId ORDER BY
         rt.reviewId DESC) as sub where 1 " . $condition1 . " " . $limit_query . "";

    // echo $sql;
    // exit();

    $subject_query = mysqli_query($databaseConnection, $sql);

    $csql = "select sub.* from (
    SELECT pr.id as preId, CASE WHEN pt.status = 'PAID' THEN 'Paid' WHEN pt.status = 'CHECKOUT' THEN 'Checkout' WHEN dfr.viewedStatus = 'download' THEN 'Download'WHEN dfr.viewedStatus = 'Viewed' THEN 'Viewed' ELSE 'Not Viewed'END AS newpaymentstatus, rt.reviewId
    FROM ratings rt INNER JOIN users u ON rt.candidateId = u.id
    LEFT JOIN feedbackonfeedback fb ON fb.interviewSessionId = rt.interviewSessionId
    INNER JOIN interviewSchedule isc ON isc.emailId = u.emailId INNER JOIN interview i ON i.id=rt.interviewId
    INNER JOIN preInterview pr ON pr.id = i.preInterviewId
    LEFT JOIN payment_transaction pt ON pt.interview_id = rt.interviewId LEFT JOIN detail_feedback_request dfr ON dfr.interviewId = rt.interviewId 
     where 1 " . $candidateSearchCondition . " 
     GROUP BY rt.interviewSessionId ORDER BY rt.reviewId DESC) as sub where 1 " . $condition1 . "";
    // echo $csql;
    // exit();


    $count_query = mysqli_query($databaseConnection, $csql);
    $values = array();
    $to_encode = array();
    if ($subject_query) {
        $values['practiceData'] = mysqli_fetch_all($subject_query, MYSQLI_ASSOC);
        $values['practiceDatacount'] = mysqli_num_rows($count_query);

        $to_encode = array(
            'result' => 'success',
            'status' => 1,
            'data' => $values,
            'message' => 'data found',
        );
    } else {
        $to_encode = array(
            'result' => 'success',
            'status' => 0,
            'message' => 'no data found',
        );
    }
    echo json_encode($to_encode);
} else if (isset($_GET['sendFeedbackReport'])) {
    $data = file_get_contents("php://input");
    $json = json_decode($data, true);

    if ($json !== null) {
        $candidateName = isset($json['candidateName']) ? $json['candidateName'] : '';
        $mobileNumber = isset($json['mobileNumber']) ? $json['mobileNumber'] : null;
        $interviewName = isset($json['interviewName']) ? $json['interviewName'] : '';
        $interviewLink = isset($json['interviewLink']) ? $json['interviewLink'] : '';
        $interviewSessionId = isset($json['interviewSessionId']) ? $json['interviewSessionId'] : '';

        $seconds = $interviewSessionId / 1000;

        // Create a DateTime object
        $datetime = new DateTime();
        $datetime->setTimestamp($seconds);

        // Separate date and time
        $date = $datetime->format('l, F j, Y');
        $time = $datetime->format('h:i A');

        $watidata = array();
        $url = $interviewLink;
        $components = explode('/', $url);
        $modifiedUrl = isset($components[3]) ? $components[3] : '';
        $watidata["candidateName"] = $candidateName;
        $watidata["companyname"] = $interviewName;
        $watidata["time"] = $time;
        $watidata["date"] = $date;
        $watidata["interviewLink1"] = $modifiedUrl;
        $watidata["interviewLink"] = $url;
        $watidata["sender"] = 'Support Team';

        //whatsAppMsg($databaseConnection,'9767479189',$watidata,"AssessmentCompletion");
        whatsAppMsg($databaseConnection, $mobileNumber, $watidata, "AssessmentCompletion");

        $updateStatus = array(
            'result' => 'success',
            'status' => 1,
            'result' => 'Successfully send Feedback'

        );

    } else {
        $updateStatus = array(
            'result' => 'error',
            'status' => 0,
            'errorCode' => 'Error while decoding JSON'
        );
    }
    $to_encode = $updateStatus;
    echo json_encode($to_encode);
} else if (isset($_GET['getPracticeInterestData'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    $userId = $json['userId'];
    $userType = $json['userType'];

    $limit = $json['limit'];
    $start = ($json['page'] - 1) * $limit;
    $limit_query = $limit == 0 ? "" : " limit " . $start . "," . $limit;

    $candidateSearchCondition = '';

    $candidate_search = trim($json['candidate_search']);

    if ($candidate_search != "") {

        if (filter_var($candidate_search, FILTER_VALIDATE_EMAIL)) {
            $candidateSearchCondition = "and r.email='" . $candidate_search . "'";
        } else {
            $candidateSearchCondition = "and (r.name LIKE '%" . $candidate_search . "%')";
        }


    }


    //     $intersetedsql="select sub_query.*,
//  GROUP_CONCAT(distinct rr.name) AS role,
//  GROUP_CONCAT(distinct fs.favourite_subject) AS subject from (
// select r.candidateStatus,r.preId,r.registeredTime,r.f2fDate,r.name,r.email,r.phone_no,r.roleId,r.subjectId,cim.preInterviewId,u.id,r.id as registerId,pd.resume,u.createdOn from register r left join users u on r.email=u.emailId left join candidateInterviewMapping cim on cim.candidateId=u.id left join professionaldetails pd on pd.candidateId=u.id where cim.candidateId is null AND r.roleId IS NOT NULL ".$candidateSearchCondition."  GROUP BY r.email, r.roleId, r.subjectId, cim.preInterviewId 
//  ) as sub_query LEFT JOIN 
//     relavant_role rr 
// ON 
//     FIND_IN_SET(rr.id, sub_query.roleId) > 0
//     LEFT JOIN
//  favourite_subject fs 
// ON 
//     FIND_IN_SET(fs.id, sub_query.subjectId) > 0
// group by sub_query.email, sub_query.roleId, sub_query.subjectId, sub_query.preInterviewId
// order by sub_query.registerId desc ".$limit_query."";

    $intersetedsql = "select sub_query.*,GROUP_CONCAT(distinct rr.name) AS role,
GROUP_CONCAT(distinct fs.favourite_subject) AS subject from (
select r.candidateStatus,r.preId,r.registeredTime,r.f2fDate,r.name,r.email,r.phone_no,r.roleId,r.subjectId,u.id,r.id as registerId,pd.resume,u.createdOn from register r left join users u on r.email=u.emailId left join professionaldetails pd on pd.candidateId=u.id where (r.source != 'companypage' OR r.source is null) " . $candidateSearchCondition . " GROUP BY r.email 
) as sub_query LEFT JOIN 
   relavant_role rr 
ON 
   FIND_IN_SET(rr.id, sub_query.roleId) > 0
   LEFT JOIN
favourite_subject fs 
ON 
   FIND_IN_SET(fs.id, sub_query.subjectId) > 0
group by sub_query.email
order by sub_query.registerId desc " . $limit_query . "";

    //echo  $intersetedsql;
// exit();

    $interseted_query = mysqli_query($databaseConnection, $intersetedsql);
    //$intersetedsqlcount="select r.id from register r left join users u on r.email=u.emailId and r.phone_no=u.mobileNumber left join candidateInterviewMapping cim on cim.candidateId=u.id  where cim.candidateId is null AND r.roleId IS NOT NULL ".$candidateSearchCondition." GROUP BY r.email, r.roleId, r.subjectId, cim.preInterviewId;";
    $intersetedsqlcount = "select r.id from register r left join users u on r.email=u.emailId where (r.source != 'companypage' OR r.source is null) " . $candidateSearchCondition . " GROUP BY r.email";


    $interseted_count_query = mysqli_query($databaseConnection, $intersetedsqlcount);

    $InterestedDataResult = mysqli_fetch_all($interseted_query, MYSQLI_ASSOC);


    foreach ($InterestedDataResult as $key => $row) {
        $uId = $row['id'];
        $emailId1 = $row['email'];
        $mobileNumber1 = $row['phone_no'];
        $userId = '';

        if ($uId !== '' && $uId !== null) {
            $userId = $uId;
        } else {
            if (!empty($emailId1)) {
                $useId = "SELECT id AS candidateId FROM users WHERE email = '" . $emailId1 . "'";
                $useIdIdResult = mysqli_query($databaseConnection, $useId);

                if ($useIdIdResult) {
                    $row = mysqli_fetch_assoc($useIdIdResult);
                    if ($row) {
                        $userId = $row['candidateId'];
                    }
                }
            }

            if (empty($userId) && !empty($mobileNumber1)) {
                $useId1 = "SELECT id AS candidateId FROM users WHERE phone_no = '" . $mobileNumber1 . "'";
                $useIdIdResult1 = mysqli_query($databaseConnection, $useId1);

                if ($useIdIdResult1) {
                    $row1 = mysqli_fetch_assoc($useIdIdResult1);
                    if ($row1) {
                        $userId = $row1['candidateId'];
                    }
                }
            }
        }

        if (!empty($emailId1)) {
            $sql = "SELECT COUNT(*) AS practiceCount FROM candidateInterviewMapping WHERE emailId = '" . $emailId1 . "'";
            $result = mysqli_query($databaseConnection, $sql);

            if ($result && mysqli_num_rows($result) > 0) {
                // Fetch the row from the SQL query
                $queryRow = mysqli_fetch_assoc($result);

                // Merge the data into $queryResult
                $InterestedDataResult[$key]['practiceCount'] = $queryRow['practiceCount'];
                $InterestedDataResult[$key]['cimemailId'] = $emailId1;
                $InterestedDataResult[$key]['userId'] = $userId;
            } else {
                $InterestedDataResult[$key]['practiceCount'] = 0; // Set to 0 if no results found
                $InterestedDataResult[$key]['userId'] = $userId;
            }
        } else {
            $InterestedDataResult[$key]['practiceCount'] = 0; // Set to 0 if userId is empty
            $InterestedDataResult[$key]['userId'] = $userId;
        }
    }

    $values = array();
    $to_encode = array();
    if ($interseted_query) {
        $values['InterestedData'] = $InterestedDataResult;
        $values['InterestedDataCount'] = mysqli_num_rows($interseted_count_query);

        $to_encode = array(
            'result' => 'success',
            'status' => 1,
            'data' => $values,
            'message' => 'data found',
        );
    } else {
        $to_encode = array(
            'result' => 'success',
            'status' => 0,
            'message' => 'no data found',
        );
    }
    echo json_encode($to_encode);
} elseif (isset($_GET['updateContactStatus'])) {
    $data = file_get_contents("php://input");
    $json = json_decode($data, true);

    $cimId = $json['cimId'];


    if ($cimId !== null) {
        $query = "UPDATE candidateInterviewMapping SET contactDate = now() WHERE id = '$cimId'";
    } else {
        $to_encode = array(
            'result' => 'error',
            'status' => 0,
            'errorCode' => 'Id not provided'
        );
        echo json_encode($to_encode);
    }

    $insert_query = mysqli_query($databaseConnection, $query);

    if ($insert_query) {
        $to_encode = array(
            'result' => 'success',
            'status' => 1,
        );
    } else {
        $to_encode = array(
            'result' => 'error',
            'status' => 0,
            'errorCode' => 'Error while inserting data into the database'
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['updateResume'])) {
    $data = file_get_contents("php://input");
    $json = json_decode($data, true);

    $iscId = $json['iscId'];
    $resume = $json['resume'];
    $submissionFlag = $json['submissionFlag'];

    if ($iscId !== null) {
        if ($submissionFlag == 'Y' || $submissionFlag == 'WA') {
            $query = "UPDATE interviewSchedule SET resume ='$resume',apmStatus = 0  WHERE id = $iscId ";
        } else {
            $query = "UPDATE interviewSchedule SET resume ='$resume',apmStatus = 50  WHERE id = $iscId ";
        }

        // echo $query;
    } else {
        $to_encode = array(
            'result' => 'error',
            'status' => 0,
            'errorCode' => 'Id not provided'
        );
        echo json_encode($to_encode);
    }

    $insert_query = mysqli_query($databaseConnection, $query);

    if ($insert_query) {
        $to_encode = array(
            'result' => 'success',
            'status' => 1,
        );
    } else {
        $to_encode = array(
            'result' => 'error',
            'status' => 0,
            'errorCode' => 'Error while inserting data into the database'
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['uploadtoS3'])) {
    $json = isset($_POST['json']) ? json_decode($_POST['json'], true) : null;
    if (isset($_FILES['file']) && $_FILES['file']['error'] == UPLOAD_ERR_OK && $json) {

        $file = $_FILES['file'];
        $newFileName = $json['newFileName'];
        $fileTmpName = $file['tmp_name'];
        $contentType = mime_content_type($fileTmpName);

        try {
            // Upload data.
            $result = $s3->putObject([
                'Bucket' => 'tempgoprac',
                'Key' => $newFileName,
                'Body' => fopen($fileTmpName, 'r'),
                'ContentType' => $contentType,
                'ACL' => 'public-read',
                'Metadata' => [
                    'Content-Disposition' => 'attachment; filename="' . $newFileName . '"',
                ],
            ]);
            $to_encode = [
                'message' => 'File uploaded successfully',
                'fileUrl' => $result['ObjectURL']
            ];
        } catch (AwsException $e) {
            $to_encode = [
                'message' => 'There was an error uploading the file',
                'error' => $e->getMessage()
            ];
        }
    } else {
        $to_encode = [
            'message' => 'No file uploaded or there was an upload error',
        ];
    }
    echo json_encode($to_encode);
} else if (isset($_GET['getSkillValues'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    $value = $json['query'];


    // $values = array();

    // $filter4 = "SELECT id, skillName from  skills WHERE active='Y'";

    $filter = "SELECT id, favourite_subject as name from  favourite_subject WHERE  active= 'Y' and favourite_subject LIKE('$value%')";
    // echo $filter;
    $filterResult = mysqli_query($databaseConnection, $filter);

    $values = mysqli_fetch_all($filterResult, MYSQLI_ASSOC);


    $to_encode = array(
        'data' => $values,
        'status' => 1
    );
    echo json_encode($to_encode);
} elseif (isset($_GET['getapmlogs'])) {
    $data = file_get_contents("php://input");
    $json = json_decode($data, true);

    $query = "Select * from apmLogs order by id desc limit 100";

    $queryResult = mysqli_query($databaseConnection, $query);

    $apm = mysqli_fetch_all($queryResult, MYSQLI_ASSOC);

    if ($apm) {
        $to_encode = array(
            'status' => 1,
            'data' => $apm
        );
    } else {
        $to_encode = array(
            'status' => 0,
            'errorCode' => 'Error while dwtchinf data into the database'
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['addSkillMaster'])) {
    $data = file_get_contents("php://input");
    $json = json_decode($data, true);
    $favourite_subject = mysqli_real_escape_string($databaseConnection, $json['favourite_subject']);

    // Build the SQL query
    // $query = "INSERT INTO favourite_subject (favourite_subject) 
    //           SELECT '$favourite_subject' 
    //           WHERE NOT EXISTS (
    //               SELECT 1 FROM favourite_subject WHERE favourite_subject = '$favourite_subject'
    //           )";

    $query = "
    INSERT INTO favourite_subject (favourite_subject, active) 
    VALUES ('$favourite_subject', 'Y')
    ON DUPLICATE KEY UPDATE active = IF(active = 'N', 'Y', active)
    ";

    // Execute the query
    $queryResult = mysqli_query($databaseConnection, $query);

    // Check for query success
    if ($queryResult && mysqli_affected_rows($databaseConnection) > 0) {
        $to_encode = array(
            'status' => 1,
            'data' => 'done'
        );
    } else {
        $to_encode = array(
            'status' => 0,
            'errorCode' => 'Error while inserting data into the database or the value already exists'
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['getCandidateActivityFilters'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    $userId = $json['userId'];

    $user_sql = "select firstName, usertype, emailId from users where id = '" . $userId . "'";
    $user_query = mysqli_query($databaseConnection, $user_sql);
    $user = mysqli_fetch_all($user_query, MYSQLI_ASSOC);
    //  print_r($user);
    $user_emailId = $user[0]['emailId'];
    $user_usertype = $user[0]['usertype'];
    //  exit();


    $colleges_sql = "SELECT col.id, col.collegeName as name, pr.id as prId
    FROM colleges col
    LEFT JOIN preInterview pr ON col.id = pr.college_id AND pr.college_id != 0
    LEFT JOIN preInterview_corporate pic ON pic.preinterviewId = pr.id
    WHERE 1
    AND pr.interviewType = 'Practice'
    ";

    if ($user_usertype !== 'admin') {
        $colleges_sql .= " AND pic.userId = $userId";
    }

    $colleges_sql .= " GROUP BY col.id";

    // echo $colleges_sql;
    // exit();
    $colleges_query = mysqli_query($databaseConnection, $colleges_sql);
    $values['colleges'] = mysqli_fetch_all($colleges_query, MYSQLI_ASSOC);

    $jobs_sql = "SELECT pr.* from preInterview pr
        LEFT JOIN preInterview_corporate pic ON pic.preinterviewId = pr.id
        WHERE 1
        AND pr.college_id IS NOT NULL
        AND pr.interviewType = 'practice'";

    if ($user_usertype !== 'admin') {
        $jobs_sql .= " AND pic.userId = $userId";
    }

    // echo $jobs_sql;
    // exit();
    $jobs_query = mysqli_query($databaseConnection, $jobs_sql);
    $values['jobs'] = mysqli_fetch_all($jobs_query, MYSQLI_ASSOC);

    $role = "SELECT * FROM relavant_role WHERE active = 'Y' ORDER BY id DESC";
    $roleResult = mysqli_query($databaseConnection, $role);
    $values['roleNames'] = mysqli_fetch_all($roleResult, MYSQLI_ASSOC);

    $competencySubject = "SELECT DISTINCT skill.id, role.id as roleId, skill.favourite_subject AS name, CASE WHEN role.id is null then 'Other' ELSE role.name END as role
    FROM favourite_subject skill
    LEFT JOIN role_subject map ON map.subjectId = skill.id
    LEFT JOIN relavant_role role ON role.id = map.roleId
    WHERE skill.subjectType = 'competency' AND skill.active = 'Y'
    order by skill.id";

    $competencySubjectResult = mysqli_query($databaseConnection, $competencySubject);
    $values['competencySubject'] = mysqli_fetch_all($competencySubjectResult, MYSQLI_ASSOC);



    $locations = "SELECT * FROM locations ORDER BY 
            CASE 
            WHEN cityName LIKE '%Any%' THEN 0
            WHEN cityName LIKE '%Remote%' THEN 1
            ELSE 2
            END,
            cityName ASC";

    $locationsResult = mysqli_query($databaseConnection, $locations);
    $values['locations'] = mysqli_fetch_all($competencySubjectResult, MYSQLI_ASSOC);





    if ($user_usertype === 'admin') {
        $values['placementSupport'] = 'y';
    } else {
        $placementSupport_sql = "SELECT placementSupport FROM users WHERE id = $userId";
        $placementSupport_query = mysqli_query($databaseConnection, $placementSupport_sql);

        if ($placementSupport_query && $row = mysqli_fetch_assoc($placementSupport_query)) {
            $placementSupport = strtolower($row['placementSupport']) === 'y' ? 'y' : $row['placementSupport'];
            $values['placementSupport'] = $placementSupport;
        } else {
            $values['placementSupport'] = 'y';
        }
    }



    echo json_encode($values);
}
// else if (isset($_GET['createCarAddEmails'])) {
//     $data = @file_get_contents("php://input");
//     $json = json_decode($data, true);

//     if (!isset($json['preInterviewId'])) {
//         echo json_encode([
//             'result' => 'error',
//             'status' => 0,
//             'message' => 'Invalid request parameters'
//         ]);
//         exit();
//     }


//     $emails = $json['emails'];
//     $preInterviewId = $json['preInterviewId'];
//     // $companyId = $json['companyId'];



//     $subjectId = "";
//     $roleId = "";


//     if (!empty($preInterviewId)) {
//         $preInterview = "SELECT st.subject from scps_transaction st inner join preInterview pr ON pr.id=st.preInterviewId where pr.interviewType = 'Practice' and pr.id IN (" . $preInterviewId . ") group by st.subject";
//         $preInterviewResult = mysqli_query($databaseConnection, $preInterview);

//         if ($preInterviewResult) {
//             $row1 = mysqli_fetch_assoc($preInterviewResult);
//             if ($row1) {
//                 $subjectId = $row1['subject'];
//             }
//         }
//     }

//     if (!empty($subjectId)) {
//         $role = "SELECT roleId FROM role_subject where subjectId IN ($subjectId)";
//         // echo $role;
//         $roleResult = mysqli_query($databaseConnection, $role);

//         if ($roleResult) {
//             $row = mysqli_fetch_assoc($roleResult);
//             if ($row) {
//                 $roleId = $row['roleId'];
//             }
//         }
//     }


//     if ($subjectId) {
//         $sql = "SELECT id, favourite_subject FROM favourite_subject WHERE id IN (" . $subjectId . ") ";
//         $subject_query = mysqli_query($databaseConnection, $sql);
//         $subjectResult = mysqli_fetch_all($subject_query, MYSQLI_ASSOC);
//         $subjectName = $subjectResult[0]['favourite_subject'];

//     } else {
//         $subjectName = "";
//     }

//     if ($roleId) {
//         $sql1 = "SELECT id, name as roleName FROM relavant_role WHERE id IN (" . $roleId . ") ";
//         $role_query = mysqli_query($databaseConnection, $sql1);
//         $role_queryResult = mysqli_fetch_all($role_query, MYSQLI_ASSOC);
//         $roleName = $role_queryResult[0]['roleName'];
//     } else {
//         $roleName = "";
//     }



//     if (is_array($emails) && count($emails) > 0) {

//         $values = [];
//         $stmt = $databaseConnection->prepare("INSERT INTO candidateInterviewMapping (emailId, mobileNumber, candidateName, preInterviewId,role, subject, source) VALUES (?, ?, ?, ?, ?, ?, 'car')");

//         foreach ($emails as $entry) {

//             [$candidateName, $email, $mobileNumber] = $entry;
//             // Check if the email already exists for the same preInterviewId
//             $checkQuery = "SELECT COUNT(*) as count FROM candidateInterviewMapping WHERE source='car' AND emailId = ? AND preInterviewId = ?";
//             $stmtCheck = $databaseConnection->prepare($checkQuery);
//             $stmtCheck->bind_param("si", $email, $preInterviewId);
//             $stmtCheck->execute();
//             $resultCheck = $stmtCheck->get_result();
//             $rowCheck = $resultCheck->fetch_assoc();
//             $stmtCheck->close();


//             if ($rowCheck['count'] == 0) {
//                 $roleIdValue = !empty($roleId) ? $roleId : null;
//                 $subjectIdValue = !empty($subjectId) ? $subjectId : null;

//                 $stmt->bind_param("sssiii", $email, $mobileNumber, $candidateName, $preInterviewId, $roleIdValue, $subjectIdValue);
//                 $stmt->execute();
//                 $values[] = ["email" => $email, "status" => "Inserted"];

//                 // send mail
//                 // $to = $email;
//                 // $to = "sourabh13689@gmail.com";
//                 // $subjects = "Practice Interview Assigned";
//                 // $messages = "<p>Hi " . $candidateName . ",</p>
//                 // <p>We have received your request to enhance your aptitude in <strong>" . $roleName . "</strong> and are excited to take it forward.<br>
//                 // You can start your problem-solving practice session anytime that suits you.</p>
//                 // <p>Please find the link to proceed 👉 <a href='https://www.goprac.com/job?p=" . $preInterviewId . "'>Start Practice</a></p>
//                 // <p>Each practice session lasts for <strong>15 minutes</strong>.<br>
//                 // For assistance, reach us at <strong>+91 6360060622</strong>.</p>
//                 // Let’s build your skills together!<br>
//                 // <p>Best regards,<br>
//                 // Nitin Rakesh Prasad<br>
//                 // Founder - GoPrac</p>";
//                 // Send the email
//                 // sendEmailToUser($to, null, $subjects, $messages);
//             }
//         }

//         $stmt->close();
//     } else {
//         $values = ["error" => "No valid emails provided"];
//     }

//     echo json_encode($values);
// }
// else if (isset($_GET['getCandidateActivityData'])) {
//     $data = file_get_contents("php://input");
//     $json = json_decode($data, true);

//     // if (!isset($json['userId']) || !isset($json['preInterviewId'])) {
//     if (!isset($json['userId']) || !isset($json['collegeId'])) {
//         echo json_encode([
//             'result' => 'error',
//             'status' => 0,
//             'message' => 'Invalid request parameters'
//         ]);
//         exit();
//     }

//     $userId = intval($json['userId']);
//     $collegeId = intval($json['collegeId']);
//     $from = $json['from'];
//     $to = $json['to'];


//     $main_sql = "SELECT
//             u.firstName as candidateName,
//             u.id as candidateId,
//              COALESCE(u.mobileNumber, cim.mobileNumber) AS mobileNumber,
//             cim.emailId as emailId,
//             pr.roleId,
//             cim.preInterviewId,
//             rr.name AS role,
//             GROUP_CONCAT(fs.favourite_subject) AS subject,
//             pr.interviewName AS product,
//             fr.intScore,
//             CONCAT(
//                 COUNT(DISTINCT pr.interviewName), 
//                 ' [', 
//                 GROUP_CONCAT(pr.interviewName SEPARATOR ', '), 
//                 ']'
//             ) AS practices
//         FROM
//             candidateInterviewMapping cim
//         LEFT JOIN users u ON u.emailId = cim.emailId 
//         LEFT JOIN preInterview pr ON pr.id = cim.preInterviewId
//         LEFT JOIN relavant_role rr ON rr.id = pr.roleId
//         LEFT JOIN favourite_subject fs ON FIND_IN_SET(fs.id, pr.subjectId) > 0
//         LEFT JOIN feedback_request fr ON
//             fr.preInterviewId = cim.preInterviewId
//             AND fr.candidateId = u.id
//             AND fr.intScore = (
//                 SELECT MAX(intScore)
//                 FROM feedback_request
//                 WHERE preInterviewId = cim.preInterviewId
//                 AND candidateId = u.id 
//             )
//         WHERE
//             cim.id IN (
//                 SELECT MAX(cim_sub.id)
//                 FROM candidateInterviewMapping cim_sub
//                 LEFT JOIN preInterview pr_sub ON pr_sub.id = cim_sub.preInterviewId
//                 WHERE 1
//                 AND pr_sub.interviewType = 'Practice'
//                 AND cim_sub.source = 'car'
//                 AND pr_sub.college_id = ? "
//         . ($from && $to ? " AND DATE(cim_sub.createdAt) BETWEEN ? AND ? " : " ") .
//         " GROUP BY cim_sub.emailId, cim_sub.preInterviewId
//             )
//         GROUP BY cim.emailId
//         ORDER BY cim.id DESC;";

//     //                 AND cim_sub.source='car'
//     // echo $main_sql;

//     $stmt = mysqli_prepare($databaseConnection, $main_sql);

//     if ($from && $to) {
//         mysqli_stmt_bind_param($stmt, "iss", $collegeId, $from, $to);
//     } else {
//         mysqli_stmt_bind_param($stmt, "i", $collegeId);
//     }
//     mysqli_stmt_execute($stmt);
//     $main_query = mysqli_stmt_get_result($stmt);


//     $values = [];

//     if ($main_query) {
//         $rows = mysqli_fetch_all($main_query, MYSQLI_ASSOC);

//         // Add extra data to each row
//         // add query per user data
//         foreach ($rows as &$row) {
//             // Fetch comptency count and formatted list
//             $subject_sql = "SELECT 
//                     CONCAT(
//                         COUNT(DISTINCT fs.favourite_subject), 
//                         ' [', 
//                         GROUP_CONCAT(DISTINCT fs.favourite_subject ORDER BY fs.favourite_subject SEPARATOR ', '), 
//                         ']'
//                     ) AS favourite_subjects,
//                     DATE_FORMAT(MIN(cim.createdAt), '%d-%b-%Y') AS createdAt
//                 FROM candidateInterviewMapping cim
//                 LEFT JOIN favourite_subject fs ON fs.id = cim.subject
//                 WHERE cim.subject IS NOT NULL
//                 AND cim.emailId = ?;";

//             $subject_stmt = mysqli_prepare($databaseConnection, $subject_sql);
//             mysqli_stmt_bind_param($subject_stmt, "s", $row['emailId']);
//             mysqli_stmt_execute($subject_stmt);
//             $subject_result = mysqli_stmt_get_result($subject_stmt);
//             $subject_row = mysqli_fetch_assoc($subject_result);


//             $row['competency'] = $subject_row['favourite_subjects'] ?? '0';
//             $row['practiceStartDate'] = $subject_row['createdAt'] ?? NULL;

//             // practiceDuration
//             $practiceDuration_sql = "SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(m.totalTime)) + SUM(TIME_TO_SEC(vwd.prwatchDuration)) + SUM(TIME_TO_SEC(vwd.psWatchDuration)) + SUM(TIME_TO_SEC(vwd.gvWatchDuration))) as duration
//                 FROM mergedVideos m
//                 inner join video_watched_details vwd on
//                     vwd.mergeId = m.mergeId
//                 inner join interview i on
//                     i.id = m.interviewId
//                 WHERE m.candidateId = ?";

//             $practiceDuration_stmt = mysqli_prepare($databaseConnection, $practiceDuration_sql);
//             mysqli_stmt_bind_param($practiceDuration_stmt, "i", $row['candidateId']);
//             mysqli_stmt_execute($practiceDuration_stmt);
//             $practiceDuration_result = mysqli_stmt_get_result($practiceDuration_stmt);
//             $practiceDuration_row = mysqli_fetch_assoc($practiceDuration_result);

//             $row['practiceDuration'] = $practiceDuration_row['duration'] ?? '0';

//             // bestScore
//             $bestScore_sql = "SELECT MAX(dk_score) as bestScore
//                 FROM feedback_request fr 
//                 WHERE 
//                     dk_score IS NOT NULL
//                     AND candidateId = ?";

//             $bestScore_stmt = mysqli_prepare($databaseConnection, $bestScore_sql);
//             mysqli_stmt_bind_param($bestScore_stmt, "i", $row['candidateId']);
//             mysqli_stmt_execute($bestScore_stmt);
//             $bestScore_result = mysqli_stmt_get_result($bestScore_stmt);
//             $bestScore_row = mysqli_fetch_assoc($bestScore_result);

//             $row['bestScore'] = $bestScore_row['bestScore'] ?? '0';


//             // assign Message
//             $assignMessage_sql = "SELECT IF(COUNT(*) > 0, 'Yes', 'No') AS assignMessage
//             From watiLogs
//             WHERE 
//                 type = 'praticeInvite'
//                 AND template IN('practice_interview_assign_partner','car_reset')
//                 AND mobileNumber = ?
//                 AND preInterviewId = ?
//             ORDER BY id DESC";

//             $assignMessage_stmt = mysqli_prepare($databaseConnection, $assignMessage_sql);
//             mysqli_stmt_bind_param($assignMessage_stmt, "ii", $row['mobileNumber'], $row['preInterviewId']);
//             mysqli_stmt_execute($assignMessage_stmt);
//             $assignMessage_result = mysqli_stmt_get_result($assignMessage_stmt);
//             $assignMessage_row = mysqli_fetch_assoc($assignMessage_result);

//             $row['assignMessage'] = $assignMessage_row['assignMessage'] ?? '0';


//             // bestScore
//             $candidateStatus_sql = "SELECT 
//                 COUNT(*) AS applied,
//                 SUM(candidateStatus = 'Client Shortlisted') AS client_shortlisted_count,
//                 SUM(candidateStatus IN ('Offered', 'Offer Drop', 'Offer Accepted', 'Joined')) AS offered_count
//             FROM interviewSchedule
//             WHERE 
//                 submissionFlag = 'Y'
//                 AND emailId = ?";

//             // echo $candidateStatus_sql;

//             $candidateStatus_stmt = mysqli_prepare($databaseConnection, $candidateStatus_sql);
//             mysqli_stmt_bind_param($candidateStatus_stmt, "s", $row['emailId']);
//             mysqli_stmt_execute($candidateStatus_stmt);
//             $candidateStatus_result = mysqli_stmt_get_result($candidateStatus_stmt);
//             $candidateStatus_row = mysqli_fetch_assoc($candidateStatus_result);

//             $row['applied_count'] = $candidateStatus_row['applied'] ?? '0';
//             $row['client_shortlisted_count'] = $candidateStatus_row['client_shortlisted_count'] ?? '0';
//             $row['offered_count'] = $candidateStatus_row['offered_count'] ?? '0';




//             // Recommended Jobs
//             // $recommendedJobs_sql = "SELECT
//             //     jobMatch(?, pr.id) AS jobMatch,
//             //     c.id,
//             //     CASE
//             //         WHEN (c.id = 0 OR c.id IS NULL) THEN pr.interviewName
//             //         WHEN pr.interviewName IS NOT NULL THEN pr.interviewName
//             //         ELSE c.name
//             //     END AS `name`,
//             //     pr.productId AS productId,
//             //     st.sector AS sectorId,
//             //     pr.targetAudience AS targetAudience,
//             //     pr.duration AS duration,
//             //     pr.categoryType AS categoryType,
//             //     pr.interviewLevel AS interviewLevel,
//             //     st.assessmenttype AS assessmenttype,
//             //     pr.id AS preInterviewId,
//             //     CASE
//             //         WHEN pr.interviewExpireDate >= NOW() OR pr.interviewExpireDate IS NULL THEN 'Active'
//             //         ELSE 'Inactive'
//             //     END AS status,
//             //     CASE
//             //         WHEN st.preInterviewId IS NULL AND pr.jobCategory IN ('interview') THEN 'dummy'
//             //         ELSE 'real'
//             //     END AS intCat,
//             //     pp.fieldValue AS jobWorkExperience,
//             //     pp2.fieldValue AS jobLocation
//             // FROM preInterview pr
//             // LEFT JOIN `scps_transaction` st ON st.preInterviewId = pr.id
//             // LEFT JOIN aspiration_company c ON st.company = c.id
//             // LEFT JOIN sector s ON s.id = st.sector
//             // LEFT JOIN profilePreferences pp ON pr.id = pp.preInterviewId AND pp.fieldName = 'workExperience'
//             // LEFT JOIN profilePreferences pp2 ON pr.id = pp2.preInterviewId AND pp2.fieldName = 'currentLocation'
//             // WHERE
//             //     pr.publish = 'Y'
//             //     AND (pr.interviewExpireDate >= NOW())
//             //     AND pr.serviceType != 'IAS'
//             //     AND pr.interviewStatus IN ('Active')
//             //     AND jobMatch(?, pr.id) = 'YES'
//             // GROUP BY pr.id
//             // ORDER BY jobMatch DESC";


//             // TODO temp change
//             // $recommendedJobs_stmt = mysqli_prepare($databaseConnection, $recommendedJobs_sql);
//             // mysqli_stmt_bind_param($recommendedJobs_stmt, "ss", $row['emailId'], $row['emailId']);
//             // mysqli_stmt_execute($recommendedJobs_stmt);
//             // $recommendedJobs_result = mysqli_stmt_get_result($recommendedJobs_stmt);

//             // $recommendedJobs = [];

//             // while ($job = mysqli_fetch_assoc($recommendedJobs_result)) {
//             //     $recommendedJobs[] = $job;
//             // }

//             // $row['recommended_jobs'] = $recommendedJobs;
//             // $row['recommended_jobs_count'] = count($recommendedJobs);

//             $row['recommended_jobs'] = [];
//             $row['recommended_jobs_count'] = 22;

//         }

//         $report_sql = "SELECT
//         (SELECT COUNT(DISTINCT cim_sub.emailId)
//             FROM candidateInterviewMapping cim_sub
//             LEFT JOIN preInterview pr_sub ON pr_sub.id = cim_sub.preInterviewId
//             WHERE pr_sub.interviewType = 'Practice'
//             AND cim_sub.source = 'car'
//             AND pr_sub.college_id = ?) AS candidates_invited,

//         (SELECT COUNT(DISTINCT u.id)
//             FROM users u
//             JOIN candidateInterviewMapping cim ON u.emailId = cim.emailId
//             JOIN preInterview pr ON pr.id = cim.preInterviewId
//             WHERE pr.interviewType = 'Practice'
//             AND cim.source = 'car'
//             AND pr.college_id = ?) AS candidates_signed_in,

//         (SELECT COUNT(DISTINCT fr.candidateId)
//             FROM feedback_request fr
//             JOIN candidateInterviewMapping cim ON fr.preInterviewId = cim.preInterviewId AND fr.candidateId = cim.candidateId
//             JOIN preInterview pr ON pr.id = cim.preInterviewId
//             WHERE pr.interviewType = 'Practice'
//             AND cim.source = 'car'
//             AND pr.college_id = ?) AS candidates_practiced,
//             (SELECT
//             CONCAT(
//                 IF(TIME_FORMAT(SEC_TO_TIME(total_seconds), '%H') + 0 > 0,
//                 CONCAT(TIME_FORMAT(SEC_TO_TIME(total_seconds), '%H') + 0, ' hour '),
//                 ''
//                 ),
//                 TIME_FORMAT(SEC_TO_TIME(total_seconds), '%i') + 0,
//                 ' minutes (',
//                 FLOOR(total_seconds / 60),
//                 ' minutes)'
//             ) AS formatted_duration
//             FROM (
//             SELECT
//                 SUM(TIME_TO_SEC(m.totalTime)) + 
//                 SUM(TIME_TO_SEC(vwd.prwatchDuration)) + 
//                 SUM(TIME_TO_SEC(vwd.psWatchDuration)) + 
//                 SUM(TIME_TO_SEC(vwd.gvWatchDuration)) AS total_seconds
//             FROM mergedVideos m
//             INNER JOIN video_watched_details vwd ON vwd.mergeId = m.mergeId
//             JOIN users u ON u.id = m.candidateId
//             JOIN candidateInterviewMapping cim ON cim.emailId = u.emailId
//             JOIN preInterview pr ON pr.id = cim.preInterviewId
//             WHERE pr.interviewType = 'Practice'
//             AND cim.source = 'car'
//             AND pr.college_id = ?) AS time ) AS totalPracticeDuration,

//         (SELECT GROUP_CONCAT(candidateName ORDER BY topScore DESC SEPARATOR ', ')
//             FROM (
//                 SELECT u.firstName AS candidateName, MAX(fr.intScore) AS topScore
//                 FROM feedback_request fr
//                 JOIN users u ON u.id = fr.candidateId
//                 JOIN preInterview pr ON pr.id = fr.preInterviewId
//                 WHERE pr.interviewType = 'Practice'
//                 AND pr.college_id = ?
//                 GROUP BY fr.candidateId
//                 ORDER BY topScore DESC
//                 LIMIT 3
//             ) AS leaderboard) AS leaderboard_top_3";

//         $report_stmt = mysqli_prepare($databaseConnection, $report_sql);
//         for ($i = 1; $i <= 5; $i++) {
//             mysqli_stmt_bind_param($report_stmt, str_repeat("i", 5), $collegeId, $collegeId, $collegeId, $collegeId, $collegeId);
//         }
//         mysqli_stmt_execute($report_stmt);
//         $report_result = mysqli_stmt_get_result($report_stmt);
//         $report_data = mysqli_fetch_assoc($report_result);

//         // Include this in final response
//         $report_summary = $report_data ?? [
//             'candidates_invited' => 0,
//             'candidates_signed_in' => 0,
//             'candidates_practiced' => 0,
//             'totalPracticeDuration' => '00:00:00',
//             'leaderboard_top_3' => ''
//         ];


//         $values = $rows;

//         $to_encode = [
//             'result' => 'success',
//             'status' => 1,
//             'data' => $values,
//             'report' => $report_summary,
//             'message' => 'data found'
//         ];
//     } else {
//         $to_encode = [
//             'result' => 'error',
//             'status' => 0,
//             'message' => 'no data found'
//         ];
//     }

//     echo json_encode($to_encode);
// }
else if (isset($_GET['getCanalyticsData'])) {
    $data = file_get_contents("php://input");
    $json = json_decode($data, true);

    if (!isset($json['userId'])) {
        echo json_encode([
            'result' => 'error',
            'status' => 0,
            'message' => 'Invalid request parameters'
        ]);
        exit();
    }

    $userId = intval($json['userId']);

    $from = $json['from'];
    $to = $json['to'];


    $main_sql =
        "SELECT 
        rr.id AS aoe_id,
        rr.name AS aoe, 
        comp.id AS competency_id,
        comp.favourite_subject AS competency,
        COUNT(DISTINCT pr.id) AS jobs_posted,
        COUNT(DISTINCT CASE 
            WHEN FIND_IN_SET(comp.id, pd.subjectId) > 0 THEN pd.candidateId 
        END) AS job_seekers,
        COUNT(DISTINCT CASE 
            WHEN isc.candidateStatus IS NOT NULL THEN isc.emailId 
        END) AS job_applicants,
        COUNT(DISTINCT CASE 
            WHEN isc.candidateStatus IN ('Profile Match', 'Interview Scheduled', 'Client Shortlisted', 'Profile Shared') THEN isc.emailId 
        END) AS job_matches,
        COUNT(DISTINCT CASE 
            WHEN isc.candidateStatus = 'Client Shortlisted' THEN isc.emailId 
        END) AS client_shortlists
    FROM favourite_subject comp
    LEFT JOIN role_subject rsmap ON comp.id = rsmap.subjectId
    LEFT JOIN relavant_role rr ON rr.id = rsmap.roleId
    LEFT JOIN preInterview pr ON pr.subjectId = comp.id AND pr.interviewType = 'job'
    LEFT JOIN interviewSchedule isc ON isc.preInterviewId = pr.id
    LEFT JOIN professionaldetails pd ON FIND_IN_SET(comp.id, pd.subjectId) > 0
    WHERE comp.subjectType = 'competency' "
        . ($from && $to ? " AND DATE(pr.createdAt) BETWEEN '$from' AND '$to' " : " ") .
        " AND pr.id IS NOT NULL
    GROUP BY comp.id, rr.name, comp.favourite_subject";

    // echo $main_sql;
    // exit();

    $stmt = mysqli_prepare($databaseConnection, $main_sql);
    mysqli_stmt_execute($stmt);
    $main_query = mysqli_stmt_get_result($stmt);

    if ($main_query) {
        $rows = mysqli_fetch_all($main_query, MYSQLI_ASSOC);
        $values = $rows;

        $to_encode = [
            'result' => 'success',
            'status' => 1,
            'data' => $values,
            'message' => 'data found'
        ];
    } else {
        $to_encode = [
            'result' => 'error',
            'status' => 0,
            'message' => 'no data found'
        ];
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['getUserDetails'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        try {
            $userId = getDecrypt($json['userData'])->userId;


            $getUserDetails = "select * from users where id  in ('" . $userId . "');";
            $getUserDetailsQuery = mysqli_query($databaseConnection, $getUserDetails);
            $UserDetailsResult = mysqli_fetch_assoc($getUserDetailsQuery);
            if ($UserDetailsResult >= 0) {

                $to_encode = array(
                    'data' => $UserDetailsResult,
                    'result' => "Success",
                    'status' => "1"
                );

            } else {
                $to_encode = array(
                    'result' => "error",
                    'errorCode' => "User Creation failed.",
                    'status' => -1
                );
            }
        } catch (Exception $e) {
            if ($e->getMessage() == "invalidField") {
                $to_encode = array(
                    'result' => $e->getMessage(),
                    'errorCode' => "field not valid",
                    'status' => "-99",
                );
            } else {
                $to_encode = array(
                    'result' => "error",
                    'errorCode' => "user Id does not exist.",
                    'status' => "-70",
                    'msg' => $e->getMessage(),
                );
            }
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'errorCode' => "User Creation failed.",
            'status' => 0
        );
    }

    echo json_encode($to_encode);
} elseif (isset($_GET['setUserMobileNumber'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    if (isset($json['mobileNumber']) && isset($json['candidateId'])) {
        try {



            $userId = $json['candidateId'];
            $mobileNumber = $json['mobileNumber'];

            // Enhanced sanitization: Remove all characters except digits and +
            $sanitizedMobileNumber = preg_replace('/[^\d+]/', '', $mobileNumber);

            // Validate phone number format: optional country code (1-3 digits with optional +) followed by 10 digits
            if (!preg_match('/^(\+?\d{1,3})?\d{10}$/', $sanitizedMobileNumber)) {
                throw new Exception("invalidField");
            }

            // Check if mobile number is empty after sanitization
            if (empty($sanitizedMobileNumber)) {
                throw new Exception("invalidField");
            }

            // Securely update user's mobile number
            $updateQuery = "UPDATE users SET mobileNumber = ? WHERE id = ?";
            $stmt = mysqli_prepare($databaseConnection, $updateQuery);
            mysqli_stmt_bind_param($stmt, "si", $sanitizedMobileNumber, $userId);
            $updateSuccess = mysqli_stmt_execute($stmt);
            mysqli_stmt_close($stmt);

            if (!$updateSuccess) {
                throw new Exception("Failed to update mobile number.");
            }

            // Fetch user details after update
            $getUserDetailsQuery = "SELECT * FROM users WHERE id = ?";
            $stmt = mysqli_prepare($databaseConnection, $getUserDetailsQuery);
            mysqli_stmt_bind_param($stmt, "i", $userId);
            mysqli_stmt_execute($stmt);
            $result = mysqli_stmt_get_result($stmt);
            $UserDetailsResult = mysqli_fetch_assoc($result);
            mysqli_stmt_close($stmt);

            if ($UserDetailsResult) {
                $response = [
                    'data' => $UserDetailsResult,
                    'result' => "Success",
                    'status' => 1
                ];
            } else {
                throw new Exception("User not found.");
            }

        } catch (Exception $e) {
            $response = [
                'result' => "error",
                'errorCode' => $e->getMessage() === "invalidField" ? "field not valid" : "User ID does not exist.",
                'status' => -70,
                'msg' => $e->getMessage(),
            ];
        }
    } else {
        $response = [
            'result' => "error",
            'errorCode' => "Invalid input data.",
            'status' => 0
        ];
    }

    echo json_encode($response);
}
// node-api
elseif (isset($_GET['subscriptionPlanEnquiry'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    if (isset($json['mobileNumber']) && isset($json['emailId'])) {
        $to = "info@goprac.com";
        // $to = "sourabh13689@gmail.com";
        // $to = "sourabh@goprac.com";
        $subjects = "Subscription plan enquiry";
        $messages = "Dear Admin,\n"
                . "There is a subscription plan enquiry from:\n"
                . "Email: " . $json['emailId'] . "\n"
                . "Mobile Number: " . $json['mobileNumber'] . "\n"
                . "Thanks.";
        // Send the email
        sendEmailToUser($to, null, $subjects, $messages);

        $response = [
            'result' => "success",
            'errorCode' => "0",
            'status' => 0
        ];
    } else {
        $response = [
            'result' => "error",
            'errorCode' => "Invalid input data.",
            'status' => 0
        ];
    }

    echo json_encode($response);
}


// elseif (isset($_GET['saveInJobMailList'])) {
//     $data = @file_get_contents("php://input");
//     $json = json_decode($data, true);

//     if (
//         isset($json['instituteName']) &&
//         isset($json['emailId']) &&
//         isset($json['whatsappNumber']) &&
//         isset($json['experienceRange'])
//     ) {
//         $instituteName = mysqli_real_escape_string($databaseConnection, $json['instituteName']);
//         $emailId = mysqli_real_escape_string($databaseConnection, $json['emailId']);
//         $mobileNumber = mysqli_real_escape_string($databaseConnection, $json['whatsappNumber']);
//         $expRange = mysqli_real_escape_string($databaseConnection, $json['experienceRange']);

//         // Insert into JobMailList
//         $sql = "INSERT INTO JobMailList (contactType, name, expRange, mobileNumber, emailId) 
//                 VALUES ('Institute', ?, ?, ?, ?)";

//         $stmt = mysqli_prepare($databaseConnection, $sql);
//         mysqli_stmt_bind_param($stmt, "ssss", $instituteName, $expRange, $mobileNumber, $emailId);
//         $result = mysqli_stmt_execute($stmt);

//         // Send the email
//         $to = "info@goprac.com";
//         //   $to = "sourabh13689@gmail.com";
//         $subjects = "New Institute Registration (Job Mail List)";
//         $messages = "Dear Admin,\n\n".
//                     "A new institute has registered interest:\n\n".
//                     "Institute Name: $instituteName\n".
//                     "Email ID: $emailId\n".
//                     "WhatsApp Number: $mobileNumber\n".
//                     "Experience Range: $expRange\n\n".
//                     "Thanks,\nGoprac";

//         sendEmailToUser($to, null, $subjects, $messages);

//         if ($result) {
//             $response = [
//                 'result' => "success",
//                 'errorCode' => "0",
//                 'status' => 0
//             ];
//         } else {
//             $response = [
//                 'result' => "error",
//                 'errorCode' => "Database insertion failed.",
//                 'status' => 0
//             ];
//         }
//     } else {
//         $response = [
//             'result' => "error",
//             'errorCode' => "Missing or invalid input data.",
//             'status' => 0
//         ];
//     }

//     echo json_encode($response);
// }

// node-api
elseif (isset($_GET['saveInJobMailList'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    if (!empty($json['website'] ?? '')) {
        error_log("Bot detected - honeypot filled (saveInJobMailList): " . json_encode($json));
        $response = [
            'result' => "success",
            'errorCode' => "0",
            'status' => 0
        ];
        header('Content-Type: application/json');
        echo json_encode($response);
        exit;
    }

    $nameInput = isset($json['instituteName']) ? $json['instituteName'] : (isset($json['fullName']) ? $json['fullName'] : null);

    // 1) Validate input
    if (
        isset($nameInput) &&
        isset($json['emailId']) &&
        isset($json['whatsappNumber'])
    ) {
        $instituteName = mysqli_real_escape_string($databaseConnection, $nameInput);
        $emailId       = mysqli_real_escape_string($databaseConnection, $json['emailId']);
        $mobileNumber  = mysqli_real_escape_string($databaseConnection, $json['whatsappNumber']);
        $contactType   = "College";
        $msg = isset($json['msg']) ? trim($json['msg']) : "";
        $contactName = isset($json['contactName']) ? mysqli_real_escape_string($databaseConnection, trim($json['contactName'])) : "";

        if (trim($instituteName) === "") {
            $response = [
                'result'    => "error",
                'errorCode' => "Missing or invalid input data. Required: instituteName/fullName",
                'status'    => 0
            ];
            header('Content-Type: application/json');
            echo json_encode($response);
            exit;
        }

        // 2) Generate a unique 6-digit code
        do {
            $uniqueCode = strval(mt_rand(100000, 999999));
            $checkStmt = mysqli_prepare(
                $databaseConnection,
                "SELECT 1 FROM JobMailList WHERE instituteCode = ? LIMIT 1"
            );
            mysqli_stmt_bind_param($checkStmt, "s", $uniqueCode);
            mysqli_stmt_execute($checkStmt);
            mysqli_stmt_store_result($checkStmt);
            $collision = mysqli_stmt_num_rows($checkStmt) > 0;
            mysqli_stmt_close($checkStmt);
        } while ($collision);

        // 3) Insert (or no-op if email already exists)
        $sql = "
            INSERT INTO JobMailList
                (contactType, name, contactName, mobileNumber, emailId, instituteCode, msg)
            VALUES
                (?, ?, ?, ?, ?, ?, ?)
            ON DUPLICATE KEY
                UPDATE instituteCode = instituteCode, contactName = VALUES(contactName), msg = VALUES(msg)
        ";
        $stmt = mysqli_prepare($databaseConnection, $sql);
        mysqli_stmt_bind_param(
            $stmt,
            "sssssss",
            $contactType,
            $instituteName,
            $contactName,
            $mobileNumber,
            $emailId,
            $uniqueCode,
            $msg
        );
        $ok = mysqli_stmt_execute($stmt);
        mysqli_stmt_close($stmt);

        if ($ok) {
            $response = [
                'result'    => "success",
                'errorCode' => "0",
                'status'    => 0,
                'code'      => $uniqueCode,
                'data'      => [
                    'instituteName' => $instituteName,
                    'contactName' => $contactName,
                    'msg' => $msg
                ]
            ];

            // Convert to JSON early
            $json = json_encode($response);

            // Send response headers
            header('Content-Type: application/json');
            header('Connection: close');
            header('Content-Length: ' . strlen($json));
            ob_end_clean(); // Clean any previous output buffer

            // Send and flush response immediately
            echo $json;
            flush();

            // Let client disconnect but continue server execution
            if (function_exists('ignore_user_abort')) {
                ignore_user_abort(true);
            }

            // Continue in background (async-like)
            // Use a new process or thread if possible

            // Email sending after response
            // $to      = "sourabh13689@gmail.com";
            $to      = "info@goprac.com";
            $subject = "New Institute Registration (Job Mail List)";
            $message = "Dear Admin,\n\n"
                    . "A new institute has registered interest:\n\n"
                    . "Institute Name:     $instituteName\n"
                    . "Contact Name:       $contactName\n"
                    . "Email ID:          $emailId\n"
                    . "WhatsApp Number:   $mobileNumber\n"
                    . "Message:          $msg\n"
                    . "Institute Code:    $uniqueCode\n\n"
                    . "Thanks,\nGoprac";

            // Send email
            sendEmailToUser($to, null, $subject, $message);
            exit;
        } else {
            $response = [
                'result'    => "error",
                'errorCode' => "Database insertion failed: " . mysqli_error($databaseConnection),
                'status'    => 0
            ];
        }
    } else {
        $response = [
            'result'    => "error",
            'errorCode' => "Missing or invalid input data. Required: instituteName, emailId, whatsappNumber",
            'status'    => 0
        ];
    }

    header('Content-Type: application/json');
    echo json_encode($response);
    exit;
}


elseif (isset($_GET['checkInstituteCode'])) {
    // Read and decode the JSON payload
    $data = file_get_contents("php://input");
    $json = json_decode($data, true);

    header('Content-Type: application/json');

    if (empty($json['instituteCode'])) {
        http_response_code(400);
        echo json_encode([
            'error' => 'Missing instituteCode'
        ]);
        exit;
    }

    $instituteCode = mysqli_real_escape_string(
        $databaseConnection,
        trim($json['instituteCode'])
    );

    // Check if code exists in JobMailList
    $sql = "SELECT 1 
              FROM JobMailList 
             WHERE instituteCode = ? 
             LIMIT 1";
    $stmt = mysqli_prepare($databaseConnection, $sql);
    mysqli_stmt_bind_param($stmt, "s", $instituteCode);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_store_result($stmt);

    $exists = (mysqli_stmt_num_rows($stmt) > 0);

    mysqli_stmt_close($stmt);

    // Return JSON
    echo json_encode([
        'exists' => $exists
    ]);
    exit;
}
// Practice Invitation Dashboard
// node-api
else if (isset($_GET['getPracticeInvitationAddEmails'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    if (!isset($json['preInterviewId'])) {
        echo json_encode([
            'result' => 'error',
            'status' => 0,
            'message' => 'Invalid request parameters'
        ]);
        exit();
    }


    $emails = $json['emails'];
    $preInterviewId = $json['preInterviewId'];
    $inviteCode = isset($json['inviteCode']) && $json['inviteCode'] !== '' ? $json['inviteCode'] : null;
    $subjectId = "";
    $roleId = "";

    if (!empty($preInterviewId)) {
        $preInterview = "SELECT st.subject from scps_transaction st inner join preInterview pr ON pr.id=st.preInterviewId where pr.interviewType = 'Practice' and pr.id IN (" . $preInterviewId . ") group by st.subject";
        $preInterviewResult = mysqli_query($databaseConnection, $preInterview);

        if ($preInterviewResult) {
            $row1 = mysqli_fetch_assoc($preInterviewResult);
            if ($row1) {
                $subjectId = $row1['subject'];
            }
        }
    }

    if (!empty($subjectId)) {
        $role = "SELECT roleId FROM role_subject where subjectId IN ($subjectId)";
        $roleResult = mysqli_query($databaseConnection, $role);

        if ($roleResult) {
            $row = mysqli_fetch_assoc($roleResult);
            if ($row) {
                $roleId = $row['roleId'];
            }
        }
    }

    if ($subjectId) {
        $sql = "SELECT id, favourite_subject FROM favourite_subject WHERE id IN (" . $subjectId . ") ";
        $subject_query = mysqli_query($databaseConnection, $sql);
        $subjectResult = mysqli_fetch_all($subject_query, MYSQLI_ASSOC);
        $subjectName = $subjectResult[0]['favourite_subject'];

    } else {
        $subjectName = "";
    }

    if ($roleId) {
        $sql1 = "SELECT id, name as roleName FROM relavant_role WHERE id IN (" . $roleId . ") ";
        $role_query = mysqli_query($databaseConnection, $sql1);
        $role_queryResult = mysqli_fetch_all($role_query, MYSQLI_ASSOC);
        $roleName = $role_queryResult[0]['roleName'];
    } else {
        $roleName = "";
    }

    if (is_array($emails) && count($emails) > 0) {

        $values = [];
        $stmt = $databaseConnection->prepare("INSERT INTO candidateInterviewMapping (emailId, mobileNumber, candidateName, preInterviewId, inviteDate, role, subject, source, code, access) VALUES (?, ?, ?, ?, NULL, ?, ?, 'invite_code', ?, 'i')");

        foreach ($emails as $entry) {
            [$candidateName, $email, $mobileNumber] = $entry;

            if ($inviteCode === null) {
                $checkQuery = "SELECT id FROM candidateInterviewMapping WHERE source='invite_code' AND emailId = ? AND preInterviewId = ? AND (code IS NULL OR code = '')";
            $stmtCheck = $databaseConnection->prepare($checkQuery);
                $stmtCheck->bind_param("si", $email, $preInterviewId);
            } else {
                $checkQuery = "SELECT id FROM candidateInterviewMapping WHERE source='invite_code' AND emailId = ? AND preInterviewId = ? AND code= ?";
                $stmtCheck = $databaseConnection->prepare($checkQuery);
                $stmtCheck->bind_param("sis", $email, $preInterviewId, $inviteCode);
            }
            $stmtCheck->execute();
            $resultCheck = $stmtCheck->get_result();
            $rowCheck = $resultCheck->fetch_assoc();
            $stmtCheck->close();


            if ($rowCheck === null) {
                // Insert new record with inviteDate=NULL
                $roleIdValue = !empty($roleId) ? $roleId : null;
                $subjectIdValue = !empty($subjectId) ? $subjectId : null;
                if ($inviteCode === null) {
                    $stmt->bind_param("sssiiis", $email, $mobileNumber, $candidateName, $preInterviewId, $roleIdValue, $subjectIdValue, $inviteCode);
                } else {
                    $stmt->bind_param("sssiiis", $email, $mobileNumber, $candidateName, $preInterviewId, $roleIdValue, $subjectIdValue, $inviteCode);
                }
                $stmt->execute();
                $values[] = ["email" => $email, "status" => "Inserted"];
            } else {
                // Update existing record: set inviteDate=NULL for re-invite
                $updateStmt = $databaseConnection->prepare("UPDATE candidateInterviewMapping SET inviteDate = NULL WHERE id = ?");
                $updateStmt->bind_param("i", $rowCheck['id']);
                $updateStmt->execute();
                $updateStmt->close();
                $values[] = ["email" => $email, "status" => "Updated (re-invite)"];
                
                // send mail
                // $to = $email;
                // $to = "sourabh13689@gmail.com";
                // $subjects = "Practice Interview Assigned";
                // $messages = "<p>Hi " . $candidateName . ",</p>
                // <p>We have received your request to enhance your aptitude in <strong>" . $roleName . "</strong> and are excited to take it forward.<br>
                // You can start your problem-solving practice session anytime that suits you.</p>
                // <p>Please find the link to proceed 👉 <a href='https://www.goprac.com/job?p=" . $preInterviewId . "'>Start Practice</a></p>
                // <p>Each practice session lasts for <strong>15 minutes</strong>.<br>
                // For assistance, reach us at <strong>+91 6360060622</strong>.</p>
                // Let’s build your skills together!<br>
                // <p>Best regards,<br>
                // Nitin Rakesh Prasad<br>
                // Founder - GoPrac</p>";
                // Send the email
                // sendEmailToUser($to, null, $subjects, $messages);
            }
        }

        $stmt->close();
    } else {
        $values = ["error" => "No valid emails provided"];
    }

    echo json_encode($values);
}
// Job Invitation Dashboard - Sync candidate + restricted access check for Job IAS
else if (isset($_GET['syncJobInviteCandidate'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    if (!isset($json['userId']) || !isset($json['preInterviewId'])) {
        echo json_encode([
            'result' => 'error',
            'status' => 0,
            'allowed' => false,
            'message' => 'userId and preInterviewId are required'
        ]);
        exit();
    }

    $userId = intval($json['userId']);
    $preInterviewId = trim((string)$json['preInterviewId']);

    if ($userId <= 0 || $preInterviewId === '') {
        echo json_encode([
            'result' => 'error',
            'status' => 0,
            'allowed' => false,
            'message' => 'Invalid userId or preInterviewId'
        ]);
        exit();
    }

    $safePreInterviewId = mysqli_real_escape_string($databaseConnection, $preInterviewId);

    $preMetaQuery = mysqli_query(
        $databaseConnection,
        "SELECT id, interviewType, serviceType, RestrictedOnly
         FROM preInterview
         WHERE id = '" . $safePreInterviewId . "'
         LIMIT 1"
    );

    if (!$preMetaQuery || mysqli_num_rows($preMetaQuery) === 0) {
        echo json_encode([
            'result' => 'error',
            'status' => 0,
            'allowed' => false,
            'message' => 'Invalid preInterviewId'
        ]);
        exit();
    }

    $preMeta = mysqli_fetch_assoc($preMetaQuery);
    $isJobType = strtolower(trim((string)($preMeta['interviewType'] ?? ''))) === 'job';
    $isIASService = strtoupper(trim((string)($preMeta['serviceType'] ?? ''))) === 'IAS';
    $isRestricted = strtoupper(trim((string)($preMeta['RestrictedOnly'] ?? ''))) === 'Y';

    if (!$isJobType || !$isIASService) {
        echo json_encode([
            'result' => 'error',
            'status' => 0,
            'allowed' => false,
            'message' => 'syncJobInviteCandidate supports only interviewType=job and serviceType=IAS'
        ]);
        exit();
    }

    $userQuery = mysqli_query(
        $databaseConnection,
        "SELECT emailId, firstName, mobileNumber, usertype
         FROM users
         WHERE id = " . $userId . "
         LIMIT 1"
    );

    if (!$userQuery || mysqli_num_rows($userQuery) === 0) {
        echo json_encode([
            'result' => 'error',
            'status' => 0,
            'allowed' => false,
            'message' => 'User not found'
        ]);
        exit();
    }

    $userRow = mysqli_fetch_assoc($userQuery);
    $userType = strtolower(trim((string)($userRow['usertype'] ?? '')));
    $isAdmin = $userType === 'admin';
    $isCorporate = $userType === 'corporate';

    // Admin should always be allowed for Job + IAS flow, irrespective of invite access row.
    if ($isAdmin) {
        echo json_encode([
            'result' => 'success',
            'status' => 1,
            'allowed' => true,
            'restrictedOnly' => $isRestricted ? 'Y' : null,
            'syncedRows' => 0,
            'scheduleId' => null,
            'access' => null,
            'message' => 'Access granted'
        ]);
        exit();
    }

    // Corporate should be allowed only when assigned to this preInterviewId.
    if ($isCorporate) {
        $corporateAccessQuery = mysqli_query(
            $databaseConnection,
            "SELECT 1
             FROM preInterview_corporate pic
             WHERE pic.preInterviewid = '" . $safePreInterviewId . "'
               AND pic.userId = " . $userId . "
             LIMIT 1"
        );

        if (!$corporateAccessQuery || mysqli_num_rows($corporateAccessQuery) === 0) {
            echo json_encode([
                'result' => 'success',
                'status' => 1,
                'allowed' => false,
                'restrictedOnly' => $isRestricted ? 'Y' : null,
                'syncedRows' => 0,
                'scheduleId' => null,
                'access' => null,
                'message' => 'Access denied for this job invitation.'
            ]);
            exit();
        }

        echo json_encode([
            'result' => 'success',
            'status' => 1,
            'allowed' => true,
            'restrictedOnly' => $isRestricted ? 'Y' : null,
            'syncedRows' => 0,
            'scheduleId' => null,
            'access' => null,
            'message' => 'Access granted'
        ]);
        exit();
    }

    // All other users (including students) follow invite access rules.
    $userEmail = strtolower(trim((string)($userRow['emailId'] ?? '')));
    $userFirstName = trim((string)($userRow['firstName'] ?? ''));
    $userMobileRaw = trim((string)($userRow['mobileNumber'] ?? ''));
    $userMobileDigits = preg_replace('/\D+/', '', $userMobileRaw);
    $userMobileNumber = $userMobileDigits !== '' ? $userMobileDigits : null;

    if ($userEmail === '') {
        echo json_encode([
            'result' => 'error',
            'status' => 0,
            'allowed' => false,
            'message' => 'User email not found'
        ]);
        exit();
    }

    $safeEmail = mysqli_real_escape_string($databaseConnection, $userEmail);
    $safeFirstName = mysqli_real_escape_string($databaseConnection, $userFirstName);
    $safeUserMobile = $userMobileNumber !== null ? mysqli_real_escape_string($databaseConnection, $userMobileNumber) : null;
    $safeUserMobileSql = $safeUserMobile !== null ? "'" . $safeUserMobile . "'" : "NULL";

    $syncCandidateSql = "UPDATE interviewSchedule
        SET
            candidate_id = CASE
                WHEN candidate_id IS NULL OR candidate_id = 0 THEN " . $userId . "
                ELSE candidate_id
            END,
            candidateName = CASE
                WHEN '" . $safeFirstName . "' <> ''
                     AND (
                        candidateName IS NULL
                        OR TRIM(candidateName) = ''
                        OR LOWER(TRIM(candidateName)) = LOWER('" . $safeEmail . "')
                     )
                THEN '" . $safeFirstName . "'
                ELSE candidateName
            END,
            mobileNumber = CASE
                WHEN " . $safeUserMobileSql . " IS NOT NULL
                     AND (
                        mobileNumber IS NULL
                        OR TRIM(CAST(mobileNumber AS CHAR)) = ''
                     )
                THEN " . $safeUserMobileSql . "
                ELSE mobileNumber
            END
        WHERE preInterviewId = '" . $safePreInterviewId . "'
          AND emailId = '" . $safeEmail . "'";
    $syncOk = mysqli_query($databaseConnection, $syncCandidateSql);

    if (!$syncOk) {
        echo json_encode([
            'result' => 'error',
            'status' => 0,
            'allowed' => false,
            'message' => mysqli_error($databaseConnection)
        ]);
        exit();
    }

    $syncedRows = mysqli_affected_rows($databaseConnection);

    $latestScheduleQuery = mysqli_query(
        $databaseConnection,
        "SELECT id, `access`
         FROM interviewSchedule
         WHERE preInterviewId = '" . $safePreInterviewId . "'
           AND emailId = '" . $safeEmail . "'
         ORDER BY id DESC
         LIMIT 1"
    );

    if (!$latestScheduleQuery) {
        echo json_encode([
            'result' => 'error',
            'status' => 0,
            'allowed' => false,
            'message' => mysqli_error($databaseConnection)
        ]);
        exit();
    }

    $scheduleRow = mysqli_fetch_assoc($latestScheduleQuery);
    $scheduleId = $scheduleRow ? intval($scheduleRow['id']) : null;
    $scheduleAccess = $scheduleRow ? strtolower(trim((string)($scheduleRow['access'] ?? ''))) : null;
    $allowed = !$isRestricted || ($scheduleAccess === 'i');

    echo json_encode([
        'result' => 'success',
        'status' => 1,
        'allowed' => $allowed,
        'restrictedOnly' => $isRestricted ? 'Y' : null,
        'syncedRows' => max(0, intval($syncedRows)),
        'scheduleId' => $scheduleId,
        'access' => $scheduleAccess,
        'message' => $allowed ? 'Access granted' : 'Access denied for this job invitation.'
    ]);
}
// Corporate header menu access
else if (isset($_GET['getCorporateMenuAccess'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    if (!isset($json['userId'])) {
        echo json_encode([
            'result' => 'error',
            'status' => 0,
            'message' => 'Invalid request parameters',
            'hasIasAccess' => false,
            'hasPracticeAccess' => false
        ]);
        exit();
    }

    $userId = intval($json['userId']);

    $userInfo = mysqli_query(
        $databaseConnection,
        "SELECT usertype FROM users WHERE id = " . $userId . " LIMIT 1"
    );
    $userType = '';
    if ($userInfo && mysqli_num_rows($userInfo) > 0) {
        $userRow = mysqli_fetch_assoc($userInfo);
        $userType = strtolower(trim((string)$userRow['usertype']));
    }

    if ($userType !== 'corporate') {
        echo json_encode([
            'result' => 'success',
            'status' => 1,
            'hasIasAccess' => false,
            'hasPracticeAccess' => false
        ]);
        exit();
    }

    $iasAccessSql = "SELECT 1
        FROM preInterview_corporate pic
        INNER JOIN preInterview pr ON pr.id = pic.preinterviewId
        WHERE pic.userId = " . $userId . "
          AND pr.serviceType = 'IAS'
        LIMIT 1";

    $practiceAccessSql = "SELECT 1
        FROM preInterview_corporate pic
        INNER JOIN preInterview pr ON pr.id = pic.preinterviewId
        WHERE pic.userId = " . $userId . "
          AND pr.interviewType = 'Practice'
        LIMIT 1";

    $iasAccessQuery = mysqli_query($databaseConnection, $iasAccessSql);
    $practiceAccessQuery = mysqli_query($databaseConnection, $practiceAccessSql);

    echo json_encode([
        'result' => 'success',
        'status' => 1,
        'hasIasAccess' => $iasAccessQuery && mysqli_num_rows($iasAccessQuery) > 0,
        'hasPracticeAccess' => $practiceAccessQuery && mysqli_num_rows($practiceAccessQuery) > 0
    ]);
}
// Job Invitation Dashboard - Filters (interviewType = job, serviceType = IAS)
else if (isset($_GET['getJobInvitationFilters'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    if (!isset($json['userId'])) {
        echo json_encode([
            'result' => 'error',
            'status' => 0,
            'message' => 'Invalid request parameters'
        ]);
        exit();
    }

    $userId = intval($json['userId']);
    $userType = '';
    $userInfo = mysqli_query($databaseConnection, "SELECT usertype FROM users WHERE id = " . $userId . " LIMIT 1");
    if ($userInfo && mysqli_num_rows($userInfo) > 0) {
        $row = mysqli_fetch_assoc($userInfo);
        $userType = strtolower(trim((string)$row['usertype']));
    }

    // Explicitly allow only admin and corporate for this dashboard.
    if ($userType !== 'admin' && $userType !== 'corporate') {
        echo json_encode([
            'result' => 'error',
            'status' => 0,
            'message' => 'Access denied for user type: ' . $userType
        ]);
        exit();
    }

    $jobs_sql = "SELECT DISTINCT
        pr.id,
        pr.interviewName,
        pr.interviewStartDate,
        pr.interviewExpireDate,
        pr.restrictedOnly,
        pr.pendingInterviews,
        pr.createdAt,
        COALESCE(ac.name, '') AS companyName
    FROM preInterview pr
    LEFT JOIN aspiration_company ac ON ac.id = pr.company_id
    WHERE pr.interviewType = 'job'
      AND pr.serviceType = 'IAS'
      AND LOWER(TRIM(COALESCE(pr.interviewStatus, ''))) = 'active'";

    if ($userType === 'corporate') {
        $jobs_sql .= " AND EXISTS (
            SELECT 1
            FROM preInterview_corporate pic
            WHERE pic.preInterviewid = pr.id
              AND pic.userId = " . $userId . "
        )";
    }

    $jobs_sql .= " ORDER BY
        pr.createdAt DESC,
        pr.id DESC";

    $jobs_query = mysqli_query($databaseConnection, $jobs_sql);
    if (!$jobs_query) {
        echo json_encode([
            'result' => 'error',
            'status' => 0,
            'message' => mysqli_error($databaseConnection)
        ]);
        exit();
    }

    $jobs = mysqli_fetch_all($jobs_query, MYSQLI_ASSOC);

    echo json_encode([
        'result' => 'success',
        'status' => 1,
        'jobs' => $jobs
    ]);
}
// Job Invitation Dashboard - Bulk invite by email (interviewSchedule table)
else if (isset($_GET['getJobInvitationAddEmails'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    if (!isset($json['preInterviewId']) || !isset($json['emails']) || !is_array($json['emails'])) {
        echo json_encode([
            'result' => 'error',
            'status' => 0,
            'message' => 'Invalid request parameters'
        ]);
        exit();
    }

    $preInterviewId = trim((string)$json['preInterviewId']);
    $safePreInterviewId = mysqli_real_escape_string($databaseConnection, $preInterviewId);

    $preCheckSql = "SELECT id, company_id
        FROM preInterview
        WHERE id = '" . $safePreInterviewId . "'
          AND interviewType = 'job'
          AND serviceType = 'IAS'
        LIMIT 1";
    $preCheckQuery = mysqli_query($databaseConnection, $preCheckSql);

    if (!$preCheckQuery || mysqli_num_rows($preCheckQuery) === 0) {
        echo json_encode([
            'result' => 'error',
            'status' => 0,
            'message' => 'Invalid preInterview for Job IAS invitation'
        ]);
        exit();
    }

    $preRow = mysqli_fetch_assoc($preCheckQuery);
    $companyId = isset($preRow['company_id']) && $preRow['company_id'] !== null ? intval($preRow['company_id']) : null;

    $emailPattern = '/^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$/';
    $results = [];

    foreach ($json['emails'] as $entry) {
        if (!is_array($entry) || count($entry) < 2) {
            continue;
        }

        $candidateName = trim((string)($entry[0] ?? ''));
        $emailId = strtolower(trim((string)($entry[1] ?? '')));
        $mobileRaw = trim((string)($entry[2] ?? ''));
        $mobileOnlyDigits = preg_replace('/\D+/', '', $mobileRaw);
        $mobileNumber = $mobileOnlyDigits !== '' ? $mobileOnlyDigits : null;

        if ($emailId === '' || !preg_match($emailPattern, $emailId)) {
            $results[] = [
                'email' => $emailId,
                'status' => 'Invalid Email'
            ];
            continue;
        }

        $candidateId = null;
        $userFirstName = '';
        $userMobileNumber = null;
        $safeEmail = mysqli_real_escape_string($databaseConnection, $emailId);
        $candidateQuery = mysqli_query(
            $databaseConnection,
            "SELECT id, firstName, mobileNumber, emailId
             FROM users
             WHERE emailId = '" . $safeEmail . "'
             LIMIT 1"
        );
        if ($candidateQuery && mysqli_num_rows($candidateQuery) > 0) {
            $candidateRow = mysqli_fetch_assoc($candidateQuery);
            $candidateId = intval($candidateRow['id']);
            $userFirstName = trim((string)($candidateRow['firstName'] ?? ''));
            $userMobileRaw = trim((string)($candidateRow['mobileNumber'] ?? ''));
            $userMobileDigits = preg_replace('/\D+/', '', $userMobileRaw);
            $userMobileNumber = $userMobileDigits !== '' ? $userMobileDigits : null;
        }

        if ($candidateName === '' || strtolower($candidateName) === strtolower($emailId)) {
            if ($userFirstName !== '') {
                $candidateName = $userFirstName;
            } else if ($candidateName === '') {
                $candidateName = $emailId;
            }
        }
        if ($mobileNumber === null && $userMobileNumber !== null) {
            $mobileNumber = $userMobileNumber;
        }

        $safeName = mysqli_real_escape_string($databaseConnection, $candidateName);
        $safeMobile = $mobileNumber !== null ? mysqli_real_escape_string($databaseConnection, $mobileNumber) : null;

        $existingQuery = mysqli_query(
            $databaseConnection,
            "SELECT id
             FROM interviewSchedule
             WHERE preInterviewId = '" . $safePreInterviewId . "'
               AND emailId = '" . $safeEmail . "'
             ORDER BY id DESC
             LIMIT 1"
        );

        if ($existingQuery && mysqli_num_rows($existingQuery) > 0) {
            $existingRow = mysqli_fetch_assoc($existingQuery);
            $results[] = [
                'email' => $emailId,
                'status' => 'Already invited (use Resend)',
                'scheduleId' => intval($existingRow['id'])
            ];
        } else {
            $insertSql = "INSERT INTO interviewSchedule (
                    company_id,
                    candidate_id,
                    candidateName,
                    emailId,
                    mobileNumber,
                    preInterviewId,
                    scheduleTime,
                    firstScheduleDate,
                    inviteFlag,
                    submissionFlag,
                    emailed,
                    `access`,
                    detailsStatus,
                    inviteDate,
                    createdAt
                ) VALUES (
                    " . ($companyId !== null ? $companyId : "NULL") . ",
                    " . ($candidateId !== null ? $candidateId : "NULL") . ",
                    '" . $safeName . "',
                    '" . $safeEmail . "',
                    " . ($safeMobile !== null ? "'" . $safeMobile . "'" : "NULL") . ",
                    '" . $safePreInterviewId . "',
                    DATE_ADD(NOW(), INTERVAL 24 HOUR),
                    NOW(),
                    'N',
                    'NA',
                    'N',
                    'i',
                    'open',
                    NOW(),
                    NOW()
                )";

            if (mysqli_query($databaseConnection, $insertSql)) {
                $results[] = [
                    'email' => $emailId,
                    'status' => 'Inserted'
                ];
            } else {
                $results[] = [
                    'email' => $emailId,
                    'status' => 'Error: ' . mysqli_error($databaseConnection)
                ];
            }
        }
    }

    echo json_encode([
        'result' => 'success',
        'status' => 1,
        'data' => $results
    ]);
}
// Job Invitation Dashboard - Candidate-level access toggle
else if (isset($_GET['updateJobInvitationAccess'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    if (!isset($json['scheduleId'])) {
        echo json_encode([
            'result' => 'error',
            'status' => 0,
            'message' => 'scheduleId required'
        ]);
        exit();
    }

    $scheduleId = intval($json['scheduleId']);
    $scheduleAccess = (isset($json['access']) && strtolower(trim((string)$json['access'])) === 'd') ? 'd' : 'i';

    $sqlAccess = "'" . mysqli_real_escape_string($databaseConnection, $scheduleAccess) . "'";

    $updateSql = "UPDATE interviewSchedule
                  SET `access` = " . $sqlAccess . "
                  WHERE id = " . $scheduleId;
    $ok = mysqli_query($databaseConnection, $updateSql);

    $accessStatus = $scheduleAccess === 'i' ? 'active' : 'deleted';

    echo json_encode([
        'result' => $ok ? 'success' : 'error',
        'status' => $ok ? 1 : 0,
        'scheduleId' => $scheduleId,
        'access' => $scheduleAccess,
        'accessStatus' => $accessStatus,
        'message' => $ok ? 'Access updated' : mysqli_error($databaseConnection)
    ]);
}
// Job Invitation Dashboard - Candidate-level resend/reset for invite + reminders
else if (isset($_GET['resendJobInvite'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    if (!isset($json['scheduleId']) || !isset($json['preInterviewId'])) {
        echo json_encode([
            'result' => 'error',
            'status' => 0,
            'message' => 'scheduleId and preInterviewId are required'
        ]);
        exit();
    }

    $scheduleId = intval($json['scheduleId']);
    $preInterviewId = trim((string)$json['preInterviewId']);

    if ($scheduleId <= 0 || $preInterviewId === '') {
        echo json_encode([
            'result' => 'error',
            'status' => 0,
            'message' => 'Invalid scheduleId or preInterviewId'
        ]);
        exit();
    }

    $safePreInterviewId = mysqli_real_escape_string($databaseConnection, $preInterviewId);

    $preCheckSql = "SELECT id
        FROM preInterview
        WHERE id = '" . $safePreInterviewId . "'
          AND interviewType = 'job'
          AND serviceType = 'IAS'
        LIMIT 1";
    $preCheckQuery = mysqli_query($databaseConnection, $preCheckSql);

    if (!$preCheckQuery || mysqli_num_rows($preCheckQuery) === 0) {
        echo json_encode([
            'result' => 'error',
            'status' => 0,
            'message' => 'Invalid preInterview for Job IAS resend'
        ]);
        exit();
    }

    $stateSql = "SELECT
            id,
            LOWER(TRIM(COALESCE(`access`, ''))) AS accessValue,
            COALESCE(inviteFlag, 'N') AS inviteFlag,
            COALESCE(reminderScheduled, 'N') AS reminderScheduled,
            COALESCE(reminderWPScheduled, 'N') AS reminderWPScheduled,
            COALESCE(reminderScheduledTwo, 'N') AS reminderScheduledTwo
        FROM interviewSchedule
        WHERE id = " . $scheduleId . "
          AND preInterviewId = '" . $safePreInterviewId . "'
        LIMIT 1";

    $stateQuery = mysqli_query($databaseConnection, $stateSql);
    if (!$stateQuery || mysqli_num_rows($stateQuery) === 0) {
        echo json_encode([
            'result' => 'error',
            'status' => 0,
            'message' => 'Candidate invite row not found'
        ]);
        exit();
    }

    $stateRow = mysqli_fetch_assoc($stateQuery);
    if (($stateRow['accessValue'] ?? '') !== 'i') {
        echo json_encode([
            'result' => 'error',
            'status' => 0,
            'message' => 'Candidate access is deleted. Enable access before resend.'
        ]);
        exit();
    }

    $isProcessing = ($stateRow['inviteFlag'] === 'P'
        || $stateRow['reminderScheduled'] === 'P'
        || $stateRow['reminderWPScheduled'] === 'P'
        || $stateRow['reminderScheduledTwo'] === 'P');

    if ($isProcessing) {
        echo json_encode([
            'result' => 'error',
            'status' => 0,
            'message' => 'Invite is currently processing. Please retry after 1-2 minutes.'
        ]);
        exit();
    }

    $resetSql = "UPDATE interviewSchedule
        SET inviteFlag = 'N',
            reminderScheduled = 'N',
            reminderWPScheduled = 'N',
            reminderScheduledTwo = 'N',
            emailed = 'N',
            inviteDate = NOW(),
            scheduleTime = DATE_ADD(NOW(), INTERVAL 24 HOUR)
        WHERE id = " . $scheduleId . "
          AND preInterviewId = '" . $safePreInterviewId . "'
          AND LOWER(TRIM(COALESCE(`access`, ''))) = 'i'
          AND COALESCE(inviteFlag, 'N') <> 'P'
          AND COALESCE(reminderScheduled, 'N') <> 'P'
          AND COALESCE(reminderWPScheduled, 'N') <> 'P'
          AND COALESCE(reminderScheduledTwo, 'N') <> 'P'";

    $resetOk = mysqli_query($databaseConnection, $resetSql);
    if (!$resetOk) {
        echo json_encode([
            'result' => 'error',
            'status' => 0,
            'message' => mysqli_error($databaseConnection)
        ]);
        exit();
    }

    if (mysqli_affected_rows($databaseConnection) === 1) {
        echo json_encode([
            'result' => 'success',
            'status' => 1,
            'scheduleId' => $scheduleId,
            'message' => 'Resend reset successful. New Invite-Reminder will be sent.'
        ]);
        exit();
    }

    $latestStateQuery = mysqli_query($databaseConnection, $stateSql);
    $latestState = $latestStateQuery ? mysqli_fetch_assoc($latestStateQuery) : null;
    $latestIsProcessing = $latestState && (
        ($latestState['inviteFlag'] ?? 'N') === 'P'
        || ($latestState['reminderScheduled'] ?? 'N') === 'P'
        || ($latestState['reminderWPScheduled'] ?? 'N') === 'P'
        || ($latestState['reminderScheduledTwo'] ?? 'N') === 'P'
    );

    echo json_encode([
        'result' => 'error',
        'status' => 0,
        'message' => $latestIsProcessing
            ? 'Invite is currently processing. Please retry after 1-2 minutes.'
            : 'No changes applied. Try again.'
    ]);
    exit();
}
// Job Invitation Dashboard - Search/report (grouped by preInterviewId/job)
else if (isset($_GET['getJobInvitationData'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    $requestedIds = [];

    if (isset($json['preInterviewId'])) {
        $singleId = intval($json['preInterviewId']);
        if ($singleId > 0) {
            $requestedIds[] = $singleId;
        }
    }

    if (isset($json['preInterviewIds']) && is_array($json['preInterviewIds'])) {
        foreach ($json['preInterviewIds'] as $idItem) {
            $idValue = intval($idItem);
            if ($idValue > 0) {
                $requestedIds[] = $idValue;
            }
        }
    }

    $requestedIds = array_values(array_unique($requestedIds));

    if (count($requestedIds) === 0) {
        echo json_encode([
            'result' => 'error',
            'status' => 0,
            'message' => 'Invalid request parameters'
        ]);
        exit();
    }

    $safeIdList = implode(',', array_map('intval', $requestedIds));

    $preCheck = mysqli_query(
        $databaseConnection,
        "SELECT id, interviewName, createdAt
         FROM preInterview
         WHERE id IN (" . $safeIdList . ")
           AND interviewType = 'job'
           AND serviceType = 'IAS'
         ORDER BY
            createdAt DESC,
            id DESC"
    );

    if (!$preCheck || mysqli_num_rows($preCheck) === 0) {
        echo json_encode([
            'result' => 'error',
            'status' => 0,
            'message' => 'Invalid preInterview for Job IAS report'
        ]);
        exit();
    }

    $validPreInterviewIds = [];
    $jobMetaById = [];
    while ($preRow = mysqli_fetch_assoc($preCheck)) {
        $jobIdInt = intval($preRow['id']);
        $validPreInterviewIds[] = $jobIdInt;
        $jobMetaById[(string)$jobIdInt] = [
            'jobName' => (string)($preRow['interviewName'] ?? ''),
            'jobCreatedAt' => $preRow['createdAt'] !== null ? (string)$preRow['createdAt'] : null
        ];
    }

    if (count($validPreInterviewIds) !== count($requestedIds)) {
        echo json_encode([
            'result' => 'error',
            'status' => 0,
            'message' => 'One or more preInterview IDs are invalid for Job IAS report'
        ]);
        exit();
    }

    $safeIdList = implode(',', array_map('intval', $validPreInterviewIds));

    $mainSql = "SELECT
            isc.id AS scheduleId,
            isc.preInterviewId,
            isc.candidate_id AS candidateId,
            COALESCE(isc.candidateName, u.firstName, '') AS candidateName,
            isc.emailId,
            COALESCE(CAST(isc.mobileNumber AS CHAR), '') AS mobileNumber,
            CASE
                WHEN LOWER(TRIM(COALESCE(isc.`access`, ''))) = 'i' THEN 'active'
                ELSE 'deleted'
            END AS accessStatus,
            DATE_FORMAT(isc.inviteDate, '%d-%b-%Y %H:%i:%s') AS inviteDate,
            pr.interviewName AS jobName,
            DATE_FORMAT(pr.createdAt, '%Y-%m-%d %H:%i:%s') AS jobCreatedAt,
            COALESCE(perf.completedInterviewCount, 0) AS completedInterviewCount,
            COALESCE(perf.bestScore, 0) AS bestScore,
            rating.userInterface,
            rating.interviewQuality,
            rating.videoQuality,
            rating.overallExperience,
            rating.questionQuality,
            COALESCE(nls.mailSentCount, 0) AS mailSentCount,
            COALESCE(nls.msgSentCount, 0) AS msgSentCount
        FROM interviewSchedule isc
        INNER JOIN preInterview pr ON pr.id = isc.preInterviewId
        LEFT JOIN users u ON u.emailId = isc.emailId
        LEFT JOIN (
            SELECT
                fr.preInterviewId,
                fr.candidateId,
                COUNT(*) AS completedInterviewCount,
                COALESCE(MAX(fr.dk_score), MAX(fr.intScore), 0) AS bestScore
            FROM feedback_request fr
            WHERE fr.preInterviewId IN (" . $safeIdList . ")
              AND fr.review_status = 2
            GROUP BY fr.preInterviewId, fr.candidateId
        ) perf
            ON perf.preInterviewId = isc.preInterviewId
           AND perf.candidateId = isc.candidate_id
        LEFT JOIN (
            SELECT
                i.preInterviewId,
                r.candidateId,
                ROUND(AVG(NULLIF(r.userInterface, '')), 2) AS userInterface,
                ROUND(AVG(NULLIF(r.interviewQuality, '')), 2) AS interviewQuality,
                ROUND(AVG(NULLIF(r.videoQuality, '')), 2) AS videoQuality,
                ROUND(AVG(NULLIF(r.overallExperience, '')), 2) AS overallExperience,
                ROUND(AVG(NULLIF(r.questionQuality, '')), 2) AS questionQuality
            FROM ratings r
            INNER JOIN interview i ON i.id = r.interviewId
            WHERE i.preInterviewId IN (" . $safeIdList . ")
            GROUP BY i.preInterviewId, r.candidateId
        ) rating
            ON rating.preInterviewId = isc.preInterviewId
           AND rating.candidateId = isc.candidate_id
        LEFT JOIN (
            SELECT
                nl.preInterviewId,
                LOWER(TRIM(nl.emailId)) AS logEmailId,
                SUM(CASE WHEN nl.source = 'mail' AND nl.status = 'sent' THEN 1 ELSE 0 END) AS mailSentCount,
                SUM(CASE WHEN nl.source = 'msg' AND nl.status = 'sent' THEN 1 ELSE 0 END) AS msgSentCount
            FROM notificationLogs nl
            WHERE nl.preInterviewId IN (" . $safeIdList . ")
              AND nl.type IN ('Job Invite', 'Job Invite Reminder 1', 'Job Invite Reminder 2')
            GROUP BY nl.preInterviewId, LOWER(TRIM(nl.emailId))
        ) nls
            ON nls.preInterviewId = isc.preInterviewId
           AND nls.logEmailId = LOWER(TRIM(isc.emailId))
        WHERE isc.preInterviewId IN (" . $safeIdList . ")
          AND pr.interviewType = 'job'
          AND pr.serviceType = 'IAS'
          AND isc.inviteDate IS NOT NULL
        ORDER BY
            pr.createdAt DESC,
            isc.inviteDate DESC,
            isc.id DESC";

    $mainQuery = mysqli_query($databaseConnection, $mainSql);
    if (!$mainQuery) {
        echo json_encode([
            'result' => 'error',
            'status' => 0,
            'message' => mysqli_error($databaseConnection)
        ]);
        exit();
    }

    $rows = mysqli_fetch_all($mainQuery, MYSQLI_ASSOC);
    $grouped = [];

    foreach ($validPreInterviewIds as $jobIdInt) {
        $jobKey = (string)$jobIdInt;
        $grouped[$jobKey] = [
            'preInterviewId' => $jobKey,
            'jobName' => $jobMetaById[$jobKey]['jobName'] ?? '',
            'jobCreatedAt' => $jobMetaById[$jobKey]['jobCreatedAt'] ?? null,
            'totalData' => 0,
            'emailsDelivered' => 0,
            'whatsAppDelivered' => 0,
            'candidates' => []
        ];
    }

    foreach ($rows as &$row) {
        $row['completedInterviewCount'] = intval($row['completedInterviewCount'] ?? 0);
        $row['bestScore'] = floatval($row['bestScore'] ?? 0);
        $row['platformFeedback'] = [
            'userInterface' => $row['userInterface'] === '' ? null : $row['userInterface'],
            'interviewQuality' => $row['interviewQuality'] === '' ? null : $row['interviewQuality'],
            'videoQuality' => $row['videoQuality'] === '' ? null : $row['videoQuality'],
            'overallExperience' => $row['overallExperience'] === '' ? null : $row['overallExperience'],
            'questionQuality' => $row['questionQuality'] === '' ? null : $row['questionQuality']
        ];

        $mailCount = intval($row['mailSentCount'] ?? 0);
        $msgCount = intval($row['msgSentCount'] ?? 0);
        $row['assignMessageSent'] = $msgCount > 0 ? 'Yes' : 'No';
        $row['whatsAppDelivered'] = $msgCount > 0 ? 1 : 0;

        unset(
            $row['mailSentCount'],
            $row['msgSentCount'],
            $row['userInterface'],
            $row['interviewQuality'],
            $row['videoQuality'],
            $row['overallExperience'],
            $row['questionQuality']
        );

        $groupKey = (string)$row['preInterviewId'];
        if (!isset($grouped[$groupKey])) {
            $grouped[$groupKey] = [
                'preInterviewId' => $groupKey,
                'jobName' => $row['jobName'] ?? '',
                'jobCreatedAt' => $row['jobCreatedAt'] ?? null,
                'totalData' => 0,
                'emailsDelivered' => 0,
                'whatsAppDelivered' => 0,
                'candidates' => []
            ];
        }

        $grouped[$groupKey]['totalData'] += 1;
        if ($mailCount > 0) {
            $grouped[$groupKey]['emailsDelivered'] += 1;
        }
        if (intval($row['whatsAppDelivered']) === 1) {
            $grouped[$groupKey]['whatsAppDelivered'] += 1;
        }

        $grouped[$groupKey]['candidates'][] = $row;
    }

    $groupedList = array_values($grouped);

    echo json_encode([
        'result' => 'success',
        'status' => 1,
        'groupedReport' => $groupedList,
        'data' => $rows,
        'message' => 'data found'
    ]);
}
// Toggle or read RestrictedOnly on preInterview
// node-api
elseif (isset($_GET['restrictedOnly'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    $response = ['success' => false];

    // id required for both read and update
    if (!isset($json['preInterviewId']) && !isset($_GET['preInterviewId'])) {
        $response['message'] = 'preInterviewId required';
        echo json_encode($response);
        exit;
    }

    // Accept from JSON body or query param
    $preInterviewId = isset($json['preInterviewId'])
        ? (int)$json['preInterviewId']
        : (int)$_GET['preInterviewId'];

    // If isRestricted is provided, perform update first
    if (isset($json['isRestricted'])) {
        $isRestricted = (bool)$json['isRestricted'];
        $restrictedValue = $isRestricted ? 'Y' : null;

        $updateSql = "UPDATE preInterview SET RestrictedOnly = ? WHERE id = ?";
        $updateStmt = mysqli_prepare($databaseConnection, $updateSql); // prepared UPDATE
        mysqli_stmt_bind_param($updateStmt, "si", $restrictedValue, $preInterviewId); // bind PHP null as SQL NULL
        if (!mysqli_stmt_execute($updateStmt)) {
            echo json_encode([
                'success' => false,
                'message' => 'Failed to update RestrictedOnly: ' . mysqli_error($databaseConnection)
            ]);
            mysqli_stmt_close($updateStmt);
            exit;
        }
        mysqli_stmt_close($updateStmt);
    }

    // Read back current value (or initial load)
    $selectSql = "SELECT RestrictedOnly FROM preInterview WHERE id = ?";
    $selectStmt = mysqli_prepare($databaseConnection, $selectSql);
    mysqli_stmt_bind_param($selectStmt, "i", $preInterviewId);
    mysqli_stmt_execute($selectStmt);
    $result = mysqli_stmt_get_result($selectStmt);
    $row = $result ? mysqli_fetch_assoc($result) : null;
    mysqli_stmt_close($selectStmt);

    echo json_encode([
        'success' => true,
        'preInterviewId' => $preInterviewId,
        'restrictedOnly' => $row ? ($row['RestrictedOnly'] ?: null) : null // 'Y' or null
    ]);
    exit;
}
// node-api
elseif (isset($_GET['getPracticeInvitationFilters'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    $userId = $json['userId'];

    $user_sql = "select firstName, usertype, emailId from users where id = '" . $userId . "'";
    $user_query = mysqli_query($databaseConnection, $user_sql);
    $user = mysqli_fetch_all($user_query, MYSQLI_ASSOC);
    //  print_r($user);
    $user_emailId = $user[0]['emailId'];
    $user_usertype = $user[0]['usertype'];
    //  exit();


    // institute
    $colleges_sql = "SELECT
        'institute' As entity,
        college.id AS entityId,
        college.collegeName as entityName,
        college.code as inviteCode,
        pr.id as prId,
        pr.*
    FROM preInterview pr
    LEFT JOIN preInterview_corporate pic ON pic.preinterviewId = pr.id
    LEFT JOIN users u ON pic.userId = u.id
    LEFT JOIN colleges college ON college.id = u.college_id
    WHERE 1
    AND u.college_id IS NOT NULL
    AND pr.interviewType = 'Practice'
    ";
    if ($user_usertype !== 'admin') {
        $colleges_sql .= " AND u.id = $userId";
    }
    // $colleges_sql .= " GROUP BY college.id";
    // echo $colleges_sql;
    // exit();
    $colleges_query = mysqli_query($databaseConnection, $colleges_sql);
    $values['colleges'] = mysqli_fetch_all($colleges_query, MYSQLI_ASSOC);


    // corporate
   $corporate_sql ="SELECT
        'corporate' as entity,
        company.id as entityId,
        company.name as entityName,
        company.code as inviteCode,
        pr.id as prId,
        pr.*
    from preInterview pr
    LEFT JOIN preInterview_corporate pic ON pic.preinterviewId = pr.id
    join users u on pic.userId = u.id
    left join aspiration_company company on company.id = u.corporate_id
    where
        1
        AND u.corporate_id IS NOT NULL
        and pr.interviewType = 'Practice'";

    if ($user_usertype !== 'admin') {
        $corporate_sql .= " AND u.id = $userId";
    }
    // $corporate_sql .= " GROUP BY company.id";
    // echo $corporate_sql;
    // exit();
    $corporate_query = mysqli_query($databaseConnection, $corporate_sql);
    $values['corporate'] = mysqli_fetch_all($corporate_query, MYSQLI_ASSOC);


    // $jobs_sql = "SELECT pr.* from preInterview pr
    //     LEFT JOIN preInterview_corporate pic ON pic.preinterviewId = pr.id
    //     WHERE 1
    //     AND pr.college_id IS NOT NULL
    //     AND pr.interviewType = 'practice'";

    // if ($user_usertype !== 'admin') {
    //     $jobs_sql .= " AND pic.userId = $userId";
    // }

    // // echo $jobs_sql;
    // // exit();
    // $jobs_query = mysqli_query($databaseConnection, $jobs_sql);
    // $values['jobs'] = mysqli_fetch_all($jobs_query, MYSQLI_ASSOC);

    $role = "SELECT * FROM relavant_role WHERE active = 'Y' ORDER BY id DESC";
    $roleResult = mysqli_query($databaseConnection, $role);
    $values['roleNames'] = mysqli_fetch_all($roleResult, MYSQLI_ASSOC);

    $competencySubject = "SELECT DISTINCT skill.id, role.id as roleId, skill.favourite_subject AS name, CASE WHEN role.id is null then 'Other' ELSE role.name END as role
    FROM favourite_subject skill
    LEFT JOIN role_subject map ON map.subjectId = skill.id
    LEFT JOIN relavant_role role ON role.id = map.roleId
    WHERE skill.subjectType = 'competency' AND skill.active = 'Y'
    order by skill.id";

    $competencySubjectResult = mysqli_query($databaseConnection, $competencySubject);
    $values['competencySubject'] = mysqli_fetch_all($competencySubjectResult, MYSQLI_ASSOC);



    $locations = "SELECT * FROM locations ORDER BY 
            CASE 
            WHEN cityName LIKE '%Any%' THEN 0
            WHEN cityName LIKE '%Remote%' THEN 1
            ELSE 2
            END,
            cityName ASC";

    $locationsResult = mysqli_query($databaseConnection, $locations);
    $values['locations'] = mysqli_fetch_all($competencySubjectResult, MYSQLI_ASSOC);





    if ($user_usertype === 'admin') {
        $values['placementSupport'] = 'y';
    } else {
        $placementSupport_sql = "SELECT placementSupport FROM users WHERE id = $userId";
        $placementSupport_query = mysqli_query($databaseConnection, $placementSupport_sql);

        if ($placementSupport_query && $row = mysqli_fetch_assoc($placementSupport_query)) {
            $placementSupport = strtolower($row['placementSupport']) === 'y' ? 'y' : $row['placementSupport'];
            $values['placementSupport'] = $placementSupport;
        } else {
            $values['placementSupport'] = 'y';
        }
    }



    echo json_encode($values);
}

// node-api
else if (isset($_GET['getPracticeInvitationData'])) {
    $data = file_get_contents("php://input");
    $json = json_decode($data, true);

    // if (!isset($json['userId']) || !isset($json['preInterviewId'])) {
    if (!isset($json['userId']) || !isset($json['collegeId']) || !isset($json['inviteCode']) || !isset($json['preInterviewId'])) {
        echo json_encode([
            'result' => 'error',
            'status' => 0,
            'message' => 'Invalid request parameters'
        ]);
        exit();
    }

    $userId = intval($json['userId']);
    $collegeId = intval($json['collegeId']);
    $from = $json['from'];
    $to = $json['to'];
    $inviteCode = $json['inviteCode'];
    $preInterviewId = $json['preInterviewId'];


    $report_sql = "SELECT
        (SELECT COUNT(DISTINCT cim_sub.emailId)
            FROM candidateInterviewMapping cim_sub
            LEFT JOIN preInterview pr_sub ON pr_sub.id = cim_sub.preInterviewId
            WHERE pr_sub.interviewType = 'Practice'
            -- AND cim_sub.source NOT IN('goprac')
            AND cim_sub.code = ?
            AND pr_sub.id = ?) AS candidates_invited,

        (SELECT COUNT(DISTINCT u.id)
            FROM users u
            JOIN candidateInterviewMapping cim ON u.emailId = cim.emailId
            JOIN preInterview pr ON pr.id = cim.preInterviewId
            WHERE pr.interviewType = 'Practice'
            -- AND cim.source NOT IN('goprac')
            AND cim.code = ?
            AND pr.id = ?
            ) AS candidates_signed_in,

        (SELECT COUNT(DISTINCT fr.candidateId)
            FROM feedback_request fr
            JOIN candidateInterviewMapping cim ON fr.preInterviewId = cim.preInterviewId AND fr.candidateId = cim.candidateId
            JOIN preInterview pr ON pr.id = cim.preInterviewId
            WHERE pr.interviewType = 'Practice'
            -- AND cim.source NOT IN('goprac')
            AND cim.code = ?
            AND pr.id = ?
            ) AS candidates_practiced,
        (SELECT
            CONCAT(
                IF(TIME_FORMAT(SEC_TO_TIME(total_seconds), '%H') + 0 > 0,
                CONCAT(TIME_FORMAT(SEC_TO_TIME(total_seconds), '%H') + 0, ' hour '),
                ''
                ),
                TIME_FORMAT(SEC_TO_TIME(total_seconds), '%i') + 0,
                ' minutes (',
                FLOOR(total_seconds / 60),
                ' minutes)'
            ) AS formatted_duration
            FROM (
            SELECT
                SUM(TIME_TO_SEC(m.totalTime)) + 
                SUM(TIME_TO_SEC(vwd.prwatchDuration)) + 
                SUM(TIME_TO_SEC(vwd.psWatchDuration)) + 
                SUM(TIME_TO_SEC(vwd.gvWatchDuration)) AS total_seconds
            FROM mergedVideos m
            INNER JOIN video_watched_details vwd ON vwd.mergeId = m.mergeId
            JOIN users u ON u.id = m.candidateId
            JOIN candidateInterviewMapping cim ON cim.emailId = u.emailId
            JOIN preInterview pr ON pr.id = cim.preInterviewId
            WHERE pr.interviewType = 'Practice'
            -- AND cim.source NOT IN('goprac')
            AND cim.code = ?
            AND pr.id =?
        ) AS time ) AS totalPracticeDuration,

        (SELECT GROUP_CONCAT(candidateName ORDER BY topScore DESC SEPARATOR ', ')
            FROM (
                SELECT u.firstName AS candidateName, MAX(fr.intScore) AS topScore
                FROM feedback_request fr
                JOIN users u ON u.id = fr.candidateId
                JOIN preInterview pr ON pr.id = fr.preInterviewId
                JOIN candidateInterviewMapping cim ON cim.emailId = u.emailId
                WHERE pr.interviewType = 'Practice'
                AND cim.code = ?
                AND pr.id = ?
                GROUP BY fr.candidateId
                ORDER BY topScore DESC
                LIMIT 3
            ) AS leaderboard) AS leaderboard_top_3";

        $report_stmt = mysqli_prepare($databaseConnection, $report_sql);
        for ($i = 1; $i <= 5; $i++) {
            mysqli_stmt_bind_param($report_stmt, "sisisisisi", $inviteCode, $preInterviewId, $inviteCode, $preInterviewId, $inviteCode, $preInterviewId, $inviteCode,$preInterviewId, $inviteCode,$preInterviewId);
        }

        mysqli_stmt_execute($report_stmt);
        $report_result = mysqli_stmt_get_result($report_stmt);
    if ($report_result) {
        $report_data = mysqli_fetch_assoc($report_result);

        // Include this in final response
        $report_summary = $report_data ?? [
            'candidates_invited' => 0,
            'candidates_signed_in' => 0,
            'candidates_practiced' => 0,
            'totalPracticeDuration' => '00:00:00',
            'leaderboard_top_3' => ''
        ];

        $to_encode = [
            'result' => 'success',
            'status' => 1,
            'report' => $report_summary,
            'message' => 'data found'
        ];
    } else {
        $to_encode = [
            'result' => 'error',
            'status' => 0,
            'message' => 'no data found'
        ];
    }

    echo json_encode($to_encode);
}
//  learner activity Report
// node-api
elseif (isset($_GET['larAssignMessage'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    if (isset($json['mobileNumber']) && isset($json['preInterviewId'])) {
        try {
            $mobileNumber = $json['mobileNumber'];
            $preInterviewId = $json['preInterviewId'];

            // ✅ Update existing entry in watiLogs
            $updateLogQuery = "UPDATE watiLogs 
                               SET template = 'car_reset'
                               WHERE 
                                 mobileNumber = ?
                               AND preInterviewId = ?
                               AND type = 'praticeInvite' 
                               AND template IN('practice_ general','practice_workplace','practice_interview_assign_partner','car_reset')";
            $stmt = mysqli_prepare($databaseConnection, $updateLogQuery);
            mysqli_stmt_bind_param($stmt, "si", $mobileNumber, $preInterviewId);
            $updateLogSuccess = mysqli_stmt_execute($stmt);
            mysqli_stmt_close($stmt);

            if (!$updateLogSuccess) {
                throw new Exception("Failed to update watiLogs.");
            }

            // ✅ Update mobile number in candidateInterviewMapping
            $updateCIMQuery = "UPDATE candidateInterviewMapping 
                               SET createdAt = NOW()
                               WHERE 
                                mobileNumber = ?
                                AND preInterviewId = ?";

            $stmt = mysqli_prepare($databaseConnection, $updateCIMQuery);
            mysqli_stmt_bind_param($stmt, "si", $mobileNumber, $preInterviewId);
            $updateCIMSuccess = mysqli_stmt_execute($stmt);
            mysqli_stmt_close($stmt);

            if (!$updateCIMSuccess) {
                throw new Exception("Failed to update candidateInfoMapping.");
            }

            $response = [
                'result' => "Success",
                'status' => 1,
                'msg' => "carAssignMessage updated successfully."
            ];

        } catch (Exception $e) {
            $response = [
                'result' => "error",
                'status' => -70,
                'msg' => $e->getMessage(),
            ];
        }
    } else {
        $response = [
            'result' => "error",
            'errorCode' => "Invalid input data.",
            'status' => 0
        ];
    }

    echo json_encode($response);
}

//node-api
elseif (isset($_GET['getlarFilters'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    $userId = $json['userId'];

    $user_sql = "select firstName, usertype, emailId from users where id = '" . $userId . "'";
    $user_query = mysqli_query($databaseConnection, $user_sql);
    $user = mysqli_fetch_all($user_query, MYSQLI_ASSOC);
    //  print_r($user);
    $user_emailId = $user[0]['emailId'];
    $user_usertype = $user[0]['usertype'];
    //  exit();
    $isGoPracAdmin = ($user_usertype === 'admin');
    // colleges
    $colleges_sql = "SELECT
        'institute' As entity,
        college.id AS entityId,
        college.collegeName as entityName,
        college.code as inviteCode,
        pr.id as prId,
        GROUP_CONCAT(DISTINCT st.subject ORDER BY st.subject ASC SEPARATOR ', ') AS competencies,
        pr.*
    FROM preInterview pr
    LEFT JOIN preInterview_corporate pic ON pic.preinterviewId = pr.id
    JOIN users u ON pic.userId = u.id
    LEFT JOIN colleges college ON college.id = u.college_id
    LEFT JOIN scps_transaction st ON st.preInterviewId = pr.id
    WHERE 1
    AND u.college_id IS NOT NULL
    AND pr.interviewType = 'Practice'
    ";
    if ($user_usertype !== 'admin') {
        $colleges_sql .= " AND u.id = $userId";
    }
    $colleges_sql .= " GROUP BY pr.id";
    // echo $colleges_sql;
    // exit();
    $colleges_query = mysqli_query($databaseConnection, $colleges_sql);
    $values['colleges'] = mysqli_fetch_all($colleges_query, MYSQLI_ASSOC);

    // corporate
   $corporate_sql ="SELECT
        'corporate' as entity,
        company.id as entityId,
        company.name as entityName,
        company.code as inviteCode,
        pr.id as prId,
        GROUP_CONCAT(DISTINCT st.subject ORDER BY st.subject ASC SEPARATOR ', ') AS competencies,
        pr.*
    from preInterview pr
    LEFT JOIN preInterview_corporate pic ON pic.preinterviewId = pr.id
    join users u on pic.userId = u.id
    left join aspiration_company company on company.id = u.corporate_id
    LEFT JOIN scps_transaction st ON st.preInterviewId = pr.id
    where
        1
        and u.corporate_id is not null
        and pr.interviewType = 'Practice'";

    if ($user_usertype !== 'admin') {
        $corporate_sql .= " AND u.id = $userId";
    }
    $corporate_sql .= " GROUP BY pr.id";
    // echo $corporate_sql;
    // exit();
    $corporate_query = mysqli_query($databaseConnection, $corporate_sql);
    $values['corporate'] = mysqli_fetch_all($corporate_query, MYSQLI_ASSOC);

    // GoPrac (Admin)
    if ($isGoPracAdmin) {
        $freetrial_sql = "SELECT
            'goprac' as entity,
            0 as entityId,
            'GoPrac (Admin)' as entityName,
            COALESCE(MIN(cim.code), '') as inviteCode,
            pr.id as prId,
            GROUP_CONCAT(DISTINCT st.subject ORDER BY st.subject ASC SEPARATOR ', ') AS competencies,
            pr.*
        FROM preInterview pr
        LEFT JOIN candidateInterviewMapping cim ON cim.preInterviewId = pr.id
        LEFT JOIN scps_transaction st ON st.preInterviewId = pr.id
        WHERE pr.interviewType = 'Practice'
        AND pr.practiceType = 'freetrial'
        GROUP BY pr.id
        ORDER BY pr.id";
        
        $freetrial_query = mysqli_query($databaseConnection, $freetrial_sql);
        $values['goprac'] = mysqli_fetch_all($freetrial_query, MYSQLI_ASSOC);
    }



    // $collegesskill_sql = "SELECT col.id, col.collegeName as name, pr.id as prId,
	// 	st.subject
    // FROM colleges col
    // LEFT JOIN preInterview pr ON col.id = pr.college_id AND pr.college_id != 0
    // LEFT JOIN preInterview_corporate pic ON pic.preinterviewId = pr.id
    // LEFT JOIN scps_transaction st ON st.preInterviewId  = pr.id
    // WHERE 1
    // AND pr.interviewType = 'Practice'
    // ";

    // if ($user_usertype !== 'admin') {
    //     $collegesskill_sql .= " AND pic.userId = $userId";
    // }


    // // echo $colleges_sql;
    // // exit();
    // $collegesskill_query = mysqli_query($databaseConnection, $collegesskill_sql);
    // $values['collegesskill'] = mysqli_fetch_all($collegesskill_query, MYSQLI_ASSOC);



    // $jobs_sql = "SELECT pr.* from preInterview pr
    //     LEFT JOIN preInterview_corporate pic ON pic.preinterviewId = pr.id
    //     WHERE 1
    //     AND pr.college_id IS NOT NULL
    //     AND pr.interviewType = 'practice'";

    // if ($user_usertype !== 'admin') {
    //     $jobs_sql .= " AND pic.userId = $userId";
    // }

    // // echo $jobs_sql;
    // // exit();
    // $jobs_query = mysqli_query($databaseConnection, $jobs_sql);
    // $values['jobs'] = mysqli_fetch_all($jobs_query, MYSQLI_ASSOC);

    $role = "SELECT * FROM relavant_role WHERE active = 'Y' ORDER BY id DESC";
    $roleResult = mysqli_query($databaseConnection, $role);
    $values['roleNames'] = mysqli_fetch_all($roleResult, MYSQLI_ASSOC);

    $competencySubject = "SELECT DISTINCT skill.id, role.id as roleId, skill.favourite_subject AS name, CASE WHEN role.id is null then 'Other' ELSE role.name END as role
    FROM favourite_subject skill
    LEFT JOIN role_subject map ON map.subjectId = skill.id
    LEFT JOIN relavant_role role ON role.id = map.roleId
    WHERE skill.subjectType = 'competency' AND skill.active = 'Y'
    order by skill.id";

    $competencySubjectResult = mysqli_query($databaseConnection, $competencySubject);
    $values['competencySubject'] = mysqli_fetch_all($competencySubjectResult, MYSQLI_ASSOC);



    $locations = "SELECT * FROM locations ORDER BY 
            CASE 
            WHEN cityName LIKE '%Any%' THEN 0
            WHEN cityName LIKE '%Remote%' THEN 1
            ELSE 2
            END,
            cityName ASC";

    $locationsResult = mysqli_query($databaseConnection, $locations);
    $values['locations'] = mysqli_fetch_all($competencySubjectResult, MYSQLI_ASSOC);


    if ($user_usertype === 'admin') {
        $values['placementSupport'] = 'y';
    } else {
        $placementSupport_sql = "SELECT placementSupport FROM users WHERE id = $userId";
        $placementSupport_query = mysqli_query($databaseConnection, $placementSupport_sql);

        if ($placementSupport_query && $row = mysqli_fetch_assoc($placementSupport_query)) {
            $placementSupport = strtolower($row['placementSupport']) === 'y' ? 'y' : $row['placementSupport'];
            $values['placementSupport'] = $placementSupport;
        } else {
            $values['placementSupport'] = 'y';
        }
    }

    $values['isGoPracAdmin'] = $isGoPracAdmin;

    echo json_encode($values);
}
//node-api
else if (isset($_GET['getlarData'])) {
    $data = file_get_contents("php://input");
    $json = json_decode($data, true);

    $isGoPracRequest = (isset($json['entityId']) && $json['entityId'] == 0);
    // Accept BOTH collegeId (institutes) AND companyId (corporates)
    // if (!isset($json['userId']) || !isset($json['inviteCode']) || 
    //     (!$isGoPracRequest && !isset($json['collegeId']) && !isset($json['companyId']))) {
    //     echo json_encode([
    //         'result' => 'error',
    //         'status' => 0,
    //         'message' => 'Invalid request parameters'
    //     ]);
    //     exit();
    // }
    if ($isGoPracRequest) {
    
        if (!isset($json['userId'])) {
            echo json_encode([
                'result' => 'error',
                'status' => 0,
                'message' => 'Invalid request parameters'
            ]);
            exit();
        }
    } else {
        // Normal users (non-Admin)
        if (
            !isset($json['userId']) ||
            !isset($json['inviteCode']) ||
            (!isset($json['collegeId']) && !isset($json['companyId']))
        ) {
            echo json_encode([
                'result' => 'error',
                'status' => 0,
                'message' => 'Invalid request parameters'
            ]);
            exit();
        }
    }

    // For validation purposes only - not used in SQL queries
    // $entityId = isset($json['collegeId']) ? intval($json['collegeId']) : intval($json['companyId']);
    // Safely get entityId
    if (isset($json['collegeId'])) {
        $entityId = intval($json['collegeId']);
    } elseif (isset($json['companyId'])) {
        $entityId = intval($json['companyId']);
    } else {
        $entityId = 0; // For goprac or when neither exists
    }

    if (!is_array($json['preInterviewId']) || empty($json['preInterviewId'])) {
        echo json_encode([
            'result' => 'error',
            'status' => 0,
            'message' => 'Invalid preInterviewId array'
        ]);
        exit();
    }

    $userId = intval($json['userId']);
    // $collegeId = intval($json['collegeId']);
    $preInterviewId = $json['preInterviewId'];
    $inviteCode = $json['inviteCode'] ?? null;
    $from = $json['from'];
    $to = $json['to'];

    $preInterviewIds = $json['preInterviewId'];
    $preInterviewIds = array_map('intval', $preInterviewIds);


    $placeholder = implode(',', array_fill(0, count($preInterviewIds), '?'));

    // MODIFIED: Build WHERE clause conditionally
    $whereClause = "WHERE pr.interviewType = 'Practice'";

    if ($isGoPracRequest) {
        // For GoPrac: Only filter by practiceType and practice IDs
        $whereClause .= " AND pr.practiceType = 'freetrial'
            AND pr.id IN($placeholder)";
    } else {
        // For Regular: Filter by code and practice IDs
        $whereClause .= " AND cim.code = ?
            AND pr.id IN($placeholder)";
    }
    // included delete from cim
    // -- AND cim.source  <> 'goprac'
    $main_sql = "SELECT
            u.firstName AS candidateName,
            u.id AS candidateId,
            COALESCE(u.mobileNumber, cim.mobileNumber) AS mobileNumber,
            cim.emailId,
            cim.deleted,
            pr.roleId,
            cim.preInterviewId,
            rr.name AS role,
            GROUP_CONCAT(fs.favourite_subject) AS subject,
            pr.interviewName AS product,
            (
                SELECT fr3.interviewId
                FROM feedback_request fr3
                JOIN interviewSchedule isc3 ON fr3.interviewId = isc3.interviewId
                WHERE isc3.preInterviewId = cim.preInterviewId
                AND fr3.candidateId = u.id
                AND fr3.review_status = 2
                ORDER BY fr3.intScore DESC
                LIMIT 1
            ) AS interviewId,
            (
                SELECT fr1.intScore
                FROM feedback_request fr1
                JOIN interviewSchedule isc1 ON fr1.interviewId = isc1.interviewId
                WHERE isc1.preInterviewId = cim.preInterviewId
                AND fr1.candidateId = u.id
                AND fr1.review_status = 2
                ORDER BY fr1.intScore DESC
                LIMIT 1
            ) AS intScore,
            (
                SELECT COUNT(*)
                FROM feedback_request fr2
                JOIN interviewSchedule isc2 ON fr2.interviewId = isc2.interviewId
                WHERE isc2.preInterviewId = cim.preInterviewId
                AND fr2.candidateId = u.id
                AND fr2.review_status = 2
            ) AS sessionCount,
            (
                SELECT DATE_FORMAT(MIN(fr_start.requestDate), '%d-%b-%Y %H:%i:%s')
                FROM feedback_request fr_start
                JOIN interviewSchedule isc_start ON fr_start.interviewId = isc_start.interviewId
                WHERE isc_start.preInterviewId = cim.preInterviewId
                AND fr_start.candidateId = u.id
                AND fr_start.review_status = 2
            ) AS firstCompletionDate,
            CONCAT(
                COUNT(DISTINCT pr.interviewName),
                ' [',
                GROUP_CONCAT(DISTINCT pr.interviewName SEPARATOR ', '),
                ']'
            ) AS practices
            FROM candidateInterviewMapping cim
            LEFT JOIN users u ON u.emailId = cim.emailId
            LEFT JOIN preInterview pr ON pr.id = cim.preInterviewId
            LEFT JOIN relavant_role rr ON rr.id = pr.roleId
            LEFT JOIN favourite_subject fs ON FIND_IN_SET(fs.id, pr.subjectId) > 0
            " . $whereClause . "
            -- WHERE pr.interviewType = 'Practice'
            -- AND cim.code = ?
            -- AND pr.id IN($placeholder)
            -- AND cim.preInterviewId IN($placeholder)
            " . ($from && $to ? " AND DATE(cim.createdAt) BETWEEN ? AND ? " : " ") . "
            AND (
                    (pr.restrictedOnly = 'Y' AND cim.access = 'i') 
                    OR (pr.restrictedOnly <> 'Y' OR pr.restrictedOnly IS NULL)
                )
            GROUP BY cim.emailId
        ORDER BY cim.createdAt DESC;";

        // ORDER BY intScore DESC;

    $stmt = mysqli_prepare($databaseConnection, $main_sql);

    // if ($from && $to) {
    //     mysqli_stmt_bind_param($stmt, "siss", $inviteCode, $preInterviewId, $from, $to);
    // } else {
    //     mysqli_stmt_bind_param($stmt, "si", $inviteCode, $preInterviewId);
    // }

    if (!$stmt) {
        echo json_encode([
            'result' => 'error',
            'status' => 0,
            'message' => 'Prepare failed: ' . mysqli_error($databaseConnection),
            'sql' => $main_sql
        ]);
        exit();
    }

    if ($from && $to) {
        $preInterviewIds = array_map('intval', $preInterviewIds);
        
        if ($isGoPracRequest) {
            // GoPrac: Skip inviteCode parameter
            $types = str_repeat('i', count($preInterviewIds)) . 'ss';
            $params = array_merge($preInterviewIds, [$from, $to]);
        } else {
            // Regular: Include inviteCode parameter
            $types = 's' . str_repeat('i', count($preInterviewIds)) . 'ss';
            $params = array_merge([$inviteCode], $preInterviewIds, [$from, $to]);
        }
        
        mysqli_stmt_bind_param($stmt, $types, ...$params);
    } else {
        $preInterviewIds = array_map('intval', $preInterviewIds);
        
        if ($isGoPracRequest) {
            // GoPrac: Skip inviteCode parameter
            $types = str_repeat('i', count($preInterviewIds));
            $params = $preInterviewIds;
        } else {
            // Regular: Include inviteCode parameter
            $types = 's' . str_repeat('i', count($preInterviewIds));
            $params = array_merge([$inviteCode], $preInterviewIds);
        }
        
        mysqli_stmt_bind_param($stmt, $types, ...$params);
    }

    // if ($from && $to) {
    //     // cast to int
    //     $preInterviewIds = array_map('intval', $preInterviewIds);

    //     // inviteCode (string) + preInterviewIds (ints) + from (string) + to (string)
    //     $types = 's' . str_repeat('i', count($preInterviewIds)) . 'ss';

    //     // merge params
    //     $params = array_merge([$inviteCode], $preInterviewIds, [$from, $to]);

    //     mysqli_stmt_bind_param($stmt, $types, ...$params);
    // } else {
    //     // cast to int
    //     $preInterviewIds = array_map('intval', $preInterviewIds);

    //     // inviteCode (string) + preInterviewIds (ints)
    //     $types = 's' . str_repeat('i', count($preInterviewIds));
    //     $params = array_merge([$inviteCode], $preInterviewIds);

    //     mysqli_stmt_bind_param($stmt, $types, ...$params);
    // }

    // echo $debug_sql;
    mysqli_stmt_execute($stmt);
    
    $main_query = mysqli_stmt_get_result($stmt);

    $values = [];

    if ($main_query) {
        $rows = mysqli_fetch_all($main_query, MYSQLI_ASSOC);

        // Add extra data to each row
        // add query per user data
        foreach ($rows as &$row) {
            $candidateId = $row['candidateId'];

            // Query ratings table for this candidate and preInterview
            $ratingSql = "SELECT questionQuality, userInterface 
                        FROM ratings 
                        WHERE candidateId = ?
                        AND interviewId = ?
                        ORDER BY ratingsSubmitTime DESC LIMIT 1";

            $stmt2 = mysqli_prepare($databaseConnection, $ratingSql);
            mysqli_stmt_bind_param($stmt2, "ii", $candidateId, $row['interviewId']);
            mysqli_stmt_execute($stmt2);
            $result2 = mysqli_stmt_get_result($stmt2);

            $ratingRow = mysqli_fetch_assoc($result2);

            $row['questionQuality'] = $ratingRow['questionQuality'] ?? null;
            $row['userInterface'] = $ratingRow['userInterface'] ?? null;

            // Fetch comptency count and formatted list
            $subject_sql = "SELECT 
                CONCAT(
                    COUNT(DISTINCT fs.favourite_subject), 
                    ' [', 
                    GROUP_CONCAT(DISTINCT fs.favourite_subject ORDER BY fs.favourite_subject SEPARATOR ', '), 
                    ']'
                ) AS favourite_subjects,
                DATE_FORMAT(MIN(cim.createdAt), '%d-%b-%Y %H:%i:%s') AS createdAt,
                GROUP_CONCAT(DISTINCT fs.id) AS subject_ids
            FROM candidateInterviewMapping cim
            LEFT JOIN favourite_subject fs ON fs.id = cim.subject
            WHERE cim.subject IS NOT NULL
            AND cim.emailId = ?;";

            $subject_stmt = mysqli_prepare($databaseConnection, $subject_sql);
            mysqli_stmt_bind_param($subject_stmt, "s", $row['emailId']);
            mysqli_stmt_execute($subject_stmt);
            $subject_result = mysqli_stmt_get_result($subject_stmt);
            $subject_row = mysqli_fetch_assoc($subject_result);


            $row['competency'] = $subject_row['favourite_subjects'] ?? '0';

            $row['subjectIds'] = isset($subject_row['subject_ids'])
                ? explode(',', $subject_row['subject_ids'])
                : [];

            $row['practiceStartDate'] = $subject_row['createdAt'] ?? NULL;

            // practiceDuration
            $practiceDuration_sql = "SELECT 
                SEC_TO_TIME(SUM(TIME_TO_SEC(m.totalTime)) +
                SUM(TIME_TO_SEC(vwd.prwatchDuration)) +
                SUM(TIME_TO_SEC(vwd.psWatchDuration)) +
                SUM(TIME_TO_SEC(vwd.gvWatchDuration))) AS duration,
                (SUM(TIME_TO_SEC(m.totalTime)) +
                SUM(TIME_TO_SEC(vwd.prwatchDuration)) +
                SUM(TIME_TO_SEC(vwd.psWatchDuration)) +
                SUM(TIME_TO_SEC(vwd.gvWatchDuration))) AS total_seconds
            FROM feedback_request fr
            INNER JOIN mergedVideos m ON m.interviewId = fr.interviewId
            INNER JOIN video_watched_details vwd ON vwd.mergeId = m.mergeId
            INNER JOIN interview i ON i.id = m.interviewId
            LEFT JOIN interviewSchedule isc ON isc.interviewId = i.id
            WHERE 1
            AND fr.review_status  = 2
            AND  m.candidateId = ?
            AND isc.preInterviewId = ?
            ";

            $practiceDuration_stmt = mysqli_prepare($databaseConnection, $practiceDuration_sql);
            mysqli_stmt_bind_param($practiceDuration_stmt, "ii", $row['candidateId'], $row['preInterviewId']);
            mysqli_stmt_execute($practiceDuration_stmt);
            $practiceDuration_result = mysqli_stmt_get_result($practiceDuration_stmt);
            $practiceDuration_row = mysqli_fetch_assoc($practiceDuration_result);

            $totalSeconds = (int) ($practiceDuration_row['total_seconds'] ?? 0);
            $practicePercent = min(round(($totalSeconds / 36000) * 100), 100);

            $row['practiceDuration'] = $practiceDuration_row['duration'] ?? '0';
            $row['practiceCompletion'] = $practicePercent . '%';

            // bestScore
            $bestScore_sql = "SELECT MAX(fr.dk_score) as bestScore
                FROM feedback_request fr
                JOIN interviewSchedule isc ON isc.interviewId = fr.interviewId
                WHERE fr.dk_score IS NOT NULL
                AND fr.review_status = 2
                AND fr.candidateId = ?
                AND isc.preInterviewId = ?";

            $bestScore_stmt = mysqli_prepare($databaseConnection, $bestScore_sql);
            mysqli_stmt_bind_param($bestScore_stmt, "ii", $row['candidateId'],  $row['preInterviewId']);


            mysqli_stmt_execute($bestScore_stmt);
            $bestScore_result = mysqli_stmt_get_result($bestScore_stmt);
            $bestScore_row = mysqli_fetch_assoc($bestScore_result);

            $row['bestScore'] = $bestScore_row['bestScore'] ?? '0';


            // assign Message
            $assignMessage_sql = "SELECT IF(COUNT(*) > 0, 'Yes', 'No') AS assignMessage
            From watiLogs
            WHERE 
                type = 'praticeInvite'
                AND template IN('practice_ general','practice_workplace','practice_interview_assign_partner','car_reset')
                AND mobileNumber = ?
                AND preInterviewId = ?
            ORDER BY id DESC";

            $assignMessage_stmt = mysqli_prepare($databaseConnection, $assignMessage_sql);
            mysqli_stmt_bind_param($assignMessage_stmt, "ii", $row['mobileNumber'], $row['preInterviewId']);
            mysqli_stmt_execute($assignMessage_stmt);
            $assignMessage_result = mysqli_stmt_get_result($assignMessage_stmt);
            $assignMessage_row = mysqli_fetch_assoc($assignMessage_result);

            $row['assignMessage'] = $assignMessage_row['assignMessage'] ?? '0';


            // count
            $candidateStatus_sql = "SELECT 
                COUNT(*) AS applied,
                SUM(candidateStatus = 'Client Shortlisted') AS client_shortlisted_count,
                SUM(candidateStatus IN ('Offered', 'Offer Drop', 'Offer Accepted', 'Joined')) AS offered_count
            FROM interviewSchedule
            WHERE 
                submissionFlag = 'Y'
                AND emailId = ?";

            // echo $candidateStatus_sql;

            $candidateStatus_stmt = mysqli_prepare($databaseConnection, $candidateStatus_sql);
            mysqli_stmt_bind_param($candidateStatus_stmt, "s", $row['emailId']);
            mysqli_stmt_execute($candidateStatus_stmt);
            $candidateStatus_result = mysqli_stmt_get_result($candidateStatus_stmt);
            $candidateStatus_row = mysqli_fetch_assoc($candidateStatus_result);

            $row['applied_count'] = $candidateStatus_row['applied'] ?? '0';
            $row['client_shortlisted_count'] = $candidateStatus_row['client_shortlisted_count'] ?? '0';
            $row['offered_count'] = $candidateStatus_row['offered_count'] ?? '0';
            $row['recommended_jobs'] = [];
            $row['recommended_jobs_count'] = 22;

        }


        $values = $rows;

        // $to_encode = [
        //     'result' => 'success',
        //     'status' => 1,
        //     'data' => $values,
        //     'report' => $report_summary,
        //     'message' => 'data found'
        // ];
                $to_encode = [
            'result' => 'success',
            'status' => 1,
            'data' => $values,
            'report' => null,
            'message' => 'data found'
        ];
    } else {
        $to_encode = [
            'result' => 'error',
            'status' => 0,
            'message' => 'no data found'
        ];
    }

    echo json_encode($to_encode);
}

else if (isset($_GET['getlarChartData'])) {
    $data = file_get_contents("php://input");
    $json = json_decode($data, true);

    // Updated validation to accept both collegeId and companyId
    if (!isset($json['userId']) || !isset($json['preInterviewId']) || !isset($json['inviteCode']) ||
        (!isset($json['collegeId']) && !isset($json['companyId']))) {
        echo json_encode([
            'result' => 'error',
            'status' => 0,
            'message' => 'Invalid request parameters'
        ]);
        exit();
    }

    $userId = intval($json['userId']);
    $entityId = isset($json['collegeId']) ? intval($json['collegeId']) : intval($json['companyId']); // added instead of collegeId
    // $collegeId = intval($json['collegeId']);
    $inviteCode = $json['inviteCode'];
    $preInterviewIds = (array)$json['preInterviewId']; // make sure it's always an array
    $from = $json['from'];
    $to = $json['to'];

    // build placeholders for preInterviewId array
    $placeholders = implode(',', array_fill(0, count($preInterviewIds), '?'));

    $main_sql = "SELECT
            u.firstName,
            ks.key_skill AS skill,
            ov.observation_values AS score,
            ks.id AS key_skill_id,
            DENSE_RANK() OVER (
                PARTITION BY er.candidateId
                ORDER BY er.interviewId
            ) AS session
        FROM
            expert_review_observation_details AS erod
        INNER JOIN observation_area AS oa ON oa.id = erod.observationAreaId
        INNER JOIN expert_review AS er ON er.id = erod.expertReviewId
        INNER JOIN key_skill AS ks ON ks.id = oa.key_skill
        LEFT OUTER JOIN observation_values AS ov ON ov.id = erod.observationValueId
        LEFT JOIN users u ON u.id = er.candidateId
        LEFT JOIN questions q ON q.id = er.questionId
        LEFT JOIN interview i ON i.id = er.interviewId
        LEFT JOIN interviewSchedule isc ON isc.interviewId = er.interviewId AND isc.candidate_id = er.candidateId
        LEFT JOIN preInterview pr ON pr.id = isc.preInterviewId
        LEFT JOIN feedback_request fr ON fr.interviewId = er.interviewId
        JOIN candidateInterviewMapping cim ON cim.candidateId = u.id AND cim.preInterviewId = isc.preInterviewId
        WHERE
            ks.key_skill NOT IN ('Pronunciation', 'Vocabulary', 'Fluency', 'Sentence Mastery','Issues with Video', 'Self-Confidence')
            AND isc.preInterviewId IN ($placeholders)
            AND cim.code = ?
            AND fr.review_status = 2
            AND q.subjectId != 178
            -- AND cim.source NOT IN('goprac')
            AND ks.status = 'Yes'
            /* CHANGE: apply access filter only when Restricted = 'Y' */
            AND (
                (pr.restrictedOnly = 'Y' AND cim.access = 'i')           /* enforce access when restricted */
                OR (pr.restrictedOnly <> 'Y' OR pr.restrictedOnly IS NULL)/* otherwise keep existing logic */
            )"
        . ($from && $to ? " AND DATE(cim.createdAt) BETWEEN ? AND ?" : "") . ";";

    $stmt = mysqli_prepare($databaseConnection, $main_sql);

    // build bind types: preInterviewIds are int, inviteCode is string
    $types = str_repeat('i', count($preInterviewIds)) . 's';

    $params = array_merge($preInterviewIds, [$inviteCode]);

    if ($from && $to) {
        $types .= 'ss';
        $params[] = $from;
        $params[] = $to;
    }

    // bind dynamically
    $bind_names[] = $types;
    foreach ($params as $key => $value) {
        $bind_names[] = &$params[$key];
    }
    call_user_func_array([$stmt, 'bind_param'], $bind_names);

    mysqli_stmt_execute($stmt);
    $main_query = mysqli_stmt_get_result($stmt);

    $values = [];

    if ($main_query) {
        $rows = mysqli_fetch_all($main_query, MYSQLI_ASSOC);
        $values = $rows;
        $to_encode = [
            'result' => 'success',
            'status' => 1,
            'data' => $values,
            'message' => 'data found'
        ];
    } else {
        $to_encode = [
            'result' => 'error',
            'status' => 0,
            'message' => 'no data found'
        ];
    }
    echo json_encode($to_encode);
}
// node-api
//  Update delete status of candidateInterviewMapping
elseif (isset($_GET['updateCandidateDeleteStatus'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    
    if (isset($json['emailId']) && isset($json['preInterviewId']) && isset($json['deleted'])) {
        $emailId = $json['emailId'];
        $preInterviewId = $json['preInterviewId'];
        $deleteStatus = $json['deleted']; // 'Y' for deleted, 'N' for active
        
        // Update the delete column using emailId and preInterviewId
        $updateSql = "UPDATE candidateInterviewMapping SET deleted = ? WHERE emailId = ? AND preInterviewId = ?";
        $updateStmt = mysqli_prepare($databaseConnection, $updateSql);
        mysqli_stmt_bind_param($updateStmt, "ssi", $deleteStatus, $emailId, $preInterviewId);
        
        if (mysqli_stmt_execute($updateStmt)) {
            $response = [
                'success' => true,
                'message' => 'Deleted status updated successfully',
                'emailId' => $emailId,
                'preInterviewId' => $preInterviewId,
                'deleted' => $deleteStatus
            ];
        } else {
            $response = [
                'success' => false,
                'message' => 'Failed to update deleted status: ' . mysqli_error($databaseConnection)
            ];
        }
        mysqli_stmt_close($updateStmt);
    } else {
        $response = [
            'success' => false,
            'message' => 'Invalid parameters - emailId, preInterviewId and deleted status required'
        ];
    }
    
    echo json_encode($response);
}
// node-api
else if (isset($_GET['getProductFilters'])) {
    header('Content-Type: application/json');
    header('Access-Control-Allow-Origin: *');

    // Fetch all data in one query - hierarchical structure
    $query = "SELECT 
                pr.id AS preInterviewId,
                pr.interviewName AS name,
                pr.YOE,
                pr.roleId,
                rr.name AS roleName,
                pr.prbCount,
                CASE 
                    WHEN pr.prbCount IS NULL THEN NULL
                    ELSE (pr.prbCount * 15)
                END AS price,
                (
                    SELECT GROUP_CONCAT(fs.favourite_subject ORDER BY fs.id SEPARATOR ', ')
                    FROM scps_transaction st
                    INNER JOIN favourite_subject fs ON FIND_IN_SET(fs.id, st.subject) > 0
                    WHERE st.preInterviewId = pr.id
                ) AS commaSepSubjects
              FROM preInterview pr
              LEFT JOIN relavant_role rr ON rr.id = pr.roleId
              WHERE pr.interviewType = 'Practice'
                AND pr.practiceType = 'freetrial'
                AND pr.YOE IS NOT NULL
                AND pr.YOE != ''
              ORDER BY pr.YOE ASC, rr.name ASC, pr.id DESC";
    
    $result = mysqli_query($databaseConnection, $query);
    
    if (!$result) {
        $to_encode = array(
            'result' => 'error',
            'status' => 0,
            'message' => 'Query error: ' . mysqli_error($databaseConnection),
        );
    } else {
        // Build hierarchical structure: YOE -> Roles -> Subjects
        $hierarchy = [];
        $yoeList = [];
        
        while ($row = mysqli_fetch_assoc($result)) {
            $yoe = $row['YOE'];
            $roleId = $row['roleId'];
            $roleName = $row['roleName'];
            
            // Track unique YOE values
            if (!in_array($yoe, $yoeList)) {
                $yoeList[] = $yoe;
            }
            
            // Initialize YOE level if not exists
            if (!isset($hierarchy[$yoe])) {
                $hierarchy[$yoe] = [];
            }
            
            // Initialize Role level if not exists
            if (!isset($hierarchy[$yoe][$roleId])) {
                $hierarchy[$yoe][$roleId] = [
                    'roleId' => $roleId,
                    'roleName' => $roleName,
                    'subjects' => []
                ];
            }
            
            // Get first subject from comma separated list
            $firstSubject = '';
            if ($row['commaSepSubjects']) {
                $subjects = explode(',', $row['commaSepSubjects']);
                $firstSubject = trim($subjects[0]);
            }
            
            // Add subject
            $hierarchy[$yoe][$roleId]['subjects'][] = [
                'preInterviewId' => $row['preInterviewId'],
                'name' => $row['name'],
                'subject' => $firstSubject,
                'commaSepSubjects' => $row['commaSepSubjects'],
                'price' => $row['price']
            ];
        }
        
        // Convert hierarchy to array format (remove associative keys)
        $formattedHierarchy = [];
        foreach ($hierarchy as $yoe => $roles) {
            $formattedHierarchy[$yoe] = array_values($roles);
        }
        
        $to_encode = array(
            'result' => 'success',
            'status' => 1,
            'data' => [
                'yoeList' => $yoeList,
                'hierarchy' => $formattedHierarchy
            ],
            'message' => 'Filters data fetched successfully',
        );
    }
    
    echo json_encode($to_encode);
}
// node-api
else if (isset($_GET['getHomepageProducts'])) {
    $recommendedPractice = "SELECT
        pr.id,
        pr.interviewName AS `name`,
        pr.targetAudience AS targetAudience,
        pr.duration AS duration,
        pr.categoryType AS categoryType,
        pr.interviewLevel AS interviewLevel,
        pr.id AS preInterviewId,
        pr.YOE AS YOE,
        pr.roleId,
        pr.prbCount,
        CASE 
            WHEN pr.prbCount IS NULL THEN NULL
            ELSE (pr.prbCount * 15)
        END AS price,
        rr.name AS Domain,
        (
            SELECT GROUP_CONCAT(fs.favourite_subject ORDER BY fs.id SEPARATOR ', ')
            FROM scps_transaction st
            INNER JOIN favourite_subject fs ON FIND_IN_SET(fs.id, st.subject) > 0
            WHERE st.preInterviewId = pr.id
        ) AS commaSepSubjects
    FROM preInterview pr
    LEFT JOIN relavant_role rr ON rr.id = pr.roleId
    WHERE 1
        AND pr.interviewType = 'Practice'
        AND pr.practiceType = 'freetrial'
    GROUP BY pr.id
    ORDER BY pr.id DESC;";
    
    $recommendedPracticeQuery = mysqli_query($databaseConnection, $recommendedPractice);
    
    if (!$recommendedPracticeQuery) {
        $to_encode = array(
            'result' => 'error',
            'status' => 0,
            'message' => 'Query error: ' . mysqli_error($databaseConnection),
        );
    } else if (mysqli_num_rows($recommendedPracticeQuery) >= 1) {
        $to_encode = array(
            'result' => 'success',
            'status' => 1,
            'data' => mysqli_fetch_all($recommendedPracticeQuery, MYSQLI_ASSOC),
            'message' => 'Homepage products data found',
        );
    } else {
        $to_encode = array(
            'result' => 'success',
            'status' => 0,
            'message' => 'No homepage products found',
        );
    }
    
    echo json_encode($to_encode);
}
// node-api
else if (isset($_GET['getBlogPageData'])) {
    header('Content-Type: application/json');
    header('Access-Control-Allow-Origin: *');

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    $candidateId = isset($json['candidateId']) ? $json['candidateId'] : null;
    $includeRecommendations = isset($json['includeRecommendations']) ? $json['includeRecommendations'] : false;

    // Fetch only domains that have blogs (with blog count)
    $domainsQuery = "SELECT DISTINCT r.id, r.name, r.active, COUNT(b.id) as blog_count
                     FROM relavant_role r
                     INNER JOIN blogs b ON r.id = b.role_id
                     WHERE r.active = 'y'
                     GROUP BY r.id, r.name, r.active
                     ORDER BY r.name ASC";
    
    $domainsResult = mysqli_query($databaseConnection, $domainsQuery);
    $domains = mysqli_fetch_all($domainsResult, MYSQLI_ASSOC);

    // Fetch all blogs with domain names and views
    $blogsQuery = "SELECT 
                    b.id,
                    b.title,
                    b.role_id,
                    b.sequence,
                    b.content,
                    b.views,
                    b.created_at,
                    r.name as domain_name
                  FROM blogs b
                  LEFT JOIN relavant_role r ON b.role_id = r.id
                  WHERE r.active = 'y'
                  ORDER BY b.sequence ASC, b.created_at DESC";
    
    $blogsResult = mysqli_query($databaseConnection, $blogsQuery);
    $allBlogs = mysqli_fetch_all($blogsResult, MYSQLI_ASSOC);

    $recommendedBlogs = [];
    
    // Fetch recommended blogs if user is logged in
    if ($includeRecommendations && $candidateId) {
        $recommendedQuery = "SELECT 
                              b.id,
                              b.title,
                              b.role_id,
                              b.sequence,
                              b.content,
                              b.views,
                              b.created_at,
                              r.name as domain_name
                            FROM blogs b
                            LEFT JOIN relavant_role r ON b.role_id = r.id
                            WHERE r.active = 'y' 
                            AND b.role_id IN (
                              SELECT DISTINCT role 
                              FROM candidateInterviewMapping 
                              WHERE candidateId = '" . mysqli_real_escape_string($databaseConnection, $candidateId) . "'
                            )
                            ORDER BY b.sequence ASC, b.created_at DESC";
        
        $recommendedResult = mysqli_query($databaseConnection, $recommendedQuery);
        $recommendedBlogs = mysqli_fetch_all($recommendedResult, MYSQLI_ASSOC);
    }

    $to_encode = array(
        'result' => 'success',
        'status' => 1,
        'data' => array(
            'domains' => $domains,
            'allBlogs' => $allBlogs,
            'recommendedBlogs' => $recommendedBlogs
        ),
        'message' => 'Blog page data fetched successfully'
    );

    echo json_encode($to_encode);
}
// Get single blog by ID
else if (isset($_GET['getBlogById'])) {
    header('Content-Type: application/json');
    header('Access-Control-Allow-Origin: *');

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    $blogId = isset($json['blogId']) ? $json['blogId'] : null;

    if (!$blogId) {
        echo json_encode(array(
            'result' => 'error',
            'status' => 0,
            'message' => 'Missing blogId'
        ));
        exit;
    }

    $query = "SELECT 
                b.id,
                b.title,
                b.role_id,
                b.sequence,
                b.content,
                b.views,                  
                b.created_at,
                r.name as domain_name
              FROM blogs b
              LEFT JOIN relavant_role r ON b.role_id = r.id
              WHERE b.id = '" . mysqli_real_escape_string($databaseConnection, $blogId) . "'
              AND r.active = 'y'
              LIMIT 1";

    $result = mysqli_query($databaseConnection, $query);

    if ($result && mysqli_num_rows($result) > 0) {
        $blog = mysqli_fetch_assoc($result);
        $to_encode = array(
            'result' => 'success',
            'status' => 1,
            'data' => $blog,
            'message' => 'Blog fetched successfully'
        );
    } else {
        $to_encode = array(
            'result' => 'error',
            'status' => 0,
            'message' => 'Blog not found'
        );
    }

    echo json_encode($to_encode);
}
// Increment blog view count
else if (isset($_GET['incrementBlogView'])) {
    header('Content-Type: application/json');
    header('Access-Control-Allow-Origin: *');

    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    $blogId = isset($json['blogId']) ? $json['blogId'] : null;

    if (!$blogId) {
        echo json_encode(array(
            'result' => 'error',
            'status' => 0,
            'message' => 'Missing blogId'
        ));
        exit;
    }

    // Increment view count
    $query = "UPDATE blogs 
              SET views = views + 1 
              WHERE id = '" . mysqli_real_escape_string($databaseConnection, $blogId) . "'";
    
    $result = mysqli_query($databaseConnection, $query);

    if ($result) {
        // Get updated view count
        $selectQuery = "SELECT views FROM blogs WHERE id = '" . mysqli_real_escape_string($databaseConnection, $blogId) . "'";
        $selectResult = mysqli_query($databaseConnection, $selectQuery);
        $row = mysqli_fetch_assoc($selectResult);
        
        $to_encode = array(
            'result' => 'success',
            'status' => 1,
            'data' => array('views' => $row['views']),
            'message' => 'View count updated'
        );
    } else {
        $to_encode = array(
            'result' => 'error',
            'status' => 0,
            'message' => 'Failed to update view count'
        );
    }

    echo json_encode($to_encode);
}

// node-api
elseif (isset($_GET['getLmdFilters'])) {

    // expRange
    $expRange_q = mysqli_query($databaseConnection, 
        "SELECT DISTINCT expRange FROM JobMailList WHERE expRange IS NOT NULL AND expRange <> '' ORDER BY expRange ASC");
    $expRanges = [];
    while ($row = mysqli_fetch_assoc($expRange_q)) $expRanges[] = $row['expRange'];

    // noOfStudents
    $students_q = mysqli_query($databaseConnection,
        "SELECT DISTINCT numberOfCandidates FROM JobMailList WHERE numberOfCandidates IS NOT NULL AND numberOfCandidates <> '' ORDER BY numberOfCandidates ASC");
    $noOfStudents = [];
    while ($row = mysqli_fetch_assoc($students_q)) $noOfStudents[] = $row['numberOfCandidates'];

    // orgTypes (static)
    $orgTypes = ["College", "Corporate", "Institute"];

    // orgNames 
    $orgNames_q = mysqli_query($databaseConnection,
        "SELECT DISTINCT name FROM JobMailList WHERE name IS NOT NULL AND name <> ''
         UNION
         SELECT DISTINCT companyName as name FROM corporateMailList WHERE companyName IS NOT NULL AND companyName <> ''
         ORDER BY name ASC");
    $orgNames = [];
    while ($row = mysqli_fetch_assoc($orgNames_q)) $orgNames[] = $row['name'];

    // leadStatus filter (for dropdown)
    $leadStatus_q = mysqli_query($databaseConnection, 
        "SELECT id, statusValue as value FROM salesLeadActionStatus WHERE id IN (1,2,3,5) ORDER BY id ASC"
    );
    $leadStatuses = [];
    while ($row = mysqli_fetch_assoc($leadStatus_q)) $leadStatuses[] = $row;


    $to_encode = [
        'result' => 'success',
        'status' => 1,
        'filters' => [
            'orgTypes' => $orgTypes,
            'expRanges' => $expRanges,
            'noOfStudents' => $noOfStudents,
            'orgNames' => $orgNames,
            'leadStatuses' => $leadStatuses
        ]
    ];
    echo json_encode($to_encode);
}

// node-api
elseif (isset($_GET['getLmdData'])) {
    // Fetch and decode JSON payload from request
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);


    // Default results per page is 100, overrideable via payload
    $limit = isset($json['limit']) ? intval($json['limit']) : 100;
    // Default to page 1 if not set (frontend should use 1-based indexing)
    $page = isset($json['page']) ? intval($json['page']) : 1;
    $start = ($page - 1) * $limit;
    // LIMIT clause for SQL
    $limit_query = $limit == 0 ? "" : " LIMIT $start, $limit";

    $jml_filter = "";   // JobMailList (institutes/institute leads)
    $cml_filter = "";   // CorporateMailList (corporate leads)
    $has_jml_specific_filter = false; // Track use of JML-only filters


    // ----- Org Type Filter -----
    $filter_orgTypes = isset($json['orgTypes']) && is_array($json['orgTypes']) ? $json['orgTypes'] : [];
    if (!empty($filter_orgTypes)) {
        // Check if this includes College/Institute
        $jmlTypes = array_intersect(['College', 'Institute'], $filter_orgTypes);
        if (count($jmlTypes) > 0) {
            $escaped = array_map(function($v) use ($databaseConnection) { return "'" . mysqli_real_escape_string($databaseConnection, $v) . "'"; }, $jmlTypes);
            $typeVals = implode(",", $escaped);
            $jml_filter .= " AND jml.contactType IN ($typeVals)";
        } else {
            // Block JML if NOT selected
            $jml_filter .= " AND 0 ";
        }
        // For CML, show only if 'Corporate' present
        if (!in_array('Corporate', $filter_orgTypes)) $cml_filter .= " AND 0 ";
    }

    // Search by orgName for JML (name) and CML (companyName)
    if (!empty($json['orgName'])) {
        $q = mysqli_real_escape_string($databaseConnection, $json['orgName']);
        $jml_filter .= " AND jml.name LIKE '%$q%'";
        $cml_filter .= " AND cml.companyName LIKE '%$q%'";
    }

    // expRange filter (JML only)
    if (!empty($json['expRanges']) && is_array($json['expRanges'])) {
        $escaped = array_map(function($v) use ($databaseConnection) { return "'" . mysqli_real_escape_string($databaseConnection, $v) . "'"; }, $json['expRanges']);
        $ranges = implode(",", $escaped);
        $jml_filter .= " AND jml.expRange IN ($ranges)";
        $has_jml_specific_filter = true; // Flag as JML filter
    }

    // noOfStudents filter (JML only)
    if (!empty($json['noOfStudents']) && is_array($json['noOfStudents'])) {
        $escaped = array_map(function($v) use ($databaseConnection) { return "'" . mysqli_real_escape_string($databaseConnection, $v) . "'"; }, $json['noOfStudents']);
        $nums = implode(",", $escaped);
        $jml_filter .= " AND jml.numberOfCandidates IN ($nums)";
        $has_jml_specific_filter = true; // Flag as JML filter
    }

    // ----- Date from/to filter (JML: createdAt, CML: createdTime) -----
    if (!empty($json['date_from'])) {
        $from = mysqli_real_escape_string($databaseConnection, $json['date_from']) . " 00:00:00";
        $jml_filter .= " AND jml.createdAt >= '$from'";
        $cml_filter .= " AND cml.createdTime >= '$from'";
    }
    if (!empty($json['date_to'])) {
        $to = mysqli_real_escape_string($databaseConnection, $json['date_to']) . " 23:59:59";
        $jml_filter .= " AND jml.createdAt <= '$to'";
        $cml_filter .= " AND cml.createdTime <= '$to'";
    }

    // 'Corporate' NOT selected, block CML
    if ($has_jml_specific_filter && (empty($filter_orgTypes) || !in_array('Corporate', $filter_orgTypes))) {
        $cml_filter .= " AND 0 ";
    }

    // ONLY 'Corporate', block both JML and CML
    if ($has_jml_specific_filter && !empty($filter_orgTypes) && count($filter_orgTypes) == 1 && $filter_orgTypes[0] === 'Corporate') {
        $jml_filter .= " AND 0 ";
        $cml_filter .= " AND 0 ";
    }

    // leadStatuses filter
    if (!empty($json['leadStatuses']) && is_array($json['leadStatuses'])) {
        $statuses = implode(",", array_map(function($v) use ($databaseConnection) {
            return "'" . mysqli_real_escape_string($databaseConnection, $v) . "'";
        }, $json['leadStatuses']));

        // Both JML and CML: ONLY include leads whose emailId appears in sales_observations with these status values
        $jml_filter .= " AND jml.emailId IN (SELECT emailId FROM sales_observations WHERE leadStatus IN ($statuses))";
        $cml_filter .= " AND cml.emailId IN (SELECT emailId FROM sales_observations WHERE leadStatus IN ($statuses))";
    }


    $sql = "SELECT
            jml.id,
            UNIX_TIMESTAMP(jml.createdAt) AS sortValue,
            jml.createdAt AS date,
            jml.name AS orgName,
            jml.contactType AS orgType,
            jml.emailId AS email,
            jml.mobileNumber AS phone,
            'NA' AS personName,
            jml.numberOfCandidates AS noOfStudents,
            jml.expRange AS expRange,
            IFNULL(loc.cityName, '') AS location,
            IFNULL(jml_sv.leadStatus, '') AS leadStatus,
            'JML' AS source
        FROM JobMailList jml
        LEFT JOIN (
            SELECT emailId, MAX(leadStatus) AS leadStatus
            FROM sales_observations
            WHERE emailId IS NOT NULL
            GROUP BY emailId
        ) jml_sv ON jml_sv.emailId = jml.emailId
        LEFT JOIN locations loc ON jml.locationId = loc.id
        WHERE 1 $jml_filter

        UNION ALL

        SELECT
            cml.id,
            UNIX_TIMESTAMP(cml.createdTime) AS sortValue,
            cml.createdTime AS date,
            cml.companyName AS orgName,
            'Corporate' AS orgType,
            cml.emailId AS email,
            cml.mobileNumber AS phone,
            cml.contactName AS personName,
            'NA' AS noOfStudents,
            'NA' AS expRange,
            'NA' AS location,
            IFNULL(cml_sv.leadStatus, '') AS leadStatus,
            'CML' AS source
        FROM corporateMailList cml
        LEFT JOIN (
            SELECT emailId, MAX(leadStatus) AS leadStatus
            FROM sales_observations
            WHERE emailId IS NOT NULL
            GROUP BY emailId
        ) cml_sv ON cml_sv.emailId = cml.emailId
        WHERE 1 $cml_filter

        ORDER BY sortValue DESC
        $limit_query
    ";


    // ----- Execute query and collect results -----
    $query = mysqli_query($databaseConnection, $sql);
    $values = [];
    while ($row = mysqli_fetch_assoc($query)) {
        $values[] = $row;
    }

    // ----- Run separate count queries for pagination -----
    $jml_count_sql = "SELECT COUNT(*) as cnt FROM JobMailList WHERE 1 $jml_filter";
    $cml_count_sql = "SELECT COUNT(*) as cnt FROM corporateMailList WHERE 1 $cml_filter";

    $jml_count_q = mysqli_query($databaseConnection, $jml_count_sql);
    $cml_count_q = mysqli_query($databaseConnection, $cml_count_sql);

    $jml_count = ($jml_count_q && $row = mysqli_fetch_assoc($jml_count_q)) ? intval($row['cnt']) : 0;
    $cml_count = ($cml_count_q && $row = mysqli_fetch_assoc($cml_count_q)) ? intval($row['cnt']) : 0;

    $total_data = $jml_count + $cml_count;

    
    $to_encode = [
        'result' => "success",
        'status' => 1,
        'data' => $values,
        'count' => $total_data
    ];
    echo json_encode($to_encode);
}

// node-api
elseif (isset($_GET['updateInstLeadStatus'])) {
    // Endpoint for institutes/corporates to update lead status by emailId.
    $to_encode = array(
        'result' => "error",
        'message' => "Error while changing institute lead status.",
        'status' => 0,
    );
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);

    if (isset($json) && isset($json['emailId']) && isset($json['leadStatus'])) {
        $emailId = mysqli_real_escape_string($databaseConnection, $json['emailId']);
        $leadStatus = mysqli_real_escape_string($databaseConnection, $json['leadStatus']);

        $checkQuery = mysqli_query($databaseConnection, 
            "SELECT id FROM sales_observations WHERE emailId = '$emailId' LIMIT 1");

        if ($checkQuery && mysqli_num_rows($checkQuery) > 0) {
            // Update existing row
            $updateSql = "UPDATE `sales_observations` 
                        SET `contactDate`=CURDATE(), `nextFollowupDate`=NULL, `leadStatus`='$leadStatus' 
                        WHERE emailId = '$emailId';";
            $update = mysqli_query($databaseConnection, $updateSql);

            if ($update) {
                $to_encode = array(
                    'result' => "Success",
                    'message' => "Institute lead status updated.",
                    'status' => 1
                );
            } else {
                $to_encode = array(
                    'result' => "error",
                    'message' => "Failed to update institute lead status.",
                    'status' => 0
                );
            }
        } else {
            // Insert new row
            $insertSql = "INSERT INTO `sales_observations` 
                        (`candidateId`, `emailId`, `contactDate`, `leadStatus`, `approxTime`)
                        VALUES (0, '$emailId', CURDATE(), '$leadStatus', '0');";
            $insert = mysqli_query($databaseConnection, $insertSql);

            if ($insert) {
                $to_encode = array(
                    'result' => "Success",
                    'message' => "Institute lead status inserted.",
                    'status' => 1
                );
            } else {
                $to_encode = array(
                    'result' => "error",
                    'message' => "Failed to insert institute lead status.",
                    'status' => 0
                );
            }
        }
    } else {
        $to_encode = array(
            'result' => "error",
            'message' => "emailId or leadStatus not supplied.",
            'status' => -1
        );
    }

    echo json_encode($to_encode);
}

else if (isset($_GET['updateCandidateAction'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (isset($json)) {
        $id = mysqli_real_escape_string($databaseConnection, $json['id']);
        $name = mysqli_real_escape_string($databaseConnection, $json['name']);
        $email = mysqli_real_escape_string($databaseConnection, $json['email']);
        
        $query1 = "UPDATE interviewSchedule SET candidateName='$name', emailId='$email' WHERE id='$id'";
        $res1 = mysqli_query($databaseConnection, $query1);
        
        $to_encode = array(
            'status' => $res1 ? 1 : 0,
            'message' => $res1 ? 'Candidate updated successfully' : 'Failed to update'
        );
    } else {
        $to_encode = array('status' => 0, 'message' => 'Invalid JSON');
    }
    echo json_encode($to_encode);
}

else if (isset($_GET['getServiceDashboardFiltersnew2'])) {
    $data = @file_get_contents("php://input");
    $json = json_decode($data, true);
    if (is_array($json)) {
        $values = array();
        
        $userId = filter_var($json['companyId'] ?? null, FILTER_VALIDATE_INT);
        $userType = strtolower(trim((string) ($json['userType'] ?? '')));

        if (!$userId || !in_array($userType, ['admin', 'corporate'], true)) {
            echo json_encode(array("status" => 0, "result" => "error", "message" => "Unauthorized access"));
            exit();
        }

        $userAccessResult = mysqli_query(
            $databaseConnection,
            "SELECT id FROM users WHERE id = " . (int) $userId . " AND usertype = '" . $userType . "' AND active = 'Y' AND deleted_at IS NULL LIMIT 1"
        );
        if (!$userAccessResult || mysqli_num_rows($userAccessResult) !== 1) {
            echo json_encode(array("status" => 0, "result" => "error", "message" => "Unauthorized access"));
            exit();
        }
        if ($userType === 'corporate') {
            $filter9 = "SELECT pr.id, CONCAT(COALESCE(pr.interviewName, ac.name), ' - ', pr.id) AS name, pr.serviceType FROM preInterview pr LEFT JOIN aspiration_company ac ON ac.id = pr.company_id WHERE pr.id != 0 AND pr.interviewType = 'job' AND pr.serviceType = 'IAS' AND LOWER(TRIM(COALESCE(pr.interviewStatus, ''))) = 'active' AND (pr.interviewName IS NOT NULL OR ac.name IS NOT NULL) AND EXISTS (SELECT 1 FROM preInterview_corporate pic WHERE pic.preinterviewId = pr.id AND pic.userId = '" . $userId . "') ORDER BY pr.createdAt DESC, pr.id DESC";
        } else {
            $filter9 = "SELECT pr.id, CONCAT(COALESCE(pr.interviewName, ac.name), ' - ', pr.id) AS name, pr.serviceType FROM preInterview pr LEFT JOIN aspiration_company ac ON ac.id = pr.company_id WHERE pr.id != 0 AND pr.interviewType = 'job' AND pr.serviceType = 'IAS' AND LOWER(TRIM(COALESCE(pr.interviewStatus, ''))) = 'active' AND (pr.interviewName IS NOT NULL OR ac.name IS NOT NULL) ORDER BY pr.createdAt DESC, pr.id DESC";
        }
        
        global $databaseConnection;
        $filter9Result = mysqli_query($databaseConnection, $filter9);
        if (!$filter9Result) {
            echo json_encode(array(
                'status' => 0,
                'result' => 'error',
                'message' => mysqli_error($databaseConnection)
            ));
            exit();
        }
        $values['interviewname'] = mysqli_fetch_all($filter9Result, MYSQLI_ASSOC);

        $values['candidateStatus'] = array(
            array("candidateStatus" => "Incomplete"),
            array("candidateStatus" => "In-Progress"),
            array("candidateStatus" => "Completed"),
            array("candidateStatus" => "All Status")
        );

        $to_encode = array(
            'data' => $values,
            'status' => 1
        );
    } else {
        $to_encode = array(
            'status' => 0,
            'result' => "error"
        );
    }
    echo json_encode($to_encode);
}

else {
    $to_encode = array(
        'result' => 'error',
        'errorCode' => 'Method Does Not exist'
    );
    echo json_encode($to_encode);
} 