<?php
include_once("CUserSession.php");
include_once("CProject.php");
include_once('helper.php');
include_once("CUtil.php");

class UD_Purchase_Info{

}


/*fetches billing and order info from UD_billing and UD_order table*/
function getpurchaseinfo(){
	
	$sql_conn = mysqli_connection();
	if(isLoggedIn()){
		// $where = "WHERE `customer_id` like '".$_SESSION['user']->_id."'";
  //           if($project_id!=NULL&&$project_id!=''&&$project_id != -1){
  //               $where = $where." AND `project_id` like '".$project_id."'";
  //           }
  //           if($order_id!=NULL&&$order_id!=''&&$order_id!=-1){
  //           	$where = $where."AND order_id like'".$order_id."'";
  //           }

		if($_SESSION['project']==NULL||$_SESSION['orderid']==NULL||$_SESSION['orderid']==''||$_SESSION['project']==''){
			$res['message'] = "invalid value of order id or project id";
			return $res;
		}

        
        $sql = "SELECT * FROM UD_Billing as bill INNER JOIN UD_Order as ord ON bill.order_id = ord.order_id WHERE `customer_id` like '".$_SESSION['user']->_id."'  AND bill.order_id like '".$_SESSION['orderid']."' AND project_id like '".$_SESSION['project']."'";
        $purchase_info = array();
        $res = array();
       try{
                $result = mysqli_query($sql_conn, $sql);
                while($row = mysqli_fetch_array($result)) {
                	unset($row["transaction_id"]);
                	unset($row["order_id"]);
                	unset($row["customer_id"]);
                	unset($row["project_id"]);
                  unset($row["order_timestamp"]);
                	$purchase_info[] = $row;
                }
                mysqli_close($sql_conn);
                return $purchase_info;
        }catch(Exception $e){
        	$res['message'] = "Error: ".$e;
        }
	}else{
		$res['message'] = "Error : User not logged in";
	}
	return $res;
}

/*update transaction id in billing and order table once credit card transaction is successful. Gets called from charge-credit-card, if authorize returns true response.*/
function updatetransaction($info){
  $sql_conn = mysqli_connection();
  $res['response'] = false;

  if(isLoggedIn()){
    if($info['trans_id'] != null && $info['auth_code'] != null){

    $sql_conn->begin_transaction();
    
     $stmt = $sql_conn->prepare("INSERT INTO UD_Transaction (transaction_id, order_id, user_id, auth_code, response_code, code, description) VALUES(?,?,?,?,?,?,?)");
     
     if(!$stmt){
      $res['message'] = "error occured during transaction update"; 
      $sql_conn->rollback();    
      return $res;
     }

     $stmt->bind_param("sssssss", $info['trans_id'], $_SESSION['orderid'], $_SESSION['user']->_id, $info['auth_code'], $info['response_code'], $info['code'], $info['description']);

     $result = $stmt->execute();

     if(!$result){
        $res['message'] = "Error while updating transaction"; 
        $sql_conn->rollback();    
        return $res;
     } 

     


      $query1 = "UPDATE UD_Billing SET transaction_id= '". $info['trans_id'] ."', billed_amount='". $info['billed_amount'] ."' WHERE order_id= '". $_SESSION['orderid']."'";

      $query2 = "UPDATE UD_Order SET transaction_id= '". $info['trans_id'] ."' WHERE order_id= '". $_SESSION['orderid']."'";

      $sql_conn->query($query1);
      if($sql_conn->affected_rows<=0){
         $res['message'] = "update transaction failed";
         $sql_conn->rollback();
         return $res;
      }
      
      $sql_conn->query($query2);
      if($sql_conn->affected_rows<=0){
         $res['message'] = "update transaction failed";
         $sql_conn->rollback();
         return $res;
      }

      $sql_conn->commit();
      $res['response'] = true;
      $res['message'] = 'success';
      return $res;
    }
  }else{
    $res['message'] = "Error : User not logged in";
  }

  return $res;
}

// Get UBF billing details
function get_ubf_billing_info($project_id){
        
    $sql_conn = mysqli_connection();
    $reponse_code_key = "x_response_code";
    $res = array();
        $res['payment_result'] = 0; 
        if(isLoggedIn()){
            if($project_id != -1){
               $sql = "SELECT * FROM UD_ubf_checkout INNER JOIN UD_P_Info ON UD_ubf_checkout.project_id = UD_P_Info._id WHERE  WHERE UD_ubf_checkout.project_id='".$project_id."'";

            try{
                $result = mysqli_query($sql_conn, $sql);
                while($row = mysqli_fetch_array($result)) {
                  $res['project_id'] = $row["project_id"];
                  if($row["project_id"] == $project_id){
                    $res['payment_result'] = $row[$reponse_code_key];
                    $res['order_id'] = $row['order_id'];
                  }
                }
                mysqli_close($sql_conn);
            } catch (Exception $e){
                $res['message'] = "Error : ".$e->getMessage();
            }
            }
            else{
              $res['message'] = "Error : Invalid project_id";
            }
        } else {
            $res['message'] = "Error : User not logged in";
        }
        
        $r = json_encode($res);
        return $r;
  }


?>