import sqlite3
import requests
import json

BOUNDARY = "----boundary"

def get_active_sites(db):
    cursor = db.cursor()
    cursor.execute("SELECT address FROM websites WHERE active = 1")
    return [row[0] for row in cursor.fetchall()]

def get_form_fields(db, address):
    cursor = db.cursor()
    cursor.execute("SELECT form_fields FROM data WHERE website_address = ?", (address,))
    row = cursor.fetchone()

    return json.loads(row[0]) if row else None

def build_multipart_body(fields, boundary):
    lines = []
    for name, value in fields.items():
        lines.append(f"--{boundary}")
        lines.append(f'Content-Disposition: form-data; name="{name}"')
        lines.append("")
        lines.append(str(value))
    lines.append(f"--{boundary}--")
    lines.append("")
    return "\r\n".join(lines).encode("utf-8")

def submit_form(site_url, form_fields):
    url = 'https://' + site_url.rstrip('/') + "/index.php?option=com_baforms"
    body = build_multipart_body(form_fields, BOUNDARY)

    headers = {
        "User-Agent": "Mozilla/5.0",
        "Accept": "*/*",
        "Content-Type": f"multipart/form-data; boundary={BOUNDARY}",
        "Referrer": site_url,
        "Origin": site_url,
    }

    try:
        response = requests.post(url, data=body, headers=headers)
        response.raise_for_status()

        status = f"[{response.status_code}] {'OK' if response.ok else 'BŁĄD'}"
        print(f"{status}: {site_url}")
    except Exception as e:
        print(f"[!] {site_url} {e}")

def main():
    db = sqlite3.connect('form_filler.db');
    for site in get_active_sites(db):
        form_fields = get_form_fields(db, site)
        if not form_fields:
            print(f"Nie znaleziono formularza na stronie {site}")
            continue

        submit_form(site, form_fields)

if __name__ == "__main__":
    main()
