<?php
include_once("CUserSession.php");
include_once("CStandard.php");
include_once("CQuestion.php");
include_once("CProjectInfo.php");
include_once("CUser.php");
include_once("CProjectDocument.php");
include_once("CPayments.php");
include_once("CPurchase.php");
include_once("charge-credit-card.php");
include_once("CComments.php");
include_once("CProjectSolutions.php");
include_once("CNotificationUserSetting.php");
include_once("CNotification.php");
include_once("CUserSubscription.php");
include_once("CProjectTeams.php");


$G_MAX_IDLE_TIME = 180;
$G_WARNING_TIME = 170;

error_reporting(E_ERROR | E_PARSE);

if(isset($_POST["notification"])){
    if($_POST["notification"] == "GET_USER_SETTINGS"){
        $response = get_notification_user_settings();
        print( json_encode( $response ) );
    } 
    else if($_POST["notification"] == "SET_USER_SETTING"){
        $response = update_notification_user_setting( $_POST["sl_no"], $_POST["email"], $_POST["web_page"] ); 
        print( json_encode( $response ) );
    }
    else if($_POST["notification"] == "GET"){
        $response = get_notifications( $_POST["type"] );
        print( json_encode( $response ) );
    } 
    else if($_POST["notification"] == "SET"){
        $response = set_notifications();
        print( json_encode( $response ) );
    }
    else if($_POST["notification"] == "MARK_READ"){
        $response = read_notifications($_POST["sl_no"]);
        print( json_encode( $response ) );
    }
    die();
}

if(isset($_POST["Review_checkbox_value"])){
    if($_POST["Review_checkbox_value"] == "SET"){
        $response = set_solution_review_checkbox_value( $_POST["project_id"], $_POST["solution_id"], $_POST["value"] ); // Function in CComment.php
        print( json_encode( $response ) );
    }
    else if($_POST["Review_checkbox_value"] == "GET"){
        $response = get_solution_review_checkbox_value( $_POST["project_id"], $_POST["solution_id"] ); 
        print( json_encode( $response ) );
    }
    else  if($_POST["Review_checkbox_value"] == "SET_ALL"){
        $response = set_solution_review_checkboxes_value( $_POST["project_id"], $_POST["solution_id"], $_POST["value"] ); // Function in CComment.php
        print( json_encode( $response ) );
    }
    else if($_POST["Review_checkbox_value"] == "GET_ALL"){
        $response = get_solution_review_checkboxes_value( $_POST["project_id"], $_POST["solution_id"] ); 
        print( json_encode( $response ) );
    }
    die();
}

if(isset($_POST["comment"])){
    if($_POST["comment"] == "SET"){
        $response = set_comment( $_POST["project_id"], $_POST["solution_id"], $_POST["text"], $_POST["visibility"] ); // Function in CComment.php
        print( json_encode( $response ) );
    }
    else if($_POST["comment"] == "SET_VISIBILITY"){
        $response = set_comment_visibility( $_POST["project_id"], $_POST["solution_id"], $_POST["visibility"] );
        print( json_encode( $response ) );
    }
    else if($_POST["comment"] == "SET_VISIBILITY_BY_NO"){
        $response = set_comment_visibility_by_no( $_POST["sl_no"], $_POST["visibility"] );
        print( json_encode( $response ) );
    }
    else if($_POST["comment"] == "GET"){
        $response = get_comments( $_POST["project_id"], $_POST["solution_id"] );
        print( json_encode( $response ) );
    }
    else if($_POST["comment"] == "GET_ALL"){
        $response = get_all_comments( $_POST["project_id"] );
        print( json_encode( $response ) );
    }
    else if($_POST["comment"] == "UPDATE_TEXT"){
        $response = update_comment_text( $_POST["sl_no"], $_POST["text"] );
        print( json_encode( $response ) );
    }
    else if($_POST["comment"] == "DELETE"){
        $response = set_comment_visibility_by_no( $_POST["sl_no"], "deleted" );
        print( json_encode( $response ) );
    }
    else if($_POST["comment"] == "GET_SOLUTIONS_STATUS"){
        $response = get_comment_solution_status( $_POST["project_id"] );
        print( json_encode( $response ) );
    }
    die();
}

