<?php
// This php file is to receive information from UBF checkout after the payment and it resides in ubf folder (folder different from that of where other php files reside). Hence include other php files into this php accordingly
include_once("CUserSession.php");
include_once("helper.php");
include_once("CUtil.php");
include_once("CProject.php");

// Silent Post Variables - Start here
$project_id = "pq_253l242522"; /* Obtain Project ID to which the payment transaction occurred*/
$project_submission_type = "Self Certification";
$authnet_transact_id = print_r($_POST['authnet_transaction_id'], true); /* Authorize.net transaction ID */
$bank_acct_last_4_digits = print_r($_POST['bank_acct_last_4_digits'], true);/* The last 4 digits of the bank account charged.*/
$billing_first_name = print_r($_POST['billing_first_name'], true);/* Payer's billing first name */
$billing_last_name = print_r($_POST['billing_last_name'], true);/* Payer's billing last name*/
$billing_address = print_r($_POST['billing_address'], true);/* Payer's billing street*/
$billing_city = print_r($_POST['billing_city'], true);/* Payer's billing city*/
$billing_state = print_r($_POST['billing_state'], true);/* Payer's billing state*/
$billing_zip = print_r($_POST['billing_zip'], true);/* Payer's billing zip*/
$billing_country = print_r($_POST['billing_country'], true);/* Payer's billing country*/
$billing_email = print_r($_POST['billing_email'], true);/* Payer's billing email*/
$billing_phone = print_r($_POST['billing_phone'], true);/* Payer's billing phone number*/
$card_last_4_digits = print_r($_POST['card_last_4_digits'], true);
$card_type = print_r($_POST['card_type'], true);
$merchant_email = print_r($_POST['merchant_email'], true);
$pay_method = print_r($_POST['pay_method'], true); 
$email_id_in_db = print_r($_POST['items'][0]['custom']['email_id_in_db'], true);
$chosen_price_plan = print_r($_POST['items'][0]['custom']['chosen_price_plan'],true);
$supporter_expiry_date = print_r($_POST['items'][0]['custom']['supporter_expiry_date'],true);
$innovator_expiry_date = print_r($_POST['items'][0]['custom']['innovator_expiry_date'],true);
$chosen_price = print_r($_POST['items'][0]['custom']['chosen_price'],true);
$chosen_downgrade_plan = print_r($_POST['items'][0]['custom']['chosen_downgrade_plan'],true);
$plan_type = print_r($_POST['items'][0]['custom']['plan_type'],true);
$item_name =  print_r($_POST['items']['0']['item_name'], true);
$purchase_plan = explode(" ", $item_name)[1];
$shipping = print_r($_POST['items']['0']['shipping'], true);/* Order shipping amount*/

$shipping_first_name = print_r($_POST['shipping_first_name'], true);/* Payer's shipping first name*/
$shipping_last_name = print_r($_POST['shipping_last_name'], true);/* Payer's shipping last name*/
$shipping_address = print_r($_POST['shipping_address'], true);/* Payer's shipping street*/
$shipping_city = print_r($_POST['shipping_city'], true);/* Payer's shipping city*/
$shipping_state = print_r($_POST['shipping_state'], true);/* Payer's shipping state*/
$shipping_zip = print_r($_POST['shipping_zip'], true);/* Payer's shipping zip*/
$shipping_country = print_r($_POST['shipping_country'], true);/* Payer's shipping country*/
$site_code = print_r($_POST['site_code'], true);/* The passed-in site_code*/
$sub_total = print_r($_POST['items']['0']['sub_total'], true);/* Order subtotal. Includes tax and shipping.*/
$tax = print_r($_POST['items']['0']['tax'], true);/* Order tax*/
$total_amount = print_r($_POST['items']['0']['total_amount'], true);/* Order total amount*/

$ubf_transaction_id = print_r($_POST['ubf_transaction_id'], true);/* UBF unique transaction identifier (UBF's Transaction ID)*/
$x_authnet_auth_code = print_r($_POST['x_authnet_auth_code'], true);/* Authorize.net authorization or approval code*/
$x_avs_code = print_r($_POST['x_avs_code'], true);
$x_response_code = print_r($_POST['x_response_code'], true);/* Authorize.net response code:*/

$x_response_reason_text = print_r($_POST['x_response_reason_text'], true);
$x_response_reason_code = print_r($_POST['x_response_reason_code'], true);
$x_response_sub_code = print_r($_POST['x_response_sub_code'], true);

mail('parasur2@buffalo.edu', 'isUD Live Dashboard', 'Passing through Silent Post.');

