import os
import sys
from flask import Flask, render_template, request, jsonify

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/submit-contact', methods=['POST'])
def contact():
    name = request.form.get('name')
    email = request.form.get('email')
    subject = request.form.get('subject')
    message = request.form.get('message')
    
    # Save submissions to a simple text file
    try:
        os.makedirs('data', exist_ok=True)
        with open('data/submissions.txt', 'a', encoding='utf-8') as f:
            f.write(f"Date: {request.date or ''}\nName: {name}\nEmail: {email}\nSubject: {subject}\nMessage: {message}\n{'-'*40}\n")
    except Exception as e:
        print(f"Failed to save contact submission: {e}")
        
    return jsonify({
        "status": "success", 
        "message": "Thank you for contacting Ramisa Trading Corporation. We will get back to you shortly!"
    })

if __name__ == '__main__':
    port = 80
    print(f"Starting Ramisa Trading Corporation website on port {port}...")
    try:
        from waitress import serve
        serve(app, host='0.0.0.0', port=port)
    except Exception as e:
        print(f"Could not bind to port {port} or Waitress error: {e}")
        print("Attempting to run on development server on port 80...")
        try:
            app.run(host='0.0.0.0', port=port, debug=True)
        except Exception as e_inner:
            fallback_port = 5000
            print(f"Failed to start on port 80: {e_inner}. Trying fallback port {fallback_port}...")
            app.run(host='0.0.0.0', port=fallback_port, debug=True)
