from flask import Flask
from flask import request
from flask import jsonify
from flask_cors import CORS
from bs4 import BeautifulSoup

import requests
import time
import json
import re

app = Flask(__name__)
CORS(app)

@app.route("/")
def hello_world():
    return "Hello, World!"
    
@app.route("/mobile/send", methods=["POST"])
def send():
    try:
        if request.method == 'POST':
            
            allowed_auth = "VEVTVFZIRU46TEFXd2lCU1ZGUGUyR3Qz"
            auth_header = request.headers.get("Authorization")
            
            if auth_header and auth_header == "Basic "+allowed_auth:
                # Get the "Authorization" header
                body = request.get_json()
                email = body.get('email')
                amount = body.get('amount')
                procid = body.get('procid')
                env = body.get('env')

                if not validate_email(email):
                    return jsonify({
                        "success": True,
                        "data": "Invalid email"
                    }), 400

                if not is_valid_amount(amount):
                    return jsonify({
                        "success": True,
                        "data": "Invalid amount"
                    }), 400
                # Get the current time as a Unix timestamp (float)
                timestamp = time.time()

                # Convert it to a struct_time object (local time)
                local_time = time.localtime(timestamp)
                # Extract milliseconds from the timestamp
                milliseconds = int((timestamp % 1) * 1000)
                # Format it into a string

                time_string = time.strftime('%Y%m%d%H%M%S', local_time) + f'.{milliseconds:03d}'

                # Define the target URL to which we want to forward the request
                txnid = "GCSHMOBILE-"+time_string
                
                target_url = "https://"+env+".dragonpay.ph/api/collect/v1/"+str(txnid)+"/post"  # Change to the target URL
               
                # Collect headers from the incoming request
                # headers = {key: value for key, value in request.headers.items()}
                if env == 'gw':
                    auth_header = 'Basic VEVTVEdDQVNITkY6MlJQRjRyZ2hBbEdBbnJ6b3k5ZmJsZQ=='
                
                headers = {
                    'Content-Type': 'application/json',  # Specify the content type (could be JSON, form-data, etc.)
                    'Authorization': auth_header,  # Example of an authorization token
                }

                dragonpay_data = {
                    "TxnId":txnid,
                    "Amount" :  amount,
                    "Currency" :  "PHP",
                    "Description" :  "Mobile app sample txn GCSH",
                    "Email" :  email,
                    "ProcId" :  procid
                }

                response = requests.post(target_url, json=dragonpay_data, headers=headers)
                
                # dp_gcash = response.json()
                # dp_gcash_url = dp_gcash.get("Url")
                
                # dp_gcash_response =  requests.get(dp_gcash_url, params={})

                # if dp_gcash_response.status_code == 200:
                #     soup = BeautifulSoup(dp_gcash_response.text, 'html.parser')
                #     div_element = soup.find(id='loading-spinner')
                #     the_link = div_element.find('a')
                    
                #     gcash_link = 'https://uat-gcash.dragonpay.ph'+the_link.get('href')
                #     # return jsonify({
                #     #     "success": True,
                #     #     "data": gcash_link
                #     # }), 200
                #     gcash_response =  requests.get(gcash_link, params={})

                #     if gcash_response.status_code == 200:
                        
                #         return gcash_response.text
                #     else:
                #         return gcash_response.status_code
                
                return jsonify({
                    "success": True,
                    "data": response.json()
                }), 200
            else:
                return jsonify({
                    "success": False,
                    "data": "Invalid Auth "+auth_header
                }), 401

        else:
            return jsonify({
                "success": False,
                "data": "Method not allowed"
            }), 405
    except Exception as e:
        return jsonify({
                "success": False,
                "data": str(e)
            }), 500


@app.route("/scan/pay", methods=["POST"])
def scan():
    try:
        if request.method == 'POST':
            
            allowed_auth = "VEVTVFZIRU46TEFXd2lCU1ZGUGUyR3Qz"
            auth_header = request.headers.get("Authorization")
            
            if auth_header and auth_header == "Basic "+allowed_auth:
                # Get the "Authorization" header
                body = request.get_json()
                qrcode = body.get('qr')
                
                env = body.get('env')

                # Get the current time as a Unix timestamp (float)
                timestamp = time.time()

                # Convert it to a struct_time object (local time)
                local_time = time.localtime(timestamp)
                # Extract milliseconds from the timestamp
                milliseconds = int((timestamp % 1) * 1000)
                # Format it into a string

                time_string = time.strftime('%Y%m%d%H%M%S', local_time) + f'.{milliseconds:03d}'

                # Define the target URL to which we want to forward the request
                txnid = "GCSHMOBILE-"+time_string
                
                target_url = "https://"+env+".dragonpay.ph/api/qrph/v1/TEST/read/"+qrcode  # Change to the target URL
               
                # Collect headers from the incoming request
                # headers = {key: value for key, value in request.headers.items()}
                
                auth_header = 'Bearer bf94fa2b7fbba9249d006c1168d8dc7d95034834'
                
                headers = {
                    'Content-Type': 'application/json',  # Specify the content type (could be JSON, form-data, etc.)
                    'Authorization': auth_header,  # Example of an authorization token
                }

                
                response = requests.get(target_url, params={}, headers=headers)
                
                # get the refno and amount after reading the qr
                response_json = response.json()

                if response_json.get("code") != "000" and response_json.get("message") != "Success":
                    return jsonify({
                        "success": False,
                        "data": "Invalid response of scan read qr"
                    }), 400
                    
                refno = response_json.get("refNo")
                amount = response_json.get("amount")

                qrpay_target_url = "https://"+env+".dragonpay.ph/api/qrph/v1/TEST/post"
                # Do the paid qr
                headers = {
                    'Content-Type': 'application/json',  # Specify the content type (could be JSON, form-data, etc.)
                    'Authorization': auth_header,  # Example of an authorization token
                }

                dragonpay_data = {
                    "Refno": refno,
                    "TxnId": txnid,
                    "Amount": amount,
                    "email": "sean.ret@dragonpay.ph",
                    "mobileno": "09442213345"
                }

                response_qrpay = requests.post(qrpay_target_url, json=dragonpay_data, headers=headers)
                
                return jsonify({
                    "success": True,
                    "data": response_qrpay.json(),
                    "refNo":refno
                }), 200
            else:
                return jsonify({
                    "success": False,
                    "data": "Invalid Auth "+auth_header
                }), 401

        else:
            return jsonify({
                "success": False,
                "data": "Method not allowed"
            }), 405
    except Exception as e:
        return jsonify({
                "success": False,
                "data": str(e)
            }), 500

# @app.errorhandler(Exception)
# def handle_exception(err):
#   path = request.path


email_regex = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'

def validate_email(email):
    if re.match(email_regex, email):
        return True
    else:
        return False

def is_valid_amount(amount):
    try:
        # Try converting the input to a float (can also handle decimal values)
        float(amount)
        return True
    except ValueError:
        # If it cannot be converted to float, it's not a valid number
        return False
    
