import requests
from django.http import JsonResponse		
from datetime import datetime
import base64
from .generateAccessToken import get_access_token
import json 
from requests.auth import HTTPBasicAuth
import requests

def initiate_stk_push(request):
	access_token_response = get_access_token(request)
	if isinstance(access_token_response,JsonResponse):
		access_token = access_token_response.content.decode('utf-8')
		access_token_json = json.loads(access_token)
		access_token = access_token_json.get('access_token')		
		if access_token:
			amount = 1
			phone = '254728680519'
			passkey = 'bfb279f9aa9bdbcf158e97dd71a467cd2e0c893059b10f78e6b72ada1ed2c919'
			business_short_code = '174379'
			process_request_url = 'https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest'
			callback_url = 'https://developer.safaricom.co.ke/'
			timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
			password = base64.b64encode((business_short_code + passkey + timestamp).encode()).decode()
			party_a = phone
			party_b = '254728680519'
			account_reference = 'SIBIA'
			transaction_desc = 'stkpush test'
			stk_push_headers = {
				'Content-Type':'application/json',
				"Authorization": 'Bearer' + access_token
			}

			stk_push_payload = {
                "BusinessShortCode": business_short_code,
                "Password": password,
                "Timestamp": timestamp,
                "TransactionType": "CustomerPayBillOnline",
                "Amount": amount ,                
                "PartyA": party_a,
                "PartyB": party_b,
                "PhoneNumber": party_a,
                "CallBackURL": callback_url,
                "AccountReference": account_reference,
                "TransactionDesc": transaction_desc,
                }

			try:
				response = requests.post(process_request_url,headers=stk_push_headers,json= stk_push_payload)
				returned_xml = response.text
				returned_json = {}
				print(returned_xml)
				print(json.dumps(returned_json, indent=2),'heree')

				
				checkout_request_id = returned_json['CheckoutRequestId']
				response_code = returned_json["ResponseCode"]

				if response_code == "0":
					return JsonResponse({"CheckoutRequestId":checkout_request_id})
				else:
					return JsonResponse({'error': 'STK push failed.'})
			except requests.exceptions.RequestException as e:
				return JsonResponse({'error':str(e)})
		else:
			return JsonResponse({"error":'failed to retrieve access_token'})    				    