if (isset($_POST['idle_time']))
{
    // $G_MAX_IDLE_TIME = 2;
    $attr = $_POST['idle_time'];
    $ret["action"] = "none";
    if($attr === "REFRESH")
    {
        $_SESSION['start_time'] = time();
        $ret["status"] = "success";
        $ret["idle_time"] = (time() - $_SESSION['start_time'])/60;
    }
    else if($attr === "GET" )
    {
        $idle_time = (time() - $_SESSION['start_time'])/60;
        $ret["idle_time"] = $idle_time;
        $ret["status"] = "success";

        if(!isLoggedIn())
        {
            $ret["action"] = "none";
        }
        // logout from server side
        else if( $idle_time > $G_MAX_IDLE_TIME )
        {
            $ret["action"] = "logout_user";
            logoutUser();
        }
        else if( $idle_time > $G_WARNING_TIME )
        {
            $ret["action"] = "warn_idle_user";
            // logoutUser();
        }
    }
    else
    {
        $ret["status"] = "failure";
        $ret["message"] = "invalid_argument";
    }
    print(json_encode($ret));
    die();
}

if(isset($_POST['register']))
{
    $_SESSION['start_time'] = time();
}
else if( time() - $_SESSION['start_time'] > ($G_MAX_IDLE_TIME*60) ) { //subtract new timestamp from the old one
    // echo"<script>alert('15 Minutes over!');</script>";
    logoutUser();
    $ret["status"] = "failure";
    $ret["message"] = "user_inactive";
    $ret["action"] = "logout_user";
    print(json_encode($ret));
    die();
}
else
{
    $_SESSION['start_time'] = time(); //set new timestamp
}

