import stripe
import mysql.connector

# Stripe Secret Key
stripe.api_key = "sk_test_51NYHWyKrIWQ3wDnPPn4ErSVVDiDWn57fXRVblqSmrJb1unl9rNBtwKU9RXR1jQF9RubmlPSFyfFAGe443utQvD5a00N9jOkzcy"

# 1. Connect to MySQL (storing only references, not raw card data!)
db = mysql.connector.connect(
    host="localhost",
    user="codduserDB",
    password="U4PBmQt!4YRpAK2j",
    database="codd_practice"
)

cursor = db.cursor(dictionary=True)

# Fetch a patient record (pretend we have stripe_customer_id in DB)
patient_id = 1
cursor.execute("SELECT * FROM aaa_patients WHERE id = %s", (patient_id,))
patient = cursor.fetchone()

if not patient:
    print("Patient not found")
    exit()

try:
    # 2. If no Stripe customer exists, create one
    if not patient.get("stripe_customer_id"):
        customer = stripe.Customer.create(
            name=patient["name"],
            email=patient["email"]
        )
        print(customer)
        stripe_customer_id = customer.id

        # Save it in DB
        cursor.execute("UPDATE aaa_patients SET stripe_customer_id=%s WHERE id=%s",
                       (stripe_customer_id, patient_id))
        db.commit()
    else:
        stripe_customer_id = patient["stripe_customer_id"]

    # 3. Create a PaymentMethod (test card — production would come from frontend Elements)
    payment_method = stripe.PaymentMethod.create(
        type="card",
        card={"token": "tok_visa"}   # ✅ test token instead of raw card details
    )

    # Attach to customer
    stripe.PaymentMethod.attach(
        payment_method.id,
        customer=stripe_customer_id
    )

    # Set default payment method
    stripe.Customer.modify(
        stripe_customer_id,
        invoice_settings={"default_payment_method": payment_method.id}
    )

    # 4. Create & confirm a PaymentIntent (charge)
    intent = stripe.PaymentIntent.create(
        amount=5000,  # $50 AUD in cents
        currency="aud",
        customer=stripe_customer_id,
        payment_method=payment_method.id,
        off_session=True,
        confirm=True
    )

    print("✅ Payment successful:", intent.id, intent.status)

except stripe.error.CardError as e:
    print("❌ Card declined:", e.user_message)
except Exception as e:
    print("❌ Error:", str(e))
 
cursor.close()
db.close()
