import os
from flask import Flask, request, redirect, url_for, render_template, jsonify, send_from_directory, flash
from flask_mail import Mail, Message
from werkzeug.utils import secure_filename
from werkzeug.security import generate_password_hash, check_password_hash
import logging
from markupsafe import Markup
#from flask_sqlalchemy import SQLAlchemy
#from flask_wtf import FlaskForm
#from wtforms import StringField, PasswordField, SubmitField
#from wtforms.validators import DataRequired, Email, EqualTo, ValidationError
#from forms import RegistrationForm, LoginForm
#from models import db, User
#from flask_migrate import Migrate
#from flask_login import LoginManager, login_user, logout_user, current_user, login_required
import requests
from dotenv import load_dotenv
import boto3

load_dotenv()
# Determine the log directory based on an environment variable
log_directory = os.getenv('LOG_DIR')

# Print the log directory for debugging purposes
print(f"Using log directory: {log_directory}")

if not os.path.exists(log_directory):
    os.makedirs(log_directory)

# Set up logging
log_file_path = os.path.join(log_directory, 'oak.log')
logging.basicConfig(filename=log_file_path, level=logging.DEBUG)

app = Flask(__name__)

# Configurations for Flask-Mail
app.config['MAIL_SERVER'] = 'smtp.gmail.com'
app.config['MAIL_PORT'] = 587
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USERNAME'] = os.getenv('EMAIL_USER')
app.config['MAIL_PASSWORD'] = os.getenv('EMAIL_PASS')
app.config['MAIL_DEFAULT_SENDER'] = os.getenv('EMAIL_USER')

mail = Mail(app)

HUBSPOT_ACCESS_TOKEN = os.getenv('HUBSPOT_ACCESS_TOKEN')


INSTANCE_ID = 'i-007012e83b632f3da'
REGION_NAME = os.getenv('AWS_DEFAULT_REGION')

# Initialize a session using your default profile
session = boto3.Session(region_name=REGION_NAME)

# Create an EC2 resource
ec2 = session.resource('ec2')

#app.config['SECRET_KEY'] = 'your_secret_key'
#app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://jake:Nocash01!@localhost/cons_users'

#login_manager = LoginManager()
#login_manager.init_app(app)

#db.init_app(app)
#migrate = Migrate(app, db)

#@login_manager.user_loader
#def load_user(user_id):
#    return User.query.get(int(user_id))

@app.errorhandler(404)
def redirect_404_to_custom_page(error):
    return redirect(url_for('page_not_found'))

###########################################################################
# Routes

@app.route('/404')
def page_not_found():
    return render_template('404.html'), 404

@app.route('/submit-form', methods=['POST'])
def submit_form():
    data = request.json
    app.logger.info(data)
    name = data.get('name')
    email = data.get('email')
    message = data.get('message')
    subject = data.get('subject')
    mobile = data.get('mobile')
    # Add contact to HubSpot
    try:
        hubspot_url = 'https://api.hubapi.com/crm/v3/objects/contacts'
        headers = {
            'Authorization': f'Bearer {HUBSPOT_ACCESS_TOKEN}',
            'Content-Type': 'application/json'
        }
        payload = {
            'properties': {
                'email': email,
                'firstname': name,
                'message': message,
                'phone': mobile
            }
        }

        response = requests.post(hubspot_url, json=payload, headers=headers)
        response.raise_for_status()

    except requests.exceptions.RequestException as e:
        print(f"Error adding contact to HubSpot: {e}")

    try:

        # Send email notification
        msg = Message('New Contact Form Submission',
                      recipients=[os.getenv('RECEIVER_EMAIL')])
        msg.body = f"Name: {name}\nEmail: {email}\nMobile Phone: {mobile}\nSubject: {subject}\nMessage: {message}"
        mail.send(msg)

        return jsonify({'message': 'Form submitted successfully.'}), 200

    except requests.exceptions.RequestException as e:
        print(f"Error sending email: {e}")
        return jsonify({'message': 'Error submitting form.'}), 500

@app.route('/zigtech')
def zigtech():
    instance = ec2.Instance(INSTANCE_ID)
    status = instance.state['Name']  # 'running' or 'stopped'
    if status not in ['running', 'stopped']:
        refresh = True
    else:
        refresh = False
    return render_template('zigtech.html', status=status, refresh=refresh)

@app.route('/start_instance', methods=['POST'])
def start_instance():
    instance = ec2.Instance(INSTANCE_ID)
    instance.start()
    return redirect(url_for('zigtech'))

@app.route('/stop_instance', methods=['POST'])
def stop_instance():
    instance = ec2.Instance(INSTANCE_ID)
    instance.stop()
    return redirect(url_for('zigtech'))

@app.route('/blog')
def blog():
    # Fetch blog posts
    posts = fetch_blog_posts()
    return render_template('blog.html', posts=posts)

@app.route('/blog/<int:post_id>')
def blog_post(post_id):
    # Logic to fetch the blog post with post_id from your WordPress API
    post = get_blog_post(post_id)  # Replace with your function to fetch blog post
    return render_template('blog_post.html', post=post)

