<?php
    include_once("CUserSession.php");
    include_once("helper.php");
    include_once("CUtil.php");
    include_once("CProjectInfo.php");
    include_once("CEnums.php");
    include_once("CUser.php");

    function get_user_subscription_type()
    {
        $user = json_decode(getUser($_SESSION["user"]->_id,"_id"));
        $user = $user[0];
        // echo $user->subscription_type;
        // $user_print = json_encode($user);
        // echo $user_print; 
        $ret['response'] = "success";
        $ret['subscription_type'] = $user->subscription_type;
        $ret['supporter_expiry_date'] = $user->supporter_expiry_date;
        $ret['innovator_expiry_date'] = $user->innovator_expiry_date;
        $ret['upgrade_date'] = $user->upgrade_date;
        $ret['ts_created'] = $user->ts_created;
        $ret['email_id'] = $user->email_id;

        // echo " return value is ".json_encode($ret);
        //mail('parasur2@buffalo.edu', 'Thu', $ret);
        return $ret;
    }

    function set_free_subscription_type($email_id_in_db, $exp_type)
    {
        $sql_conn = mysqli_connection();
        if (!($stmt = $sql_conn->prepare("UPDATE `Users_temp` SET subscription_type = ?, supporter_expiry_date = NULL, innovator_expiry_date = NULL WHERE email_id = ?"))){
            $sql_ret =  "Prepare failed: (" . $sql_conn->errno . ") " . $sql_conn->error;
        }

        if(!($stmt->bind_param("ss",$exp_type, $email_id_in_db)))
        { 
            $sql_ret =  "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
        }

        if(!$stmt->execute()) mail('parasur2@buffalo.edu', 'Error', $stmt->error);

        $stmt->close();
        $ret['response'] = "success";
        return $ret; 
    }

    function update_subscription_plan_for_future_date($plan_type, $plan, $email_id_in_db){
        $sql_conn = mysqli_connection();

        if($plan == "supporter_expiry_date"){
            if (!($stmt = $sql_conn->prepare("UPDATE `Users_temp` SET subscription_type = ?, supporter_expiry_date = NULL WHERE email_id = ?"))){
                $sql_ret =  "Prepare failed: (" . $sql_conn->errno . ") " . $sql_conn->error;
            }
        }else if($plan == "innovator_expiry_date"){
            if (!($stmt = $sql_conn->prepare("UPDATE `Users_temp` SET subscription_type = ?, innovator_expiry_date = NULL WHERE email_id = ?"))){
                $sql_ret =  "Prepare failed: (" . $sql_conn->errno . ") " . $sql_conn->error;
            }
        }

        
        if(!($stmt->bind_param("ss",$plan_type,$email_id_in_db)))
        { 
            $sql_ret =  "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
        }

        if(!$stmt->execute()) mail('parasur2@buffalo.edu', 'Error', $stmt->error);
        $stmt->close();
        $ret['response'] = "success";
        return $ret; 
    }

    function set_free_upgrade($sup_exp_date, $purchase_plan, $email_id_in_db)
    {
        $sql_conn = mysqli_connection();

        $date_now = new DateTime();
        $timezone = new DateTimeZone('US/Eastern');
        $date_now->setTimezone($timezone);
        $timestamp_now = (string)$date_now->getTimestamp();
        $supporter_exp_date_tmstmp = strtotime($sup_exp_date);
        $date_diff = $supporter_exp_date_tmstmp - $timestamp_now;
        $no_of_days_left = round($date_diff/86400);
        $innovator_subs_days_after_proration = $no_of_days_left/2;
        $new_date = $timestamp_now + (($innovator_subs_days_after_proration) * 86400);

        if (!($stmt = $sql_conn->prepare("UPDATE `Users_temp` SET subscription_type = ?, date_created = NOW(), innovator_expiry_date = FROM_UNIXTIME($new_date) WHERE email_id = ?"))){
            $sql_ret =  "Prepare failed: (" . $sql_conn->errno . ") " . $sql_conn->error;
        }

        if(!($stmt->bind_param("ss",$purchase_plan,$email_id_in_db)))
        { 
            $sql_ret =  "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
        }

        if(!$stmt->execute()) mail('parasur2@buffalo.edu', 'Thu', $stmt->error);
        mail('parasur2@buffalo.edu', 'FreeUpgradeTestTmst', $supporter_exp_date_tmstmp);
        $stmt->close();

        // Set supporter expiry date to null
        if (!($stmt2 = $sql_conn->prepare("UPDATE `Users_temp` SET supporter_expiry_date = NULL WHERE email_id = ?"))){
            $sql_ret2 =  "Prepare failed: (" . $sql_conn->errno . ") " . $sql_conn->error;
        }

        if(!($stmt2->bind_param("s",
                $email_id_in_db))){
        $sql_ret2 =  "Binding parameters failed: (" . $stmt2->errno . ") " . $stmt2->error;
        }   

        if(!$stmt2->execute()) mail('parasur2@buffalo.edu', 'Thu', $stmt2->error);
        $stmt2->close();
        mysqli_close($sql_conn);
    }

    function set_free_downgrade($innv_exp_date, $purchase_plan, $email_id_in_db)
    {
        $sql_conn = mysqli_connection();

        $date_now = new DateTime();
        $timezone = new DateTimeZone('US/Eastern');
        $date_now->setTimezone($timezone);
        $timestamp_now = (string)$date_now->getTimestamp();
        mail('parasur2@buffalo.edu', 'InnvExpDate', $innv_exp_date);
        $innovator_exp_date_tmstmp = strtotime($innv_exp_date);
        mail('parasur2@buffalo.edu', 'InnvExpDateTmstp', $innovator_exp_date_tmstmp);
        $date_diff = $innovator_exp_date_tmstmp - $timestamp_now;
        $no_of_days_left = round($date_diff/86400);
        mail('parasur2@buffalo.edu', 'DaysLeft', $no_of_days_left);
        $supporter_subs_days_after_proration = $no_of_days_left*2;
        mail('parasur2@buffalo.edu', 'DaysAfterProration', $supporter_subs_days_after_proration);
        if($supporter_subs_days_after_proration > 2190){
            $supporter_subs_days_after_proration = 2190;
        }
        $new_date = $timestamp_now + (($supporter_subs_days_after_proration) * 86400);

        if (!($stmt = $sql_conn->query("SET time_zone = '+0:00'"))){
            $sql_ret =  "Prepare failed: (" . $sql_conn->errno . ") " . $sql_conn->error;
        }
        
        if (!($stmt = $sql_conn->prepare("UPDATE `Users_temp` SET subscription_type = ?, date_created = NOW(), supporter_expiry_date = FROM_UNIXTIME($new_date) WHERE email_id = ?"))){
            $sql_ret =  "Prepare failed: (" . $sql_conn->errno . ") " . $sql_conn->error;
        }

        if(!($stmt->bind_param("ss",$purchase_plan,$email_id_in_db)))
        { 
            $sql_ret =  "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
        }

        if(!$stmt->execute()) mail('parasur2@buffalo.edu', 'Thu', $stmt->error);
        $stmt->close();

        // Set innovator expiry date to null
        if (!($stmt2 = $sql_conn->prepare("UPDATE `Users_temp` SET innovator_expiry_date = NULL WHERE email_id = ?"))){
            $sql_ret2 =  "Prepare failed: (" . $sql_conn->errno . ") " . $sql_conn->error;
        }

        if(!($stmt2->bind_param("s",
                $email_id_in_db))){
        $sql_ret2 =  "Binding parameters failed: (" . $stmt2->errno . ") " . $stmt2->error;
        }   

        if(!$stmt2->execute()) mail('parasur2@buffalo.edu', 'Thu', $stmt2->error);
        $stmt2->close();
        mysqli_close($sql_conn);
    }

    function get_subscription_information()
    {
        $sql_conn = mysqli_connection();
        $clause = Util::escapeObject($clause);
        $message = "success";
                
        $query = "SELECT * FROM  `subscription_types`";
        if (!($stmt = $sql_conn->prepare($query))){
            $message = "Prepare failed: (" . $sql_conn->errno . ") " . $sql_conn->error. $query;
        }
        
        if (!($stmt->execute())) {
            $message = "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
        }
        
        if (!($ret = $stmt->get_result())) {
           $message = "Getting Result failed: (" . $stmt->errno . ") " . $stmt->error;
        }
      
        $stmt->close();
        mysqli_close($sql_conn);

        // check if there are any rows in the result
        if ( $ret->num_rows > 0 )  
        {
        }
        else
        {            
        }  

        // collect the result in the array
        $result = array();
        while($row = mysqli_fetch_array($ret)) {
           $result[] = $row;  
        }

        $r["response"] = $message;
        $r["subscription_types"] = $result;

        return $r;
    }

    // get_user_subscription_type();
    // get_subscription_information();
?>