from flask import Flask, render_template, abort, request, session, redirect, url_for
import json
import os

app = Flask(__name__)
app.secret_key = 'super-secret-garden-key'

# Path to the products data
DATA_FILE = os.path.join(os.path.dirname(__file__), 'data', 'products.json')

def load_products():
    try:
        with open(DATA_FILE, 'r') as f:
            return json.load(f)
    except (FileNotFoundError, json.JSONDecodeError):
        return []

def get_cart_count():
    cart = session.get('cart', {})
    return sum(item['quantity'] for item in cart.values())

@app.route('/')
def index():
    category = request.args.get('category')
    search_query = request.args.get('q', '').lower()
    
    products = load_products()
    
    if category:
        products = [p for p in products if p['category'].lower() == category.lower()]
    
    if search_query:
        products = [p for p in products if search_query in p['name'].lower() or search_query in p['description'].lower()]
        
    return render_template('index.html', 
                           products=products, 
                           active_category=category, 
                           search_query=search_query,
                           cart_count=get_cart_count())

@app.route('/product/<int:product_id>')
def product_detail(product_id):
    products = load_products()
    product = next((p for p in products if p['id'] == product_id), None)
    if product is None:
        abort(404)
    return render_template('product.html', 
                           product=product, 
                           cart_count=get_cart_count())

@app.route('/cart/add/<int:product_id>', methods=['POST'])
def add_to_cart(product_id):
    cart = session.get('cart', {})
    
    if str(product_id) in cart:
        cart[str(product_id)]['quantity'] += 1
    else:
        cart[str(product_id)] = {'quantity': 1}
    
    session['cart'] = cart
    return {"status": "success", "cart_count": get_cart_count()}

@app.route('/cart/update/<int:product_id>', methods=['POST'])
def update_cart_quantity(product_id):
    cart = session.get('cart', {})
    pid_str = str(product_id)
    
    try:
        quantity = int(request.form.get('quantity', 1))
    except (ValueError, TypeError):
        quantity = 1

    if pid_str in cart:
        if quantity <= 0:
            del cart[pid_str]
        else:
            cart[pid_str]['quantity'] = quantity
    
    session['cart'] = cart
    return redirect(url_for('view_cart'))

@app.route('/cart/remove/<int:product_id>', methods=['POST'])
def remove_from_cart(product_id):
    cart = session.get('cart', {})
    pid_str = str(product_id)
    
    if pid_str in cart:
        if cart[pid_str]['quantity'] > 1:
            cart[pid_str]['quantity'] -= 1
        else:
            del cart[pid_str]
    
    session['cart'] = cart
    return redirect(url_for('view_cart'))

@app.route('/cart/clear', methods=['POST'])
def clear_cart():
    session['cart'] = {}
    return redirect(url_for('view_cart'))

@app.route('/cart')
def view_cart():
    cart_data = session.get('cart', {})
    products = load_products()
    
    cart_items = []
    total_price = 0
    
    for pid_str, item in cart_data.items():
        product = next((p for p in products if p['id'] == int(pid_str)), None)
        if product:
            item_total = product['price'] * item['quantity']
            cart_items.append({
                'product': product,
                'quantity': item['quantity'],
                'item_total': item_total
            })
            total_price += item_total
            
    return render_template('cart.html', cart_items=cart_items, total_price=total_price)

@app.route('/checkout')
def checkout():
    if not session.get('cart'):
        return redirect(url_for('cart'))
    return render_template('checkout.html')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5050, debug=True)