@app.route('/signup', methods=['GET', 'POST'])
def signup():
    form = RegistrationForm()
    if form.validate_on_submit():
        user = User(username=form.username.data, email=form.email.data)
        user.set_password(form.password.data)
        db.session.add(user)
        db.session.commit()
        flash('Congratulations, you are now a registered user!')
        return redirect(url_for('login'))
    return render_template('signup.html', title='Sign Up', form=form)

@app.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user is None or not user.check_password(form.password.data):
            flash('Invalid email or password')
            return redirect(url_for('login'))
        # Log in user
        login_user(user)  # Log in the user
        flash('You are now logged in!')
        return redirect(url_for('dashboard'))  # Redirect to the appropriate page
    return render_template('login.html', title='Log In', form=form)

@app.route('/logout')
def logout():
    logout_user()  # Log out the user
    flash('You have been logged out')
    return redirect(url_for('index'))  # Redirect to the homepage or another appropriate page

#@app.route('/dashboard')
#@login_required  # Ensure that only logged-in users can access this route
#def dashboard():
#    return render_template('dashboard.html', title='Dashboard', user=current_user)

@app.route('/reset_password', methods=['GET', 'POST'])
def reset_password():
    if request.method == 'POST':
        # Process the form submission to send password reset instructions
        email = request.form.get('email')
        # Implement logic to send password reset instructions to the user's email
        flash('Instructions to reset your password have been sent to your email.')
        return redirect(url_for('login'))
    return render_template('reset_password.html')

@app.route('/', methods=['GET', 'POST'])
def home():
    posts = fetch_blog_posts()
    return render_template('index.html', posts=posts)

@app.route('/index', methods=['GET', 'POST'])
def index():
    posts = fetch_blog_posts()
    return render_template('index.html', posts=posts)

@app.route('/calculate', methods=['POST'])
def calculate():
    data = request.json
    service_type = data.get('service_type')
    hourly_rate = float(data.get('hourly_rate').replace('$', '').replace(',', ''))
    initial_investment = float(data.get('initial_investment').replace('$', '').replace(',', ''))
    estimated_hours = float(data.get('estimated_hours'))
    task_frequency = int(data.get('task_frequency'))
    time_frame = data.get('time_frame')

    if time_frame == 'monthly':
        gain_from_investment = hourly_rate * estimated_hours * task_frequency * 12
    else:  # yearly
        gain_from_investment = hourly_rate * estimated_hours * task_frequency

    cost_of_investment = initial_investment
    roi_percentage = ((gain_from_investment - cost_of_investment) / cost_of_investment) * 100 if cost_of_investment != 0 else 0
    savings = gain_from_investment - cost_of_investment

    if savings != 0:
        break_even_months = cost_of_investment / (gain_from_investment / 12)
        break_even_months = break_even_months if time_frame == 'yearly' else break_even_months / 12
    else:
        break_even_months = float('inf')

    response = {
        'roi_percentage': roi_percentage,
        'savings': savings,
        'break_even_months': break_even_months
    }
    return jsonify(response)

@app.route('/features', methods=['GET', 'POST'])
def features():
    return render_template('feature.html')

@app.route('/contact', methods=['GET', 'POST'])
def contact():
    return render_template('contact.html')

@app.route('/privacy', methods=['GET', 'POST'])
def privacy():
    return render_template('privacy.html')

@app.route('/about', methods=['GET', 'POST'])
def about():
    return render_template('about.html')

@app.route('/pricing', methods=['GET', 'POST'])
def pricing():
    return render_template('pricing.html')

@app.route('/services', methods=['GET', 'POST'])
def service():
    return render_template('service.html')

@app.route('/testimonials', methods=['GET', 'POST'])
def testimonials():
    return render_template('testimonial.html')

if __name__ == '__main__':
    #db.create_all()
    app.run(debug=True)

##############################################################################
# Regular functions

def fetch_blog_posts():
    # Replace 'your_wordpress_url' with the URL of your WordPress site
    url = 'https://blog.jakeedwards.xyz/wp-json/wp/v2/posts'
    response = requests.get(url)
    if response.status_code == 200:
        return response.json()
    else:
        return None



def get_blog_post(post_id):
    # Replace 'YOUR_WORDPRESS_API_ENDPOINT' with the actual endpoint of your WordPress API
    url = f'https://blog.jakeedwards.xyz/wp-json/wp/v2/posts/{post_id}'
    
    try:
        response = requests.get(url)
        if response.status_code == 200:
            post_data = response.json()
            post = {
                'id': post_data['id'],
                'title': post_data['title']['rendered'],
                'content': Markup(post_data['content']['rendered']),  # Decode HTML entities
                # Add other fields you want to fetch from the API response
            }
            return post
        else:
            # Handle API errors
            print("Error with wordpress API")
            print(response.json())

            return None
    except requests.RequestException as e:
        # Handle request errors
        print(f"Error fetching blog post: {e}")
        return None