if(isset($_POST['chapter'])){

    $chapter = $_POST['chapter'];
    $chapter = mysqli_real_escape_string(mysqli_connection(), $chapter);

    print(API($chapter));


} else if(isset($_POST['columns'])){

    $columns = $_POST['columns'];

    if($columns === "GOALS"){
        print(getGoalColumnNames());
    } elseif($columns === "PHASES") {
        print(getPhaseColumnNames());
    }

} else if(isset($_POST['register'])){
    $columns = $_POST['register'];
    if($columns === "QUESTIONS"){
        print(getSecurityQuestions());
    }

    if($columns === "PROJECT_SIGNUP_ROLES"){
        print(getSignupRoles());
    }

    if($columns === "PROJECT_SIGNUP_REASON"){
        print(getSignupReasons());
    }

    if($columns === "REGISTER"){
        $data = json_decode(stripslashes( $_POST['data']), true);
        $recaptcha = $data['recaptcha'];

        // verify recaptcha
        $url ="https://www.google.com/recaptcha/api/siteverify";
        $fields = array('secret' => '6LcmTSATAAAAAFtJj2F9XlF6wl9gUmIX9Vu-4af7', 'response' => $recaptcha);

        //open connection
        $ch = curl_init($url);

        //set the url, number of POST vars, POST data
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_POST,true);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$fields);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        //execute post
        $captchaResponse = curl_exec($ch);
        curl_close($ch);
        $captchaResponse = json_decode($captchaResponse,true);
        $ret = new stdClass();
        if($captchaResponse['success']){
            $ret = createNewUser($data['email_id'], $data['password'],
                                $data['first_name'], $data['middle_name'], $data['last_name'],
                                $data['organization_id'], $data['job_title'],$data['authtype_id'], $data['securityquestion_id'], $data['securityquestion_ans'], $data['free_trial_expiry_date'], $data['phone'],$data['country_name'],$data['country_code'], $data['signuprole_id'], $data['signupreason_id']);


            $ret = json_decode($ret);
            $ret->mail = false;
            // if($ret->response){
            //     $ret->mail = Util::send_mail_SMTP($data['email_id'], "Registration Confirmation", "Thank you for registering with the isUD website. Please login to visit the inclusive design solutions.");
            // }
        } else {
            $ret->response = false;
            $ret->message = "Recaptcha verification failed.";
        }

        //$ret->m = $captchaResponse['challenge_ts']." ".$captchaResponse['success'];

        print(json_encode($ret));
    }

    if($columns === "LOGIN"){
        $username = $_POST['username'];
        $password = $_POST['password'];
        print(validateUser($username, $password));
    }

    if($columns === "GETUSER"){
        $username = $_POST['username'];
        print(getUser($username));
    }

    if($columns === "EDIT_PROFILE_RETRIEVE"){
        $ret["response"] = isLoggedIn();
        $ret["data"] = getPublicUserData($_SESSION["user"]);
        print(json_encode($ret));
    }

    if($columns === "EDIT_PROFILE_SAVE"){
        $data = json_decode(stripslashes( $_POST['data']), true);
        $ret = UpdateUser($data['email_id'], $data['password'],
                                $data['first_name'], $data['middle_name'], $data['last_name'],
                                $data['organization_id'], $data['authtype_id'], $data['securityquestion_id'], $data['securityquestion_ans'],$data['phone'],$data['country_name'],$data['country_code']);

        print($ret);
    }

    if($columns === "LOGOUT"){
        logoutUser();
    }

    if($columns === "RESET_PASSWORD_PREP"){
        $username = $_POST['username'];
        print(resetPassword_prep($username));
    }

    if($columns === "RESET_PASSWORD_INIT"){
        $username = $_POST['username'];
        $securityanswer = $_POST['securityanswer'];

        $ret = new stdClass();
        $ret = resetPassword_init($username, $securityanswer);
        $ret = json_decode($ret);
        $ret->mail = false;

        $msg = "<html><body>";
        $msg.= 'Hi,';
        $msg.= '<p>We have received a request to reset your isUD password.<br>';
        $msg.= 'Your username is '.$username.'<br>';
        $msg.= '<a href= "https://thisisud.com/dashboard/register.php?reset=true&rl='.$ret->message.'">RESET PASSWORD </a>';
        $msg.=  '<br>If the link above does not work, you can copy and paste the following into your browser:<br>';
        $msg.= "https://thisisud.com/dashboard/register.php?reset=true&rl=".$ret->message;
        $msg.= "<br>If you did not request a new password, or you have received this notification in error, you may ignore this e-mail and your password will remain unchanged.</p>";
        $msg.= "<b>isUD Team</b><br><br>";
        $msg.= '</body></html>';

        $ret->msg = $msg;

        if($ret->response){
            //$ret->mail = Util::send_mail_SMTP($username, "isUD Password Reset link", "Please use the following link to reset your password : http://www.udeworld.com/uds/V2/register.php?reset=true&rl=".$ret->message." . <br>The link expires in 3 days.<br><b>IsUD Team.</b>");
            $ret->mail = Util::send_mail_SMTP($username, "isUD Password Reset link", $msg);
        }
        print(json_encode($ret));
    }

    if($columns === "RESET_PASSWORD_CONF"){
        $password = $_POST['password'];
        $confirmpassword = $_POST['confirmpassword'];
        $reset_link = $_POST['reset_link'];

        $ret = resetPassword_conf($reset_link, $password, $confirmpassword);
        print($ret);
    }

    if($columns === "RE_CONFIRM_PASS"){
        $password = $_POST['password'];
        $ret = checkPassword($_SESSION["user"]->email_id, $password);
        print($ret);
    }
} else if(isset($_POST['contact'])){
    $contact = $_POST['contact'];

    if($contact === "CONTACT_EMAILER"){
        $data = json_decode(stripslashes( $_POST['data']), true);
        $name = $data['name'];
        $email = $data['email'];
        $comment = $data['comment'];

        $msg = "<html><body><table style='max-width: 800px; border-radius: 5px; border: 1px solid black;'>";
        $msg.= '<tr><td style="width:180px; background-color: gray; color: white; padding: 10px;">Name</td><td style="width: 600px; padding: 10px;">'.$name.'</td></tr>';
        $msg.= '<tr><td style="width:180px; background-color: gray; color: white; padding: 10px;">Email</td><td style="width: 600px; padding: 10px;">'.$email.'</td></tr>';
        $msg.= '<tr><td style="width:180px; background-color: gray; color: white; padding: 10px;">Question/Comment</td><td style="width: 600px; padding: 10px;">'.$comment.'</td></tr>';
        $msg.= "</table></body></html>";
        $ret = new stdClass();
        $ret->response = true;
        $ret->mail = false;
        if($ret->response){
            $ret->mail = Util::send_mail_SMTP("info@thisisud.com", "New question/comment from: ".$name, $msg);
        }
        print(json_encode($ret));
    }
} else if(isset($_POST['query'])){
    $query = $_POST['query'];

    if($query === "sr_version"){
        $ret = new stdClass();
        $ret->response = ($_SESSION["user"]->uses_sr === 1);
        print(json_encode($ret));
    }
} else if(isset($_POST['survey_complete'])){
    updateSurveyStatus($_POST['survey_complete']);
} else if(isset($_POST['all_users'])){
    //Original Funciton getAllUsers();
    // print(getAllUsers($_POST['all_users']));
    print(fetchAllUsersData());
} else if(isset($_POST['project'])){

    if($_POST['project'] === "CREATE"){       
        $data = json_decode(stripslashes( $_POST['data']), true);
        $ret = createProjectInfo($data['title'], $data['owner'], $data['architect'], $data['habitable_floor_area'], $data['site_area'], $data['pre_certification'], $data['project_cost'], isset($data['a_start_date']), isset($data['a_end_date']), $data['building_type'], $data['service_type'], $data['certification_type'], $data['project_scope'], $data['contact_person'], $data['contact_email'], $data['contact_telephone'], $data['contact_telephone_c_code'],$data['address_line_1'], $data['address_line_2'], $data['city'], $data['state'], $data['country'], $data['zipcode'], $data['project_submission_type'], $data['project_type']);
        print(json_encode($ret)); 

        // $emailDemo = new stdClass();        
        // Util::send_mail_SMTP("hsubryan@buffalo.edu", "New Project Announcement", "A new ISUD Project has been created <br><br>Title: ".$data['title']."<br>Contact Person: ".$data['contact_person']."<br>Contact Email: ".$data['contact_email']);
        // print(json_encode($emailDemo->mail));
    }

    if($_POST['project'] === "LIST"){
        // -1 for listing all projects
        print(getProjectInfo(-1));
    }

    if($_POST['project'] === "DETAILS"){
        // -1 for listing all projects
        print(getProjectInfo($_POST["id"]));
    }

    if($_POST['project'] === "VALIDATE_CURRENT_USER"){
        // -1 for listing all projects
        print(validateCurrentUser($_POST["id"]));
    }

    if($_POST['project'] === "SELECT_PROJECT"){
        // -1 for listing all projects
        print(updateRetainedProject($_POST["project_id"], $_POST["creating_user_id"]));
    }

    if($_POST['project'] === "UPDATE_INFO"){
        // -1 for listing all projects
        $data = json_decode(stripslashes( $_POST['data']), true);
        $ret = updateProjectInfo($data["id"], $data['title'], $data['owner'], $data['architect'], $data['habitable_floor_area'], $data['site_area'], $data['pre_certification'],  $data['project_cost'], $data['a_start_date'], $data['a_end_date'], $data['building_type'], $data['project_scope'], $data['contact_person'], $data['contact_email'], $data['contact_telephone'], $data['contact_telephone_c_code'],$data['address_line_1'], $data['address_line_2'], $data['city'], $data['state'], $data['country'], $data['zipcode'], $data['project_submission_type']);
        print($ret);

        // Adding services seperately
        $sql_conn = mysqli_connection();
        $query = "UPDATE `UD_P_Info` SET `service_type` = '".$data['service_type']."', `certification_type` = '".$data['certification_type']."' WHERE `UD_P_Info`.`_id` = "."'".$data["id"]."'";                
        $result = mysqli_query($sql_conn, $query);   
        $sql_conn->close();  
    }

    if($_POST['project'] === "PHASE_UPDATE"){
       
        $ret = updateProjectPhase($_POST["id"],$_POST["projectPhase"]);
        print($ret);
    }

    if($_POST['project'] === "UPDATE"){
        // -1 for listing all projects
        print(updateProjectSolutionValues($_POST["id"],$_POST["data"],$_POST["target"], $_POST["applicable_credits"], $_POST["earned_credits"], $_POST["bonus_credits"],0,0, $_POST["award_percentage"], $_POST["award_category"], $_POST["h1_credits_applicable"], $_POST["h1_credits_earned"]));
    }

    if($_POST['project'] === "DELETE"){
        // -1 for listing all projects
        print(deleteProject($_POST["id"], $_SESSION["user"]->_id));
    }

    if($_POST['project'] === "SUBMIT_REVIEW"){
        print(submitProjectForReview($_POST["id"],$_POST["submit_type"]));
    }

    if( $_POST['project'] === "PRE_CHECK_SUBMIT_REVIEW" )
    {
        $project_id = $_POST['project_id'];
        $submit_type = $_POST['submit_type'];
        print(json_encode( submitProjectCheck($project_id, $submit_type)));
    }

    if($_POST['project'] == "SUBMIT_DISCUSSION"){
        $response = submitProjectForDiscussion( $_POST["project_id"] );
        print( json_encode( $response ) );
    }
    
    if($_POST['project'] == "SUBMIT_COMPLETION"){
        $response = submitProjectForCompletion( $_POST["project_id"] ); 
        print( json_encode( $response ) );
    }

    if( $_POST['project'] === "GET_DICT" )
    {
        $project_id = $_POST['project_id'];
        print( json_encode( createDictionaryForSpecificProject ( $project_id )));
    }

} else if(isset($_POST['document'])){
    if($_POST['document'] === "DELETE"){
        // -1 for listing all projects
        print(deleteProjectDocument_DB($_POST["project_id"], $_POST["document_id"]));
    }

    else if($_POST['document'] === "LIST"){
        // -1 for listing all projects
        print(getProjectDocuments_DB($_POST["project_id"]));
    }

    else if($_POST['document'] === "GET_DETAILS"){
        // getting details about specific documents. which check box is checked and which is not
        print( json_encode(getProjectDocumentDetails($_POST["project_id"], $_POST["document_id"])) );
    }

    else if($_POST['document'] === "UPDATE_DETAILS"){
        // getting details about specific documents. which check box is checked and which is not
        print( json_encode(updateDocumentDetails($_POST["project_id"], $_POST["document_id"], $_POST["types"], $_POST["name"], $_POST["description"])) );
    }
}
/*Called when user submits info to payments page. Makes call to cpayments and insert records in the order and the billing table.*/
else if(isset($_POST['payments'])){
    if($_POST['payments']=="GET_BILLING"){
        //shows billing information on payments.php page on load
        print(getProjectInfo($_POST['id']));
    }
    else if($_POST['payments']=="GET_UBF_BILLING_INFO"){   //CPurchase.php
        //read ubf billing info on payments.php to check the status of payment
        print(get_ubf_billing_info($_POST['id']));
    }
    else if($_POST['payments']=="BILLING_SUBMIT"){
        //echo "entered billing submit in api";
         $data = $_POST['data'];
        /*inserts record in billing table. If the response is true then insert order record.
            TODO: delete last entry from billing if order fails.
        */
         $response = insert_billing_info($data['project_id'], $data['firstname'], $data['lastname'], $data['address'], $data['city'], $data['state'], $data['country'], $data['zip'], $data['email'], $data['phone']);

         if($response['response']==true){
            $res = insert_order_info($response['order_id'], $data['project_id'], $data['order_info'], $data['cost']);
            print(json_encode($res));
         }
         else{
            print(json_encode($response));
         }
        // //ChromePhp::log("response in API: "+$response);

    }else if($_POST['payments']=="SUBMIT_BILLING_INFO"){
        $data = $_POST['data'];
        $response = insertBillingInfo($data['project_id'], $data['billing_first_name'], $data['billing_last_name'], $data['billing_address'], $data['billing_city'], $data['billing_state'], $data['billing_country'], $data['billing_zip'], $data['billing_email'], $data['billing_phone']);
        print(json_encode($response));
    }
    else if($_POST['payments']=="GET_BILLING_INFO"){
        print(getBillingInfo($_POST['id']));
    }
}
/*Called when user submits credit card information for payment. Makes call to authorize api(charge-credit-card) and Cpurchase. Returns response in form of message, response code and exp date of card.*/
else if(isset($_POST['purchase'])){
    /*loads information on purchase page by calling getpurchaseinfo() in Cpurchase.
    TODO: do not redirect user to purchase page directly by url. Only payments page should lead user to purchase page.
    */
        if($_POST['purchase'] == "GET_PURCHASE"){
            $response = getpurchaseinfo();
            print(json_encode($response));
            // print("call to purchase succesful");
        }

        /*makes call to charge-credit-card. Validates card info format and update payments and purchase records.*/
        if($_POST['purchase'] == "CHARGE_CREDIT"){
            $data = json_decode($_POST['details'],true);
             $validate = validatedata($data);
            if($validate['response']){
                $response = chargeCreditCard($data['code'], $data['card'], $data['expdate']);
                print(json_encode($response));
            }else{
                print(json_encode($response));
            }
            //print($validate['response'].";".$validate['message']);
        }
    }

 else if(isset($_POST["signup"])){
    if($_POST["signup"] == "NEW_SIGNUP"){
        $response=add_mailid_to_news_signup_db($_POST["mailID"]);
        print(json_encode($response));
    }
 }
 else if(isset($_POST["user_info"])){
   if($_POST["user_info"] == "USER_EMAIL"){
     $response=get_user_mail_from_db($_POST["user_id"]); // Function in CUser.php
     print(json_encode($response));
   }
 }
 
 if(isset($_POST["user_info"]) == "SUBSCRIPTION_TYPE"){
    $response=get_subscription_type_of_user($_POST["user_id"]); // Function in CUser.php
    print(json_encode($response));
 }
 /*
 else if(isset($_POST["comment"])){
    if($_POST["comment"] == "SET"){
        $response = set_comment( $_POST["project_id"], $_POST["solution_id"], $_POST["text"] ); // Function in CComment.php
        print( json_encode( $response ) );
    }
    else if($_POST["comment"] == "GET"){
        $response = get_comments( $_POST["project_id"], $_POST["solution_id"] );
        print( json_encode( $response ) );
    }
  }
  */


  /******** Code starts for Admin Dashboard Statistics ********/

