from flask import Flask, render_template, request, jsonify
from flask_cors import CORS
from flask_mail import Mail, Message
import re
from datetime import datetime
import os
from dotenv import load_dotenv
import logging
from logging.handlers import RotatingFileHandler

# --- FIX: Load environment variables ---
load_dotenv()

# Initialize Flask app
app = Flask(__name__)
CORS(app)

# --- NEW: Set up file-based logging ---
# This creates a log file named 'app.log' in your application's directory.
# It's configured to rotate, so it won't grow indefinitely.
if not app.debug: # Only use file logging when not in debug mode (good for production)
    # Create a handler for the log file
    file_handler = RotatingFileHandler('app.log', maxBytes=10240, backupCount=10)
    
    # Set the format for the log messages
    file_handler.setFormatter(logging.Formatter(
        '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'
    ))
    
    # Set the level of messages to log
    file_handler.setLevel(logging.INFO)
    app.logger.addHandler(file_handler)
    
    app.logger.setLevel(logging.INFO)
    app.logger.info('Flask app startup with file logging.')

# --- FIX: Load email configuration from environment variables ---
app.config['MAIL_SERVER'] = os.getenv('MAIL_SERVER', 'mail.collnetwork.net')
app.config['MAIL_PORT'] = int(os.getenv('MAIL_PORT', 587)) # Port should be an integer
app.config['MAIL_USE_TLS'] = os.getenv('MAIL_USE_TLS', 'True').lower() in ['true', '1', 't']
app.config['MAIL_USE_SSL'] = os.getenv('MAIL_USE_SSL', 'False').lower() in ['true', '1', 't']
app.config['MAIL_USERNAME'] = os.getenv('MAIL_USERNAME', 'info@collnetwork.net')
app.config['MAIL_PASSWORD'] = os.getenv('MAIL_PASSWORD') # Load from .env
app.config['MAIL_DEFAULT_SENDER'] = os.getenv('MAIL_DEFAULT_SENDER', 'info@collnetwork.net')

# Add a check to ensure the password was loaded
if not app.config['MAIL_PASSWORD']:
    app.logger.error("FATAL ERROR: MAIL_PASSWORD is not set in the .env file.")

# Initialize Flask-Mail
mail = Mail(app)

# Service mapping
SERVICE_NAMES = {
    'ip-telephony': 'IP Telephony & Unified Communication',
    'networking': 'Networking Services',
    'cctv': 'CCTV & Surveillance',
    'hardware': 'Hardware & Repairs',
    'other': 'Other'
}

def validate_email(email):
    """Validate email format"""
    pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
    return re.match(pattern, email) is not None

def sanitize_input(text):
    """Sanitize user input"""
    if text:
        return text.strip()
    return ''

def create_html_email(name, email, phone, service, message):
    """Create HTML email body"""
    service_display = SERVICE_NAMES.get(service, service if service else 'Not specified')
    
    html = f"""
    <!DOCTYPE html>
    <html>
    <head>
        <style>
            body {{ font-family: Arial, sans-serif; line-height: 1.6; color: #333; }}
            .container {{ max-width: 600px; margin: 0 auto; padding: 20px; }}
            .header {{ background: linear-gradient(135deg, #6a1b9a 0%, #00897b 100%); 
                        color: white; padding: 20px; text-align: center; border-radius: 5px 5px 0 0; }}
            .content {{ background: #f9f9f9; padding: 20px; border: 1px solid #ddd; }}
            .field {{ margin-bottom: 15px; }}
            .label {{ font-weight: bold; color: #6a1b9a; }}
            .value {{ margin-top: 5px; padding: 10px; background: white; border-left: 3px solid #00897b; }}
            .footer {{ text-align: center; padding: 20px; color: #666; font-size: 12px; }}
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <h2>New Contact Form Submission</h2>
            </div>
            <div class="content">
                <p>You have received a new message from your website contact form.</p>
                
                <div class="field">
                    <div class="label">Name:</div>
                    <div class="value">{name}</div>
                </div>
                
                <div class="field">
                    <div class="label">Email:</div>
                    <div class="value"><a href="mailto:{email}">{email}</a></div>
                </div>
                
                <div class="field">
                    <div class="label">Phone:</div>
                    <div class="value">{phone if phone else 'Not provided'}</div>
                </div>
                
                <div class="field">
                    <div class="label">Service Interested In:</div>
                    <div class="value">{service_display}</div>
                </div>
                
                <div class="field">
                    <div class="label">Message:</div>
                    <div class="value">{message.replace(chr(10), '<br>')}</div>
                </div>
                
                <div class="field">
                    <div class="label">Submitted:</div>
                    <div class="value">{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}</div>
                </div>
            </div>
            <div class="footer">
                <p>This email was sent from the Collnetwork Technology contact form.</p>
                <p><strong>Collnetwork Technology LTD</strong><br>"...building a sustainable network"</p>
            </div>
        </div>
    </body>
    </html>
    """
    return html

def create_text_email(name, email, phone, service, message):
    """Create plain text email body"""
    service_display = SERVICE_NAMES.get(service, service if service else 'Not specified')
    
    text = f"""
New Contact Form Submission

Name: {name}
Email: {email}
Phone: {phone if phone else 'Not provided'}
Service Interested In: {service_display}

Message:
{message}

Submitted: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}

---
This email was sent from the Collnetwork Technology contact form.
Collnetwork Technology LTD
"...building a sustainable network"
    """
    return text

# Routes
@app.route('/')
def index():
    """Serve the main website page"""
    return render_template('index.html')

@app.route('/send_contact', methods=['POST'])
def send_contact():
    """Handle contact form submission"""
    try:
        data = request.form
        name = sanitize_input(data.get('name', ''))
        email = sanitize_input(data.get('email', ''))
        phone = sanitize_input(data.get('phone', ''))
        service = sanitize_input(data.get('service', ''))
        message = sanitize_input(data.get('message', ''))
        
        if not name or not email or not message:
            return jsonify({
                'success': False,
                'message': 'Please fill in all required fields'
            }), 400
        
        if not validate_email(email):
            return jsonify({
                'success': False,
                'message': 'Please enter a valid email address'
            }), 400
        
        msg = Message(
            subject=f'New Contact Form Submission from {name}',
            recipients=['info@collnetwork.net'],
            reply_to=email
        )
        
        msg.html = create_html_email(name, email, phone, service, message)
        msg.body = create_text_email(name, email, phone, service, message)
        
        mail.send(msg)
        
        return jsonify({
            'success': True,
            'message': 'Thank you! Your message has been sent successfully. We will get back to you soon.'
        }), 200
        
    except Exception as e:
        app.logger.error(f'Contact form error: {str(e)}', exc_info=True)
        
        return jsonify({
            'success': False,
            'message': 'There was an error sending your message. Please email us directly at info@collnetwork.net or try again later.'
        }), 500

@app.route('/health')
def health_check():
    """Health check endpoint"""
    return jsonify({
        'status': 'ok',
        'timestamp': datetime.now().isoformat()
    }), 200

# Error handlers
@app.errorhandler(404)
def not_found(e):
    """Handle 404 errors"""
    return render_template('404.html'), 404

@app.errorhandler(500)
def server_error(e):
    """Handle 500 errors"""
    app.logger.error(f'Server error: {str(e)}')
    return jsonify({
        'error': 'Internal server error',
        'message': 'Something went wrong. Please try again later.'
    }), 500

if __name__ == '__main__':
    # For development
    app.run(debug=True, host='0.0.0.0', port=5000)