// Silent Post Variables - End here
if($x_response_code == 1){

if($plan_type=="free"){
    if($purchase_plan == "Supporter"){
        $subs_in_years = $total_amount/500;
    }else if($purchase_plan == "Innovator"){
        $subs_in_years = $total_amount/1000;
    }
    $date = new DateTime();
    $exp_in_string = "+$subs_in_years years";
    $exp = $date->modify($exp_in_string);
    $new_date = (string)$exp->getTimestamp();
}

//For Downgrade to Supporter
if($plan_type!="free" && $purchase_plan == "Supporter"){
    $subs_in_years = $total_amount/500;
    if($supporter_expiry_date!=null){
        $new_date = strtotime("+$subs_in_years years", strtotime($supporter_expiry_date));
    }else if($chosen_downgrade_plan == "subLater"){
        $new_date = strtotime("+$subs_in_years years", strtotime($innovator_expiry_date));
    }else{
        $date = new DateTime();
        $exp_in_string = "+$subs_in_years years";
        $exp = $date->modify($exp_in_string);
        $new_date = (string)$exp->getTimestamp();
    }
}

// When upgrading to innovator 
if($purchase_plan == "Innovator"){
    $subs_in_years = $total_amount/1000;
    // Renewing the innovator plan
    if($plan_type=="Innovator"){
        $new_date = strtotime("+$subs_in_years years", strtotime($innovator_expiry_date));
    }
    else if($plan_type=="Supporter"){
        $supporter_exp_date_tmstmp = strtotime($supporter_expiry_date);
        if($chosen_price_plan == "subLater"){
            $new_date = strtotime("+$subs_in_years years", $supporter_exp_date_tmstmp);
        }
        else{
            $date_now = new DateTime();
            $timezone = new DateTimeZone('US/Eastern');
            $date_now->setTimezone($timezone);
            $timestamp_now = (string)$date_now->getTimestamp();
            //$timestamp_now = 1634107509; // Oct 13th, 2021 - One year exactly from subscription.
            //$timestamp_now = 1647153909; // March 13th, 2022 - One and half year from subscription.
            //$timestamp_now = 1668494709; // Nov 15th, 2022 - One and half year from subscription.
            $date_diff = $supporter_exp_date_tmstmp - $timestamp_now;
            $no_of_days_left = round($date_diff/86400);
            $amount_due = (per_day_supporter_sub_fee() * ($no_of_days_left)) + $chosen_price; 
            $innovator_subs_days_after_proration = (($amount_due/10) * 365)/100;
           
           // This is commented for a reason. Think abt this. This will ensure the years are capped.
            if($innovator_subs_days_after_proration > 2190){
                $innovator_subs_days_after_proration = 2190;
            }
            $new_date = $timestamp_now + ((round($innovator_subs_days_after_proration)) * 86400);
            // Refactor this
            if($innovator_expiry_date!=null){
                $new_date = strtotime("+$subs_in_years years", strtotime($innovator_expiry_date));
            }
        }
    }
}

// Database Insertions
$date_now = new DateTime();
$timestamp = (string)$date_now->getTimestamp();
$order_id = "ord_".$timestamp;

$sql_conn = mysqli_connection();

if(!($stmt = $sql_conn->prepare("INSERT INTO UD_ubf_checkout (order_id,project_id,project_submission_type, authnet_transact_id, bank_acct_last_4_digits, billing_first_name, billing_last_name, billing_address, billing_city, billing_state, billing_zip, 
                                    billing_country,billing_email,billing_phone,card_last_4_digits,card_type,merchant_email,pay_method,site_code,total_amount,ubf_transaction_id,x_authnet_auth_code,x_avs_code,x_response_code,x_response_reason_text,x_response_reason_code,x_response_sub_code) 
                                    VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"))){
    $ret =  "Prepare failed: (" . $sql_conn->errno . ") " . $sql_conn->error." ll";
}

$stmt->bind_param("ssdssssssssssssssssssssssss",
                $order_id,$project_id,$project_submission_type,$authnet_transact_id, $bank_acct_last_4_digits, $billing_first_name, $billing_last_name, $billing_address, $billing_city, $billing_state, $billing_zip, $billing_country,$billing_email,$billing_phone,$card_last_4_digits,$card_type,$merchant_email,$pay_method,$site_code,$total_amount,$ubf_transaction_id,$x_authnet_auth_code,$x_avs_code,$x_response_code,$x_response_reason_text,$x_response_reason_code,$x_response_sub_code);

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

$stmt->close();
mysqli_close($sql_conn);

$sql_conn = mysqli_connection();

if($purchase_plan == "Supporter"){
    if($chosen_downgrade_plan == "subLater"){
        $purchase_plan = "Innovator";
    }

    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(), upgrade_date = FROM_UNIXTIME($timestamp), supporter_expiry_date = FROM_UNIXTIME($new_date) WHERE email_id = ?"))){
        $sql_ret =  "Prepare failed: (" . $sql_conn->errno . ") " . $sql_conn->error;
    }
}
else if($purchase_plan == "Innovator"){
    if($chosen_price_plan == "subLater"){
        $purchase_plan = "Supporter";
    }
    if($plan_type=="Supporter" && $innovator_expiry_date!=null){
        if($timestamp > strtotime($supporter_expiry_date)){
            $purchase_plan = "Innovator";
        }
    }

    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(), upgrade_date = FROM_UNIXTIME($timestamp), 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', 'IntenseTesting', $chosen_price_plan);

// Set supporter expiry date to null
$timestamp_now2 = (string)$date_now->getTimestamp();
//$timestamp_now = 1634107509; // Oct 13th, 2021 - One year exactly from subscription.
//$timestamp_now = 1647153909; // March 13th, 2022 - One and half year from subscription.
//$timestamp_now = 1668494709; // Nov 15th, 2022 - One and half year from subscription.
$date_diff2 = $supporter_exp_date_tmstmp - $timestamp_now2;
$no_of_days_left2 = round($date_diff/86400);
if(($purchase_plan == "Innovator" && $no_of_days_left2 > 90) || ($purchase_plan == "Innovator" && $chosen_downgrade_plan == "today")){
    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);
}

$stmt->close();
mysqli_close($sql_conn);
}
?>