if(isset($_POST['dashboard']) === "PROJSTATS"){
    print(getProjectStats());
} 

if(isset($_POST['dashboard']) === "USERSTATS"){
    print(getUserStats());
}

if(isset($_POST['dashboard']) === "SUBSCRIPTION_TYPE"){
    $ret = get_user_subscription_type();
    print(json_encode($ret));
}

if(isset($_POST['dashboard']) === "FREE_UPGRADE"){
    set_free_upgrade($_POST["sup_expiry_date"], $_POST["purchase_plan"], $_POST["email_id_in_db"]);
}

if(isset($_POST['dashboard']) === "FREE_DOWNGRADE"){
    set_free_downgrade($_POST["innv_expiry_date"], $_POST["purchase_plan"], $_POST["email_id_in_db"]);
}

if(isset($_POST['dashboard']) === "UPDATE_SUBSCRIPTION_PLAN_FOR_FUTURE_DATE"){
    $ret = update_subscription_plan_for_future_date($_POST["plan_type"], $_POST["plan"], $_POST["email_id_in_db"]);
    print(json_encode($ret));
}

if(isset($_POST['dashboard']) === "SET_FREE_SUBSCRIPTION"){
    set_free_subscription_type($_POST["email_id_in_db"], $_POST["exp_type"]);
    print(json_encode($ret));
}


