<?php 
/*saves order and billing information in database. Both order and billing records are saved when user submits info on payments page.*/

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

//ChromePhp::log("hello world from Cpayments");
    class UD_Payment_Info{
    	public $transaction_id;
    	public $bill_firstname;
    	public $bill_lastname;
    	public $bill_address;
    	public $bill_city;
    	public $bill_state;
    	public $bill_zip;
    	public $bill_country;
    	public $bill_email;
    	public $bill_phone;

    	public $order_id;
    	public $customer_id;
    	public $project_id;
    	public $order_amount;
    	public $order_info;

    }

    class UD_Billing_Info{
    	public $billing_first_name;
    	public $billing_last_name;
    	public $billing_address;
    	public $billing_city;
    	public $billing_state;
    	public $billing_zip;
    	public $billing_country;
    	public $billing_email;
    	public $billing_phone;

    	public $order_id;
    	public $project_id;

    }
    
    /*inserts record in the billing table and responds back to API. If response is false then eventually there won't be any entry in the order table.*/
    function insert_billing_info($projectid, $firstname, $lastname, $address, $city, $state, $country, $zip, $email ,$phone){
    	
    	$sql_conn = mysqli_connection();
        $sql_conn->begin_transaction();

        if(isLoggedIn()){
        	$payment = new UD_Payment_Info();

        	$date = new DateTime();
			$timestamp = (string)$date->getTimestamp();

			$payment->order_id 			= "ord_".$timestamp;
			$payment->bill_firstname 	= $firstname;
			$payment->bill_lastname 	= $lastname;
			$payment->bill_address 		= $address;
			$payment->bill_city 		= $city;
			$payment->bill_state 		= $state;
			$payment->bill_country 		= $country;
			$payment->bill_zip 			= $zip;
			$payment->bill_email 		= $email;
			$payment->bill_phone 		= $phone;
			$payment->transaction_id	= "";


            /*set the response to false and order id to -1 in case of a failed database response. Rollback transaction in case of failure.*/
			$ret['response'] = false;
			$ret['order_id'] = "-1";
			
			//$ret['sql'] = $sql_conn;
            
			if (!($stmt = $sql_conn->prepare("INSERT INTO UD_Billing (order_id, firstname, lastname, address, city, state, country, zipcode, email, phone) VALUES (?,?,?,?,?,?,?,?,?,?)"))){	
				$ret["message"] =  "Prepare failed: (" . $sql_conn->errno . ") " . $sql_conn->error." ll";
				$sql_conn->rollback();
                return $ret;
			}
			$payment = Util::escapeObject($payment);

			if(!($stmt->bind_param("ssssssssss",
					$payment->order_id,
					$payment->bill_firstname,
					$payment->bill_lastname,
					$payment->bill_address,
					$payment->bill_city,
					$payment->bill_state,
					$payment->bill_country,
					$payment->bill_zip,
					$payment->bill_email,
					$payment->bill_phone))){
				$ret["message"] =  "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
				$sql_conn->rollback();
                return $ret; 
			}

			

            if (!($res = $stmt->execute())) {
            	$ret["message"] =  "Execute failed: (" . $stmt->errno . ") " . $stmt->error." ;". $res;
            	$sql_conn->rollback();
            	return $ret;
            }else{
            	$ret["response"] = true;
                $ret["message"] = $res;
                $ret['order_id'] = $payment->order_id;
                $sql_conn->commit();
            }
        }else{
        	$ret["message"] = "Error : User not logged in";
        }
    	//ChromePhp::log("return value from Cpayments billing info: "+$ret['order_id']);
    	$stmt->close();
    	
    	return $ret;
    }


    /*inserts in order table only if insert_billing_info() returns true*/
    function insert_order_info($order_id, $project_id, $order_info, $order_cost){
    	$sql_conn = mysqli_connection();
        $sql_conn->begin_transaction();
        
        if(isLoggedIn()){
        	$order = new UD_Payment_Info();
        	$order->order_id 	 = $order_id;
        	$order->order_info 	 = $order_info;
        	$order->order_amount = $order_cost;
        	$order->project_id 	 = $project_id;
        	$order->customer_id	 = $_SESSION['user']->_id;
            $ret['response'] = false;

        	if (!($stmt = $sql_conn->prepare("INSERT INTO UD_Order(order_id, order_info, project_id, order_amount, customer_id) VALUES (?,?,?,?,?)"))){
        		$ret["message"] =  "Prepare failed: (" . $sql_conn->errno . ") " . $sql_conn->error." ll";
				$sql_conn->rollback();
                return $ret;
        	}

        	$order = Util::escapeObject($order);
        	
			if(!($stmt->bind_param("sssss",
				$order->order_id,
				$order->order_info,
				$order->project_id,
				$order->order_amount,
				$order->customer_id))){
				$ret["message"] =  "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
				$sql_conn->rollback();
                return $ret; 
			}

			if (!($res = $stmt->execute())) {
            	$ret["message"] =  "Execute failed: (" . $stmt->errno . ") " . $stmt->error." ;". $res;
            	$sql_conn->rollback();
            	return $ret;
            }else{
            	$ret["response"] = true;
                $ret["message"] = $res;
                $ret['orderid'] = $order->order_id;
                session_start();
                $_SESSION['orderid'] = $order->order_id;
                $_SESSION['project'] = $order->project_id;
                $sql_conn->commit();
            }


        }else{
        	$ret["message"] = "Error : User not logged in";
        }
        $stmt->close();
    	return $ret;
    }
    
    function insertBillingInfo($projectid, $firstname, $lastname, $address, $city, $state, $country, $zip, $email ,$phone){
    	
    	$sql_conn = mysqli_connection();
		$sql_conn->begin_transaction();
		
        if(isLoggedIn()){
			$billingInfo = new UD_Billing_Info();
			$date = new DateTime();
			$timestamp = (string)$date->getTimestamp();

			$billingInfo->order_id 	= "ord_".$timestamp;
			$billingInfo->project_id 	 = $projectid;
			$billingInfo->billing_first_name = $firstname;
    		$billingInfo->billing_last_name = $lastname;
    		$billingInfo->billing_address = $address;
    		$billingInfo->billing_city = $city;
			$billingInfo->billing_state = $state;
			$billingInfo->billing_zip = $zip;
			$billingInfo->billing_country = $country;
			$billingInfo->billing_email = $email;
			$billingInfo->billing_phone = $phone;

			$billingInfo = Util::escapeObject($billingInfo);
			$ret["response"] = false;

			// print $billingInfo->order_id;
			// print $billingInfo->project_id;
			// print $billingInfo->billing_first_name;
			// print $billingInfo->billing_last_name;
			// print $billingInfo->billing_address;
			// print $billingInfo->billing_city;
			// print $billingInfo->billing_state;
			// print $billingInfo->billing_zip;
			// print $billingInfo->billing_country;
			// print $billingInfo->billing_email;
			// print $billingInfo->billing_phone;
			
			if (!($stmt = $sql_conn->prepare("INSERT INTO `UD_ubf_checkout`(order_id, project_id, billing_first_name, billing_last_name, billing_address, billing_city,
											 billing_state, billing_zip, billing_country, billing_email, billing_phone) VALUES (?,?,?,?,?,?,?,?,?,?,?)"))){
                $ret["message"] =  "Prepare failed: (" . $sql_conn->errno . ") " . $sql_conn->error." ll";
                return $ret;
			}

			if(!($stmt->bind_param("sssssssssss",
				$billingInfo->order_id,
				$billingInfo->project_id,
				$billingInfo->billing_first_name,
				$billingInfo->billing_last_name,
				$billingInfo->billing_address,
				$billingInfo->billing_city,
				$billingInfo->billing_state,
				$billingInfo->billing_zip,
				$billingInfo->billing_country,
				$billingInfo->billing_email,
				$billingInfo->billing_phone
				))){
				$ret["message"] =  "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
                return $ret; 
			}

			if (!($res = $stmt->execute())) {
                $ret["message"] =  "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
                $ret["response"] = false;
            } else {
                $ret["response"] = true;
                $ret["message"] = $res;
            }
        }else{
        	$ret["message"] = "Error : User not logged in";
		}
		mysqli_close($sql_conn);
		$stmt->close();
    	return $ret;
	}
	
	//getBillingInfo("pr_e9521b02b2");
	function getBillingInfo($project_id){
        // print $project_id;
		$sql_conn = mysqli_connection();
    	$res = array();
        if(isLoggedIn()){
            if($project_id != -1){
               $sql = "SELECT * FROM UD_ubf_checkout WHERE 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['order_id'] = $row['order_id'];
					$res['first_name'] = $row['billing_first_name'];
					$res['last_name'] = $row['billing_last_name'];
					$res['address'] = $row['billing_address'];
					$res['city'] = $row['billing_city'];
					$res['state'] = $row['billing_state'];
					$res['zip'] = $row['billing_zip'];
					$res['country'] = $row['billing_country'];
					$res['email'] = $row['billing_email'];
					$res['phone'] = $row['billing_phone'];
                  }
                }
                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;
	}

?>