#!/bin/bash

export DB_NAME=$(cat /opt/srzone/etc/config.ini | grep db_name | awk -F= '{print $2}')
export DB_HOST=$(cat /opt/srzone/etc/config.ini | grep db_host | awk -F= '{print $2}')
export DB_USERNAME=$(cat /opt/srzone/etc/config.ini | grep db_username | awk -F= '{print $2}')
export DB_PASSWORD=$(cat /opt/srzone/etc/config.ini | grep db_password | awk -F= '{print $2}')

# Connect to the database
mysql_command="mysql -h$DB_HOST -u$DB_USERNAME -p$DB_PASSWORD $DB_NAME"

# Retrieve SMS API details for each partner from srzone_partners table
query_partner_sms_api="SELECT p.id AS partner_id, p.sms_api_id, sa.api_url, sp.sms_expired_reminder
                       FROM srzone_partners p
                       LEFT JOIN srzone_sms_api sa ON p.sms_api_id = sa.id
                       LEFT JOIN srzone_partners sp ON p.id = sp.id;"

result_partner_sms_api=$($mysql_command -e "$query_partner_sms_api")

if [ $? -ne 0 ]; then
    echo "Error retrieving partner SMS API details: $result_partner_sms_api"
    exit 1
fi

# Get the sms_expired_reminder value from the first row (after header)
sms_expired_reminder=$(echo "$result_partner_sms_api" | tail -n +2 | head -n 1 | awk '{print $4}')


# Fetch users with expiring accounts
query_users="SELECT u.id, u.firstname, u.lastname, u.username, u.expiration, u.phone, u.enabled, p.name AS profile_name
             FROM srzone_users u
             LEFT JOIN srzone_profiles p ON u.profile_id = p.id
             WHERE u.enabled = 1 AND DATE(u.expiration) = CURDATE() + INTERVAL $sms_expired_reminder DAY;"
result_users=$($mysql_command -e "$query_users")

if [ $? -ne 0 ]; then
    echo "Error retrieving users: $result_users"
    exit 1
fi

# Check if there are users before entering the loop
if [ "$(echo "$result_users" | wc -l)" -gt 1 ]; then
    while read -r row_user; do
        user_id=$(echo "$row_user" | cut -f1)
        first_name=$(echo "$row_user" | cut -f2)
        last_name=$(echo "$row_user" | cut -f3)
        username=$(echo "$row_user" | cut -f4)
        expiration_date=$(echo "$row_user" | cut -f5)
        phone=$(echo "$row_user" | cut -f6)
        profile_name=$(echo "$row_user" | cut -f7)

        # Check if the phone number is not empty
        if [ -n "$phone" ] && [ "$phone" != 'phone' ]; then
            # Retrieve the SMS template from the srzone_sms_templates table
            query_sms_template="SELECT template FROM srzone_sms_templates WHERE id = 4;"
            result_sms_template=$($mysql_command -e "$query_sms_template")

            if [ $? -ne 0 ]; then
                echo "Error retrieving SMS template: $result_sms_template"
                exit 1
            fi

            sms_template=$(echo "$result_sms_template" | tail -n 1)

            # Replace placeholders in SMS message
            sms_message=$(echo "$sms_template" | sed "s/{first_name}/$first_name/g; s/{last_name}/$last_name/g; s/{expiry_date}/$expiration_date/g; s/{package_name}/$profile_name/g; s/{username}/$username/g; s/{mobile}/$phone/g")

            # Log the SMS data in srzone_sms_queue
            query_insert_sms_log="INSERT INTO srzone_sms_queue (user_id, dst, text, sent, created_at) VALUES ($user_id, '$phone', '$sms_message', 0, NOW());"
            result_insert_sms_log=$($mysql_command -e "$query_insert_sms_log")

            if [ $? -ne 0 ]; then
                echo "Error inserting SMS data into queue: $result_insert_sms_log"
                exit 1
            fi
        else
            echo "User $username does not have a phone number. Skipping..."
        fi
    done <<<"$result_users"
fi

echo "SMS data prepared successfully."

# Close database connection
$mysql_command -e "quit"