/******** Code starts for Admin Dashboard Statistics  ********/


/******** VERIFY EMAIL  ********/
/******** Using same logic as forget password  ********/

if(isset($columns) && $columns === "VERIFY_EMAIL_SEND"){
        $username = $_POST['username'];

        $ret = new stdClass();
        $ret = verifyEmail_init($username);
        $ret = json_decode($ret);
        $ret->mail = false;

        $msg = "<html><body>";
        $msg.= 'Hi,';
        $msg.= '<p>Thank you for creating an isUD account. To complete your profile and start using isUD, you will need to verify your email address using the link below.<br>';
        $msg.= 'Your username is '.$username.'<br>';
        $msg.= '<a href= "https://thisisud.com/dashboard/verify.php?verify=true&user='.$username.'&vtoken='.$ret->message.'"> VERIFY EMAIL </a>';
        $msg.=  '<br>If the link above does not work or broken, please copy and paste the following link into your browser tab:<br>';
        $msg.= "https://thisisud.com/dashboard/verify.php?verify=true&user='.$username.'&vtoken=".$ret->message;
        $msg.= "<br> The verification link will expire in 24 hours. </p>";
        $msg.= "<b>isUD Team</b><br><br>";
        $msg.= '</body></html>';

        $ret->msg = $msg;

        if($ret->response){
                $ret->mail = Util::send_mail_SMTP($username, "isUD -Verify your email address today!", $msg);        
        }
        print(json_encode($ret));
    }

    if(isset($columns) && $columns === "VERIFY_EMAIL_CONF"){
       
        $reset_link = $_POST['reset_link'];

        $ret = verifyEmail_conf($reset_link);
        print($ret);
    }

