#let's modify the previous code to add time-based billing based on the amount paid, with hourly, daily, and weekly rates. We'll assume the following rates for simplicity:

#Hourly rate: $1 per hour
#Daily rate: $10 per day
#Weekly rate: $50 per week
#Here's the updated Flask application with time-based billing:

#1. Install Required Libraries
#Ensure you have the required libraries installed:

pip install flask requests librouteros

#2. Flask Application Code
#Here's the complete code:

from flask import Flask, request, jsonify
import requests
from librouteros import connect
from datetime import datetime, timedelta

app = Flask(__name__)

# MikroTik connection details
MT_HOST = 'your_mikrotik_ip'
MT_USER = 'your_mikrotik_username'
MT_PASS = 'your_mikrotik_password'

# Daraja API credentials
DARJA_CONSUMER_KEY = 'your_daraja_consumer_key'
DARJA_CONSUMER_SECRET = 'your_daraja_consumer_secret'

# Billing rates
HOURLY_RATE = 20  # KSh.20 per hour
DAILY_RATE = 80  # Ksh.80 per day
WEEKLY_RATE = 300  # KSh.300 per week
MONTHLY_RATE = 1000 # Ksh.1000 per week

def get_mikrotik_connection():
    return connect(username=MT_USER, password=MT_PASS, host=MT_HOST)

@app.route('/pay', methods=['POST'])
def pay():
    data = request.json
    phone_number = data['phone_number']
    amount = data['amount']

    # Step 1: Initiate payment via Daraja API
    token = get_daraja_token()
    payment_response = initiate_payment(token, phone_number, amount)

    if payment_response['ResponseCode'] == '0':
        # Payment successful
        # Step 2: Update MikroTik user details
        update_mikrotik_user(phone_number, amount)
        return jsonify({'message': 'Payment successful and user updated'})
    else:
        return jsonify({'message': 'Payment failed'}), 400

def get_daraja_token():
    response = requests.get(
        'https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials',
        auth=(DARJA_CONSUMER_KEY, DARJA_CONSUMER_SECRET)
    )
    json_response = response.json()
    return json_response['access_token']

def initiate_payment(token, phone_number, amount):
    headers = {
        'Authorization': f'Bearer {token}',
        'Content-Type': 'application/json'
    }
    payload = {
        'BusinessShortCode': 'your_shortcode',
        'Password': 'generated_password',
        'Timestamp': 'timestamp',
        'TransactionType': 'CustomerPayBillOnline',
        'Amount': amount,
        'PartyA': phone_number,
        'PartyB': 'your_shortcode',
        'PhoneNumber': phone_number,
        'CallBackURL': 'https://your_callback_url',
        'AccountReference': 'account_reference',
        'TransactionDesc': 'Payment for services'
    }
    response = requests.post(
        'https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest',
        headers=headers,
        json=payload
    )
    return response.json()

def update_mikrotik_user(phone_number, amount):
    api = get_mikrotik_connection()
    
    # Calculate time to add based on amount
    if amount >= WEEKLY_RATE:
        time_to_add = timedelta(weeks=amount // WEEKLY_RATE)
    elif amount >= DAILY_RATE:
        time_to_add = timedelta(days=amount // DAILY_RATE)
    elif amount >= MONTHLY_RATE:
        time_to_add = timedelta(days=amount // MONTHLY_RATE)
    else:
        time_to_add = timedelta(hours=amount // HOURLY_RATE)
    
    # Assume user is identified by phone number in MikroTik
    user_name = phone_number  # Modify this according to your user identification method

    # Fetch existing user profile
    users = api(cmd='/ip/hotspot/user/print', where={'name': user_name})
    if users:
        user = users[0]
        expiry_time_str = user.get('limit-uptime')
        
        # Calculate new expiry time
        if expiry_time_str:
            expiry_time = datetime.strptime(expiry_time_str, '%Y-%m-%d %H:%M:%S')
        else:
            expiry_time = datetime.now()
        
        new_expiry_time = expiry_time + time_to_add
        
        # Update user profile
        api(cmd='/ip/hotspot/user/set', numbers=user['.id'], limit_uptime=new_expiry_time.strftime('%Y-%m-%d %H:%M:%S'))
    
    api.close()

if __name__ == '__main__':
    app.run(debug=True)