/******** VERIFY EMAIL  ********/

/******** Generic Send email API *******/
if(isset($_POST['notify'])){
    
    if($_POST['notify'] === "NOTIFY_BY_EMAIL"){

        $ret = Util::send_mail_SMTP($_POST['destination_email'], $_POST['subject'], $_POST['message_body']);
        print($ret);
    }

}


/////UPDATE SESSION VARIABLE UPON VERIFY AND ALREADY LOGGEDIN

if(isset($_POST['session_update'])){
    if($_POST['session_update'] === "UPDATE_VERIFICATION"){
        $_SESSION['is_verified'] = 1;
    }
}

/*****Project TEAM APIs******/

if(isset($_POST['projectTeam'])){

    if($_POST['projectTeam'] === "CREATE"){
        // $data = json_decode(stripslashes( $_POST['data']), true);
        // createProjectInfo($project_id, $user_id, $project_permission_id, $status);
        $ret = createProjectTeam($_POST['project_id'], $_POST['user_id'], $_POST['project_permission_id'],  $_POST['project_role_id'], $_POST['status']);
        // print(json_encode($ret));
    }

    if($_POST['projectTeam'] === "UPDATE"){
        // $data = json_decode(stripslashes( $_POST['data']), true);
        // createProjectInfo($project_id, $user_id, $project_permission_id, $status);
        $ret = updateProjectTeam($_POST['project_id'], $_POST['user_id'], $_POST['project_permission_id'],  $_POST['project_role_id'], $_POST['status']);
        print(json_encode($ret));
    }

    if($_POST['projectTeam'] === "LIST"){
        print(getAllProjectMembers($_POST['project_id']));
    }

    if($_POST['projectTeam'] === "TEAMINVITE"){
        $ret = createMemberInvite($_POST['owner_id'],$_POST['project_id'], $_POST['user_email'], $_POST['project_role_id'], $_POST['project_permission_id']);
        print(json_encode($ret));
    }

    if($_POST['projectTeam'] === "GET_INVITES"){
        $ret = getAllTeamInvitations($_POST['project_id']);
        print(json_encode($ret));
    }
////EDIT THIS
    if($_POST['projectTeam'] === "UPDATE_SESSION_STATUS"){
        $ret = updateStatusOnProject($_POST['project_id'], $_POST['user_id'], $_POST['edit_status']);
        print(json_encode($ret));
    }
    if($_POST['projectTeam'] === "CHECK_SESSION_STATUS"){
        $ret = checkEditingStatusOnProject($_POST['project_id']);
        print(json_encode($ret));
    }
    

    // if($_POST['project'] === "DETAILS"){
    //     // -1 for listing all projects
    //     print(getProjectInfo($_POST["id"]));
    // }

    // if($_POST['project'] === "VALIDATE_CURRENT_USER"){
    //     // -1 for listing all projects
    //     print(validateCurrentUser($_POST["id"]));
    // }

    // if($_POST['project'] === "UPDATE_INFO"){
    //     // -1 for listing all projects
    //     $data = json_decode(stripslashes( $_POST['data']), true);
    //     $ret = updateProjectInfo($data["id"], $data['title'], $data['owner'], $data['architect'], $data['habitable_floor_area'], $data['site_area'], $data['cost'],
    //                              $data['a_start_date'], $data['a_end_date'], $data['building_type'], $data['project_scope'], $data['contact_person'], $data['contact_email'], $data['contact_telephone'], $data['contact_telephone_c_code'],
    //                              $data['address_line_1'], $data['address_line_2'], $data['city'], $data['state'], $data['country'], $data['zipcode'], $data['project_submission_type']);
    //     print($ret);
    // }

    // if($_POST['project'] === "PHASE_UPDATE"){
       
    //     $ret = updateProjectPhase($_POST["id"],$_POST["projectPhase"]);
    //     print($ret);
    // }

    // if($_POST['project'] === "UPDATE"){
    //     // -1 for listing all projects
    //     print(updateProjectSolutionValues($_POST["id"],$_POST["data"],$_POST["target"], $_POST["applicable_credits"], $_POST["earned_credits"], $_POST["bonus_credits"],0,0, $_POST["award_percentage"], $_POST["award_category"], $_POST["h1_credits_applicable"], $_POST["h1_credits_earned"]));
    // }

    // if($_POST['project'] === "DELETE"){
    //     // -1 for listing all projects
    //     print(deleteProject($_POST["id"], $_SESSION["user"]->_id));
    // }

    // if($_POST['project'] === "SUBMIT_REVIEW"){
    //     print(submitProjectForReview($_POST["id"],$_POST["submit_type"]));
    // }

    // if( $_POST['project'] === "PRE_CHECK_SUBMIT_REVIEW" )
    // {
    //     $project_id = $_POST['project_id'];
    //     $submit_type = $_POST['submit_type'];
    //     print(json_encode( submitProjectCheck($project_id, $submit_type)));
    // }

    // if($_POST['project'] == "SUBMIT_DISCUSSION"){
    //     $response = submitProjectForDiscussion( $_POST["project_id"] );
    //     print( json_encode( $response ) );
    // }
    
    // if($_POST['project'] == "SUBMIT_COMPLETION"){
    //     $response = submitProjectForCompletion( $_POST["project_id"] ); 
    //     print( json_encode( $response ) );
    // }

    // if( $_POST['project'] === "GET_DICT" )
    // {
    //     $project_id = $_POST['project_id'];
    //     print( json_encode( createDictionaryForSpecificProject ( $project_id )));
    // }
}

?>