import os
import shutil
import threading
from flask import Blueprint, jsonify, request, current_app, session
from app_server.extensions import db, socketio
from werkzeug.utils import secure_filename
from app_server.models import User, Product, Category, Order, OrderItem, ShopSettings, Expense, Coupon, KhataAccount, KhataTransaction, BankAccount, Company, FinancePayment, DailyProfit, Employee, Attendance, BackupSetting, PurchaseOrder, Review, Wishlist, PosSyncLog
from app_server import currency_config
from datetime import datetime, timedelta
from sqlalchemy import func
from app_server.utils.security import (
    hash_password,
    needs_password_rehash,
    normalize_email,
    verify_password,
)
from app_server.utils.registration import (
    create_verified_customer,
    registration_payload,
    registration_pending_matches,
    send_registration_otps,
    validate_registration_payload,
    verify_registration_otps,
)
from twilio.rest import Client

# Do not import pywhatkit at load time: it pulls pyautogui and requires DISPLAY (breaks Passenger/WSGI).

# Twilio Credentials
TWILIO_ACCOUNT_SID = 'AC34edbf192118dbb49be0cbf19c6273d6'
TWILIO_AUTH_TOKEN = 'fc320c00642f399a2edfc8f4df2a4fd7'
TWILIO_PHONE_NUMBER = '+15822670005'

# WhatsApp via Twilio (sandbox) – enable if you have a Twilio WhatsApp sandbox number
WHATSAPP_TWILIO_ENABLED = True
# Replace with your Twilio sandbox WhatsApp number (e.g., '+14155238886')
TWILIO_WHATSAPP_NUMBER = '+14155238886'


api_bp = Blueprint('api', __name__)

# ==========================================
# 🌐 1. SERVER STATUS
# ==========================================
@api_bp.route('/status', methods=['GET'])
def server_status():
    return jsonify({
        "status": "running",
        "message": "SwiftCart API is Online!",
        "currency": currency_config.CURRENCY_DISPLAY,
        "currency_code": currency_config.CURRENCY_CODE,
    })

# ==========================================
# 🔐 2. AUTHENTICATION (LOGIN)
# ==========================================
@api_bp.route('/login', methods=['POST'])
def login():
    data = request.json
    username = data.get('username')
    password = data.get('password')

    user = User.query.filter_by(username=username).first()

    # Hardware fallback / Default bypass if no user exists in DB yet
    if not user and username == "admin" and password == "admin":
        return jsonify({"message": "Login Successful!", "user_id": 0, "role": "admin", "username": "admin"}), 200

    if user and verify_password(user.password, password):
        if needs_password_rehash(user.password):
            user.password = hash_password(password)
            db.session.commit()
        return jsonify({
            "message": "Login Successful!",
            "user_id": user.id,
            "role": user.role,
            "username": user.username
        }), 200
    else:
        return jsonify({"message": "Invalid Credentials"}), 401


@api_bp.route('/register/send-otp', methods=['POST'])
def register_send_otp():
    data = request.json or {}
    payload = registration_payload(data)
    error = validate_registration_payload(payload)
    if error:
        return jsonify({"ok": False, "message": error}), 400

    try:
        sent, result = send_registration_otps(payload)
        if not sent:
            return jsonify({"ok": False, "message": result}), 503

        session["signup_pending"] = result
        return jsonify({
            "ok": True,
            "message": "Email verification code sent.",
        })
    except ValueError as exc:
        return jsonify({"ok": False, "message": str(exc)}), 429
    except Exception:
        db.session.rollback()
        return jsonify({"ok": False, "message": "Could not send verification codes."}), 500


@api_bp.route('/register/verify', methods=['POST'])
def register_verify():
    data = request.json or {}
    pending = session.get("signup_pending")
    payload = registration_payload(data)
    matches, message = registration_pending_matches(pending, payload)
    if not matches:
        return jsonify({"ok": False, "message": message}), 400

    verified, message = verify_registration_otps(
        pending,
        payload,
        (data.get("email_otp") or "").strip(),
    )
    if not verified:
        return jsonify({"ok": False, "message": message}), 400

    error = validate_registration_payload(payload)
    if error:
        return jsonify({"ok": False, "message": error}), 400

    user, message = create_verified_customer(payload)
    if not user:
        return jsonify({"ok": False, "message": message}), 400

    session.pop("signup_pending", None)
    return jsonify({"ok": True, "message": message, "user_id": user.id}), 201

# ==========================================
# 📂 3. CATEGORY MANAGEMENT 
# ==========================================
@api_bp.route('/categories', methods=['GET', 'POST'])
def handle_categories():
    if request.method == 'GET':
        categories = Category.query.all()
        result = [{"id": c.id, "name": c.name} for c in categories]
        return jsonify({"categories": result}), 200
        
    elif request.method == 'POST':
        data = request.json
        if not data.get('name'): 
            return jsonify({"message": "Name required"}), 400
            
        if Category.query.filter_by(name=data['name']).first():
            return jsonify({"message": "Category already exists!"}), 400
            
        new_cat = Category(name=data['name'])
        try:
            db.session.add(new_cat)
            db.session.commit()
            return jsonify({"message": "Category created successfully!", "id": new_cat.id}), 201
        except Exception as e:
            return jsonify({"message": str(e)}), 500

@api_bp.route('/categories/<int:cat_id>', methods=['PUT', 'DELETE'])
def manage_single_category(cat_id):
    cat = Category.query.get(cat_id)
    if not cat:
        return jsonify({"message": "Category not found"}), 404
        
    if request.method == 'PUT':
        data = request.json
        cat.name = data['name']
        db.session.commit()
        return jsonify({"message": "Category updated!"}), 200
        
    elif request.method == 'DELETE':
        db.session.delete(cat)
        db.session.commit()
        return jsonify({"message": "Category deleted!"}), 200

# ==========================================
# 📦 4. PRODUCT INVENTORY MANAGEMENT
# ==========================================
@api_bp.route('/products', methods=['GET', 'POST'])
def handle_products():
    if request.method == 'GET':
        products = Product.query.all()
        result = []
        for p in products:
            result.append({
                "id": p.id,
                "name": p.name,
                "price": p.price,
                "purchase_price": p.purchase_price,
                "stock": p.stock,
                "min_stock": p.min_stock,
                "barcode": p.barcode,
                "supplier": p.supplier,
                "brand": p.brand,
                "discount_price": p.discount_price,
                "category_id": p.category_id,
                "category": p.category.name if p.category else "Uncategorized",
                "image_file": p.image_file,
                "show_in_recent": p.show_in_recent,
                "show_in_gifts": p.show_in_gifts,
                "show_in_deals": p.show_in_deals,
                "show_in_video": p.show_in_video,
                "flash_sale_end": p.flash_sale_end.isoformat() if p.flash_sale_end else None,
                "flash_sale_video": p.flash_sale_video,
                "physical_sale_video": p.physical_sale_video,
                "expiry_date": p.expiry_date.isoformat() if getattr(p, "expiry_date", None) else None,
                "last_updated": p.last_updated.isoformat() if getattr(p, "last_updated", None) else None,
            })
        return jsonify({"products": result}), 200
        
    elif request.method == 'POST':
        # Ab data JSON se nahi, balkay Form Data se aayega (taake file bhi aa sake)
        data = request.form
        
        # Check if Barcode exists
        if data.get('barcode'):
            exist = Product.query.filter_by(barcode=data['barcode']).first()
            if exist: return jsonify({"message": "Barcode already used!"}), 400

        # --- IMAGE UPLOAD LOGIC ---
        image_filename = 'default.png'
        if 'image' in request.files:
            file = request.files['image']
            if file and file.filename != '':
                filename = secure_filename(file.filename)
                unique_name = f"{int(datetime.utcnow().timestamp())}_{filename}"
                
                upload_folder = os.path.join(current_app.root_path, 'static', 'uploads')
                os.makedirs(upload_folder, exist_ok=True) 
                file.save(os.path.join(upload_folder, unique_name))
                image_filename = unique_name

        def _parse_category_id(raw):
            if raw is None or str(raw).strip() == "":
                return None
            try:
                return int(raw)
            except (TypeError, ValueError):
                return None

        exp_date = None
        if data.get("expiry_date"):
            try:
                exp_date = datetime.strptime(data["expiry_date"].strip()[:10], "%Y-%m-%d").date()
            except (ValueError, TypeError):
                pass

        new_product = Product(
            name=data.get('name'),
            price=float(data.get('price', 0)),
            purchase_price=float(data.get('purchase_price', 0)),
            stock=int(data.get('stock', 0)),
            min_stock=int(data.get('min_stock', 5)),
            barcode=data.get('barcode', ''),
            supplier=data.get('supplier', ''),
            brand=data.get('brand', ''),
            discount_price=float(data.get('discount_price', 0)),
            category_id=_parse_category_id(data.get('category_id')),
            image_file=image_filename,
            expiry_date=exp_date,
            show_in_recent=data.get('show_in_recent') == 'true',
            show_in_gifts=data.get('show_in_gifts') == 'true',
            show_in_deals=data.get('show_in_deals') == 'true',
            show_in_video=data.get('show_in_video') == 'true'
        )
        if data.get('flash_sale_end'):
            try:
                new_product.flash_sale_end = datetime.strptime(
                    data['flash_sale_end'].strip(), "%Y-%m-%d %H:%M:%S"
                )
            except (ValueError, TypeError, AttributeError):
                pass
        if data.get('flash_sale_video'):
            new_product.flash_sale_video = data['flash_sale_video'].strip()
        if data.get('physical_sale_video'):
            new_product.physical_sale_video = data['physical_sale_video'].strip()

        if 'physical_video_file' in request.files:
            pvf = request.files['physical_video_file']
            if pvf and pvf.filename != '':
                pfn = secure_filename(pvf.filename)
                vname = f"video_{int(datetime.utcnow().timestamp())}_{pfn}"
                upload_folder = os.path.join(current_app.root_path, 'static', 'uploads')
                os.makedirs(upload_folder, exist_ok=True)
                pvf.save(os.path.join(upload_folder, vname))
                new_product.physical_sale_video = vname

        try:
            db.session.add(new_product)
            db.session.commit()
            return jsonify({"message": "Product saved successfully!", "id": new_product.id}), 201
        except Exception as e:
            return jsonify({"message": str(e)}), 500

@api_bp.route('/update-product/<int:pid>', methods=['PUT'])
def update_product(pid):
    p = Product.query.get(pid)
    if not p: return jsonify({"message": "Product not found"}), 404
    
    # Ab JSON ke bajaye Form Data receive karega (Image ke liye)
    data = request.form if request.form else request.json
    if not data: data = {}

    if 'name' in data: p.name = data['name']
    if 'price' in data: p.price = float(data['price'])
    if 'purchase_price' in data: p.purchase_price = float(data['purchase_price'])
    if 'stock' in data: p.stock = int(data['stock'])
    if 'min_stock' in data: p.min_stock = int(data['min_stock'])
    if 'barcode' in data: p.barcode = data['barcode']
    if 'supplier' in data: p.supplier = data['supplier']
    if 'brand' in data: p.brand = data['brand']
    if 'discount_price' in data: p.discount_price = float(data.get('discount_price', 0))
    if 'category_id' in data:
        raw = data.get('category_id')
        if raw is None or str(raw).strip() == "":
            p.category_id = None
        else:
            try:
                p.category_id = int(raw)
            except (TypeError, ValueError):
                p.category_id = None

    if 'expiry_date' in data:
        ev = (data.get('expiry_date') or '').strip()
        if ev:
            try:
                p.expiry_date = datetime.strptime(ev[:10], "%Y-%m-%d").date()
            except (ValueError, TypeError):
                pass
        else:
            p.expiry_date = None
    
    if 'show_in_recent' in data: p.show_in_recent = data['show_in_recent'] == 'true'
    if 'show_in_gifts' in data: p.show_in_gifts = data['show_in_gifts'] == 'true'
    if 'show_in_deals' in data: p.show_in_deals = data['show_in_deals'] == 'true'
    if 'show_in_video' in data: p.show_in_video = data['show_in_video'] == 'true'
    
    if 'flash_sale_end' in data:
        try:
            p.flash_sale_end = datetime.strptime(data['flash_sale_end'], "%Y-%m-%d %H:%M:%S")
        except:
            pass
    if 'flash_sale_video' in data: p.flash_sale_video = data['flash_sale_video']
    if 'physical_sale_video' in data: p.physical_sale_video = data['physical_sale_video']
    
    # --- NEW: UPDATE IMAGE LOGIC ---
    if 'image' in request.files:
        file = request.files['image']
        if file and file.filename != '':
            filename = secure_filename(file.filename)
            unique_name = f"{int(datetime.utcnow().timestamp())}_{filename}"
            upload_folder = os.path.join(current_app.root_path, 'static', 'uploads')
            os.makedirs(upload_folder, exist_ok=True)
            file.save(os.path.join(upload_folder, unique_name))
            p.image_file = unique_name # Database mein naya naam save karein

    if 'physical_video_file' in request.files:
        file = request.files['physical_video_file']
        if file and file.filename != '':
            filename = secure_filename(file.filename)
            unique_name = f"video_{int(datetime.utcnow().timestamp())}_{filename}"
            upload_folder = os.path.join(current_app.root_path, 'static', 'uploads')
            os.makedirs(upload_folder, exist_ok=True)
            file.save(os.path.join(upload_folder, unique_name))
            p.physical_sale_video = unique_name

    db.session.commit()
    return jsonify({"message": "Product updated!"}), 200

@api_bp.route('/delete-product/<int:pid>', methods=['DELETE'])
def delete_product(pid):
    p = Product.query.get(pid)
    if not p: return jsonify({"message": "Product not found"}), 404
    try:
        db.session.delete(p)
        db.session.commit()
        return jsonify({"message": "Product deleted!"}), 200
    except:
        return jsonify({"message": "Cannot delete (Used in orders)"}), 500

# ==========================================
# 🛒 5. CREATE ORDER
# ==========================================
@api_bp.route('/create-order', methods=['POST'])
def create_order():
    data = request.json
    items = data.get('items', [])
    cust_email = data.get('customer_email', '')

    if not items: return jsonify({"message": "Cart empty"}), 400

    gross = sum(i['price'] * i['qty'] for i in items)
    discount = float(data.get('discount', 0))
    tax = float(data.get('tax', 0))
    final = (gross - discount) + tax

    # Generate Order ID manually since it's a string
    order_count = Order.query.count()
    new_id = f"INV-10{order_count + 1}"

    new_order = Order(
        id=new_id,
        customer_name=data.get('customer_name', 'Walk-in'),
        customer_phone=data.get('customer_phone', ''),
        customer_email=cust_email,
        subtotal=gross,
        discount=discount,
        tax=tax,
        final_total=final,
        payment_method=data.get('payment_method') or data.get('payment_mode', 'Cash'),
        cashier=data.get('cashier', 'Admin'),
        user_id=data.get('user_id', 1),
        source=data.get('source') or 'POS',
    )
    
    try:
        db.session.add(new_order)
        db.session.flush()

        for item in items:
            prod = Product.query.get(item['id'])
            if prod:
                if prod.stock < item['qty']:
                    db.session.rollback()
                    return jsonify({"message": f"Low Stock: {prod.name}"}), 400
                
                # 📉 POS sale hote hi stock kam karo
                prod.stock -= item['qty']
                
                # Agar stock zero ho jaye, toh socket ke zariye web ko signal bhej sakte hain
                if prod.stock <= 0:
                    socketio.emit('stock_update', {'product_id': prod.id, 'status': 'out_of_stock'})
            
            oi = OrderItem(order_id=new_order.id, product_name=item['name'], price=item['price'], quantity=item['qty'])
            db.session.add(oi)

        db.session.commit()
        
        # ✅ SMS + WhatsApp Notification for Platform (POS)
        if new_order.customer_phone:
            formatted_phone = new_order.customer_phone
            if not formatted_phone.startswith('+'):
                formatted_phone = "+92" + formatted_phone.lstrip('0')
            
            msg = (f"Thank you for shopping with SwiftCart.\n"
                   f"Your order #{new_order.id} has been placed successfully.\n"
                   f"Total: Rs. {new_order.final_total:,.2f}")
            
            # 📩 SMS bhejo (Twilio)
            send_sms_notification(formatted_phone, msg, new_order.id)
            # 📱 WhatsApp bhi bhejo (Free, Unlimited)
            send_whatsapp_notification(formatted_phone, msg, new_order.id)

        return jsonify({"message": "Order Created", "order_id": new_order.id}), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({"message": str(e)}), 500

@api_bp.route('/order-details/<order_id>')
def order_details(order_id):
    order = Order.query.get(order_id)
    if order:
        return jsonify({
            "id": order.id,
            "customer_name": order.customer_name,
            "customer_phone": order.customer_phone,
            "final_total": order.final_total,
            "items": [{"name": i.product_name, "qty": i.quantity, "price": i.price} for i in order.items]
        }), 200
    return jsonify({"message": "Not found"}), 404

# ==========================================
# 📜 6. GET ORDERS (SALES HISTORY)
# ==========================================
@api_bp.route('/orders', methods=['GET'])
def get_orders():
    orders = Order.query.order_by(Order.date.desc()).all()
    output = []
    for o in orders:
        items_data = [{"name": i.product_name, "price": i.price, "qty": i.quantity} for i in o.items]
        output.append({
            "id": o.id,
            "customer": o.customer_name,
            "customer_phone": o.customer_phone,
            "subtotal": o.subtotal,
            "discount": o.discount,
            "tax": o.tax,
            "final_total": o.final_total,
            "method": o.payment_method,
            "payment_method": o.payment_method,
            "status": o.status,
            "cashier": o.cashier,
            "date": o.date.strftime("%Y-%m-%d %H:%M"),
            "items_count": len(o.items),
            "items": items_data,
            "source": getattr(o, "source", None) or "POS",
        })
    return jsonify({"orders": output})

@api_bp.route('/stats/recent-transactions', methods=['GET'])
def recent_transactions():
    try:
        last_orders = Order.query.order_by(Order.date.desc()).limit(7).all()
        res = []
        for o in last_orders:
            res.append({
                "id": o.id,
                "customer": o.customer_name or "Walk-in",
                "amount": o.final_total,
                "status": o.status,
                "date": o.date.strftime('%Y-%m-%d %H:%M')
            })
        return jsonify(res), 200
    except Exception as e:
        return jsonify({"error": str(e)}), 500

# ==========================================
# 💰 FINANCE API ROUTES
# ==========================================

@api_bp.route('/finance/banks', methods=['GET', 'POST'])
def finance_banks():
    if request.method == 'POST':
        data = request.json
        bank = BankAccount(name=data['name'], contact_person=data.get('contact_person'), phone=data.get('phone'), address=data.get('address'), current_credit=data.get('current_credit', 0))
        db.session.add(bank)
        db.session.commit()
        return jsonify({"message": "Bank added"}), 201
    banks = BankAccount.query.all()
    return jsonify([{"id": b.id, "name": b.name, "contact_person": b.contact_person, "phone": b.phone, "address": b.address, "current_credit": b.current_credit} for b in banks])

@api_bp.route('/finance/companies', methods=['GET', 'POST'])
def finance_companies():
    if request.method == 'POST':
        data = request.json
        comp = Company(name=data['name'], contact_person=data.get('contact_person'), email=data.get('email'), phone=data.get('phone'))
        db.session.add(comp)
        db.session.commit()
        return jsonify({"message": "Company added"}), 201
    comps = Company.query.all()
    return jsonify([{"id": c.id, "name": c.name, "contact_person": c.contact_person, "email": c.email, "phone": c.phone} for c in comps])

@api_bp.route('/finance/payments', methods=['GET', 'POST'])
def finance_payments():
    if request.method == 'POST':
        data = request.json
        pay = FinancePayment(party_type=data['party_type'], party_name=data['party_name'], txn_type=data['txn_type'], amount=data['amount'], method=data['method'], bank_name=data.get('bank_name'), description=data.get('description'))
        db.session.add(pay)
        db.session.commit()
        return jsonify({"message": "Payment recorded"}), 201
    pays = FinancePayment.query.order_by(FinancePayment.date.desc()).all()
    return jsonify([{"id": p.id, "party_type": p.party_type, "party_name": p.party_name, "txn_type": p.txn_type, "amount": p.amount, "method": p.method, "bank_name": p.bank_name, "description": p.description, "date": p.date.strftime("%Y-%m-%d %H:%M:%S")} for p in pays])

@api_bp.route('/finance/profits', methods=['GET', 'POST'])
def finance_profits():
    if request.method == 'POST':
        data = request.json
        pd = data.get('date')
        if pd:
            d = datetime.strptime(pd, "%Y-%m-%d")
        else:
            d = datetime.utcnow()
        prof = DailyProfit(purchase_amount=data['purchase_amount'], sale_amount=data['sale_amount'], profit=data['profit'], description=data.get('description'), date=d)
        db.session.add(prof)
        db.session.commit()
        return jsonify({"message": "Profit recorded"}), 201
    profs = DailyProfit.query.order_by(DailyProfit.date.desc()).all()
    return jsonify([{"id": p.id, "purchase_amount": p.purchase_amount, "sale_amount": p.sale_amount, "profit": p.profit, "description": p.description, "date": p.date.strftime("%Y-%m-%d")} for p in profs])

@api_bp.route('/online-orders', methods=['GET'])
def get_online_orders():
    orders = Order.query.filter_by(source='Web').order_by(Order.date.desc()).limit(10).all()
    output = []
    for o in orders:
        output.append({
            "id": o.id,
            "customer": o.customer_name,
            "total": o.final_total,
            "status": o.status
        })
    return jsonify(output)

@api_bp.route('/return-order/<string:order_id>', methods=['POST'])
def return_order(order_id):
    order = Order.query.get(order_id)
    if not order: return jsonify({"message": "Not found"}), 404
    if order.status == 'Refunded': return jsonify({"message": "Already Refunded"}), 400

    try:
        for item in order.items:
            prod = Product.query.filter_by(name=item.product_name).first()
            if prod: prod.stock += item.quantity
        
        order.status = 'Refunded'
        db.session.commit()
        return jsonify({"message": "Returned & Stock Restored"}), 200
    except Exception as e:
        return jsonify({"message": str(e)}), 500

@api_bp.route('/cashbook-today', methods=['GET'])
def cashbook_today():
    today_start = datetime.combine(datetime.utcnow().date(), datetime.min.time())
    
    # Orders Today
    all_orders = Order.query.filter(Order.date >= today_start).all()
    
    cash_sales = 0
    bank_sales = 0
    credit_sales = 0
    return_sales = 0
    
    for o in all_orders:
        if o.status == 'Refunded':
            return_sales += o.final_total
            continue
            
        pm_lower = o.payment_method.lower()
        if 'credit' in pm_lower or 'udhaar' in pm_lower:
            credit_sales += o.final_total
        elif pm_lower in ['card', 'online', 'bank']:
            bank_sales += o.final_total
        else:
            cash_sales += o.final_total
            
    total_sales = cash_sales + bank_sales + credit_sales
    
    # Expenses Today
    today_exp = Expense.query.filter(Expense.date >= today_start).all()
    expenses_total = sum(e.amount for e in today_exp)
    salary_paid = sum(e.amount for e in today_exp if 'salary' in e.description.lower())
    
    # Other placeholders (since we don't track hard cash purchases specifically vs bank yet)
    data = {
        "cash_sales": cash_sales,
        "bank_sales": bank_sales,
        "credit_sales": credit_sales,
        "return_sales": return_sales,
        "total_sales": total_sales,
        "expenses": expenses_total,
        "salary_paid": salary_paid,
        "total_purchase": 0.0, # Implement later based on PO
        "credit_purchases": 0.0
    }
    return jsonify(data), 200

# ==========================================
# 📊 7. DASHBOARD STATS & ANALYTICS
# ==========================================
@api_bp.route('/dashboard-stats', methods=['GET'])
def dashboard_stats():
    try:
        # Sales
        revenue = db.session.query(func.sum(Order.final_total)).filter(Order.status!='Refunded').scalar() or 0
        orders_count = Order.query.count()
        low_stock = Product.query.filter(Product.stock <= Product.min_stock).count()
        
        # Optimized Profit Calculation (Using Joins instead of N+1 loop)
        cogs = db.session.query(func.sum(Product.purchase_price * OrderItem.quantity))\
            .join(OrderItem, Product.name == OrderItem.product_name)\
            .join(Order, OrderItem.order_id == Order.id)\
            .filter(Order.status != 'Refunded').scalar() or 0
        
        expenses = db.session.query(func.sum(Expense.amount)).scalar() or 0
        net_profit = revenue - cogs - expenses

        # --- NEW DASHBOARD STATS ---
        today_start = datetime.combine(datetime.utcnow().date(), datetime.min.time())
        today_orders = Order.query.filter(Order.status != 'Refunded', Order.date >= today_start).all()
        
        today_sales = sum(o.final_total for o in today_orders)
        
        # Cash vs Card (Today)
        today_cash = sum(o.final_total for o in today_orders if o.payment_method.lower() == 'cash')
        today_card = sum(o.final_total for o in today_orders if o.payment_method.lower() in ['card', 'online'])
        
        # Web vs POS (Today)
        today_web = sum(o.final_total for o in today_orders if o.source == 'Web')
        today_shop = sum(o.final_total for o in today_orders if o.source != 'Web')

        # Top 5 Selling Products (Overall or Today - Let's do Overall Top 5 for better visualization)
        top_items_query = db.session.query(
            OrderItem.product_name, 
            func.sum(OrderItem.quantity).label('total_qty')
        ).join(Order, OrderItem.order_id == Order.id)\
         .filter(Order.status != 'Refunded')\
         .group_by(OrderItem.product_name)\
         .order_by(func.sum(OrderItem.quantity).desc())\
         .limit(5).all()
         
        top_products = [{"name": row.product_name, "qty": row.total_qty} for row in top_items_query]

        top_products = [{"name": row.product_name, "qty": row.total_qty} for row in top_items_query]

        # Calculate Average Order Value
        avg_order_value = (revenue / orders_count) if orders_count > 0 else 0

        # --- FINANCE STATS ---
        today_date_str = datetime.utcnow().strftime('%Y-%m-%d')
        # Sum of manual daily profits entered today (if any)
        manual_profits_today = db.session.query(func.sum(DailyProfit.profit))\
            .filter(func.date(DailyProfit.date) == today_date_str).scalar() or 0
            
        # Total Bank Reserves
        bank_reserves = db.session.query(func.sum(BankAccount.current_credit)).scalar() or 0

        return jsonify({
            "revenue": revenue,
            "orders": orders_count,
            "low_stock": low_stock,
            "profit": net_profit,
            "today_sales": today_sales,
            "today_cash": today_cash,
            "today_card": today_card,
            "today_web": today_web,
            "today_shop": today_shop,
            "top_products": top_products,
            "avg_order_value": avg_order_value,
            "manual_profit_today": manual_profits_today,
            "bank_reserves": bank_reserves
        })
    except Exception as e:
        return jsonify({"message": str(e)}), 500

@api_bp.route('/sales-chart', methods=['GET'])
def sales_chart():
    today = datetime.utcnow().date()
    dates = []
    sales = []
    for i in range(6, -1, -1):
        d = today - timedelta(days=i)
        total = db.session.query(func.sum(Order.final_total))\
            .filter(func.date(Order.date) == str(d))\
            .filter(Order.status!='Refunded').scalar() or 0
        dates.append(d.strftime('%d %b'))
        sales.append(total)
    return jsonify({"dates": dates, "sales": sales})

# -----------------------------------------------------------------
# ADMIN: Delete all sales (Web & POS) but keep product stock unchanged
# -----------------------------------------------------------------
@api_bp.route('/admin/clear-sales', methods=['POST'])
def clear_sales():
    # Simple admin check – requires admin user
    #  logged in via session
    if 'user_id' not in session:
        return jsonify({"message": "Login required"}), 401
    user = User.query.get(session['user_id'])
    if not user or user.role != 'admin':
        return jsonify({"message": "Admin access required"}), 403

    try:
        # Delete OrderItems first (cascade may handle, but explicit for safety)
        db.session.query(OrderItem).delete(synchronize_session=False)
        # Delete Orders (both Web and POS sources)
        db.session.query(Order).filter(Order.source.in_(['Web', 'POS'])).delete(synchronize_session=False)
        db.session.commit()
        return jsonify({"message": "All sales records cleared (stock untouched)"}), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({"message": f"Error clearing sales: {str(e)}"}), 500


# -----------------------------------------------------------------
# ADMIN: Remove all products from the web catalog (optionally categories)
# Auth: Flask session admin OR header X-SwiftCart-Reset-Key == env SWIFTCART_RESET_KEY
# -----------------------------------------------------------------
@api_bp.route("/admin/clear-products", methods=["POST"])
def admin_clear_products():
    """
    Deletes all products (and dependent reviews/wishlist rows).
    JSON body optional: {"clear_categories": true} to also delete all categories.
    """
    reset_key = os.environ.get("SWIFTCART_RESET_KEY", "").strip()
    header_key = (request.headers.get("X-SwiftCart-Reset-Key") or "").strip()
    body = request.get_json(silent=True) or {}
    authorized = False
    if reset_key and header_key == reset_key:
        authorized = True
    elif "user_id" in session:
        user = User.query.get(session["user_id"])
        if user and user.role == "admin":
            authorized = True
    if not authorized:
        return jsonify({"message": "Forbidden: set SWIFTCART_RESET_KEY and send X-SwiftCart-Reset-Key, or login as admin"}), 403

    try:
        db.session.query(Review).delete(synchronize_session=False)
        db.session.query(Wishlist).delete(synchronize_session=False)
        # Product may be referenced elsewhere; delete children first
        db.session.query(Product).delete(synchronize_session=False)
        if body.get("clear_categories"):
            db.session.query(Category).delete(synchronize_session=False)
        db.session.commit()
        msg = "All products removed from the web server."
        if body.get("clear_categories"):
            msg += " Categories cleared."
        return jsonify({"message": msg}), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({"message": f"Error: {str(e)}"}), 500


# ==========================================
# 💸 8. EXPENSES
# ==========================================
@api_bp.route('/expenses', methods=['GET', 'POST'])
def handle_expenses():
    if request.method == 'POST':
        d = request.json
        exp = Expense(
            title=d['title'],
            category=d['category'], 
            amount=float(d['amount']), 
            date=datetime.strptime(d['date'], "%Y-%m-%d").date(),
            method=d['method'],
            notes=d.get('notes','')
        )
        db.session.add(exp); db.session.commit()
        return jsonify({"message": "Added"}), 201
    
    exps = Expense.query.order_by(Expense.date.desc()).all()
    out = [{
        "id": e.id, "title": e.title, "date": e.date.strftime("%Y-%m-%d"), 
        "category": e.category, "amount": e.amount, "method": e.method, "notes": e.notes
    } for e in exps]
    return jsonify({"expenses": out})

@api_bp.route('/sales-comparison')
def sales_comparison():
    from datetime import timedelta
    from sqlalchemy import func

    # Pichle 7 din ki dates nikalna
    today = datetime.utcnow().date()
    dates = [(today - timedelta(days=i)) for i in range(6, -1, -1)]
    
    web_sales = []
    shop_sales = []
    labels = []

    for d in dates:
        labels.append(d.strftime('%d %b')) # e.g. 13 Mar
        start_dt = datetime.combine(d, datetime.min.time())
        end_dt = start_dt + timedelta(days=1)
        
        # 🌐 Web Sales (Source: Web)
        w_total = db.session.query(func.sum(Order.final_total)).filter(
            Order.date >= start_dt,
            Order.date < end_dt,
            Order.source == 'Web'
        ).scalar() or 0
        web_sales.append(float(w_total))

        # 🛍️ Shop Sales (Source: POS)
        s_total = db.session.query(func.sum(Order.final_total)).filter(
            Order.date >= start_dt,
            Order.date < end_dt,
            Order.source == 'POS'
        ).scalar() or 0
        shop_sales.append(float(s_total))

    return jsonify({
        "labels": labels,
        "web": web_sales,
        "shop": shop_sales
    })


@api_bp.route('/reports/pos-sync', methods=['POST'])
def pos_report_sync():
    data = request.json or {}
    terminal = (data.get("terminal") or "Swift_Cart").strip() or "Swift_Cart"
    sales_uploaded = 0
    expenses_uploaded = 0

    for sale in data.get("sales", []):
        try:
            sale_id = int(sale.get("id"))
        except (TypeError, ValueError):
            continue
        order_id = f"POS-{sale_id}"
        if Order.query.get(order_id):
            continue

        sale_dt = datetime.utcnow()
        raw_date = sale.get("date")
        if raw_date:
            for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%d"):
                try:
                    sale_dt = datetime.strptime(str(raw_date)[:19], fmt)
                    break
                except ValueError:
                    continue

        subtotal = float(sale.get("subtotal") or 0)
        discount = float(sale.get("discount") or 0)
        tax = float(sale.get("tax") or 0)
        final_total = float(sale.get("final_total") or max(subtotal - discount + tax, 0))
        status = "Refunded" if sale.get("is_return") else "Completed"

        order = Order(
            id=order_id,
            date=sale_dt,
            customer_name=sale.get("customer_name") or "Walk-in",
            customer_phone=sale.get("customer_phone") or "",
            customer_email=sale.get("customer_email") or "",
            subtotal=subtotal,
            discount=discount,
            tax=tax,
            final_total=final_total,
            payment_method=sale.get("payment_method") or "Cash",
            status=status,
            source="POS",
            cashier=terminal,
        )
        db.session.add(order)
        db.session.flush()

        for item in sale.get("items", []):
            db.session.add(
                OrderItem(
                    order_id=order.id,
                    product_name=item.get("name") or "Item",
                    price=float(item.get("price") or 0),
                    quantity=int(float(item.get("qty") or 0)),
                )
            )
        sales_uploaded += 1

    for expense in data.get("expenses", []):
        try:
            expense_id = int(expense.get("id"))
        except (TypeError, ValueError):
            continue
        marker = f"POS-EXP:{expense_id}"
        if Expense.query.filter(Expense.notes.contains(marker)).first():
            continue

        expense_date = datetime.utcnow().date()
        raw_date = expense.get("date")
        if raw_date:
            try:
                expense_date = datetime.strptime(str(raw_date)[:10], "%Y-%m-%d").date()
            except ValueError:
                pass

        db.session.add(
            Expense(
                title=expense.get("title") or "POS expense",
                category=expense.get("category") or "General",
                amount=float(expense.get("amount") or 0),
                date=expense_date,
                method=expense.get("method") or "Cash",
                notes=f"{marker} {(expense.get('notes') or '').strip()}".strip(),
            )
        )
        expenses_uploaded += 1

    details = data.get("synced_at") or datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
    db.session.add(
        PosSyncLog(
            sales_uploaded=sales_uploaded,
            expenses_uploaded=expenses_uploaded,
            source_terminal=terminal,
            details=f"POS sync at {details}",
        )
    )
    db.session.commit()
    return jsonify(
        {
            "ok": True,
            "sales_uploaded": sales_uploaded,
            "expenses_uploaded": expenses_uploaded,
            "message": "POS report sync completed.",
        }
    ), 200


@api_bp.route('/low-stock-report')
def low_stock_report():
    # Sirf wo items uthayen jinka stock 5 ya us se kam hai
    low_stock_items = Product.query.filter(Product.stock <= 5).all()
    
    results = []
    for p in low_stock_items:
        results.append({
            "id": p.id,
            "name": p.name,
            "current_stock": p.stock,
            "price": p.price,
            "category": p.category.name if p.category else "General"
        })
    return jsonify(results), 200

# ==========================================
# ⚙️ 9. USERS & SETTINGS
# ==========================================
@api_bp.route('/users', methods=['GET'])
def get_users():
    users = User.query.all()
    return jsonify({"users": [{"id": u.id, "username": u.username, "role": u.role} for u in users]})

@api_bp.route('/add-user', methods=['POST'])
def add_user():
    d = request.json
    if User.query.filter_by(username=d['username']).first():
        return jsonify({"message": "User exists"}), 400
    u = User(
        username=d['username'],
        password=hash_password(d['password']),
        role=d.get('role', 'cashier'),
        email=normalize_email(d.get('email') or f"{d['username']}@swiftcart.local"),
    )
    db.session.add(u); db.session.commit()
    return jsonify({"message": "User Created"}), 201

@api_bp.route('/delete-user/<int:id>', methods=['DELETE'])
def delete_user(id):
    u = User.query.get(id)
    if u and u.role != 'admin':
        db.session.delete(u); db.session.commit()
        return jsonify({"message": "Deleted"})
    return jsonify({"message": "Cannot delete admin"}), 400

@api_bp.route('/settings', methods=['GET', 'POST'])
def handle_settings():
    s = ShopSettings.query.first()
    if not s: s = ShopSettings(); db.session.add(s); db.session.commit()
    
    if request.method == 'POST':
        d = request.json
        if 'shop_name' in d: s.shop_name = d['shop_name']
        if 'address' in d: s.address = d['address']
        if 'phone' in d: s.phone = d['phone']
        if 'receipt_footer' in d: s.receipt_footer = d['receipt_footer']
        db.session.commit()
        return jsonify({"message": "Saved"})
    
    return jsonify({"shop_name": s.shop_name, "address": s.address, "phone": s.phone, "receipt_footer": s.receipt_footer})

# ==========================================
# 💾 10. BACKUP 
# ==========================================
@api_bp.route('/backup', methods=['GET'])
def backup_db():
    try:
        db_path = os.path.join(current_app.instance_path, 'swiftcart_cloud.db')
        backup_dir = os.path.join(os.getcwd(), 'backups')
        if not os.path.exists(backup_dir): os.makedirs(backup_dir)
        
        fname = f"backup_{datetime.now().strftime('%Y%m%d_%H%M%S')}.db"
        shutil.copyfile(db_path, os.path.join(backup_dir, fname))
        return jsonify({"message": f"Saved to backups/{fname}"})
    except Exception as e:
        return jsonify({"message": str(e)}), 500

def send_sms_notification(to_phone, message_body, order_id=None):
    """Bhejte hain SMS notification Twilio ke zariye aur Order update karte hain"""
    try:
        client = Client(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)
        
        message = client.messages.create(
            body=message_body,
            from_=TWILIO_PHONE_NUMBER,
            to=to_phone
        )
        print(f"[SwiftCart] SMS sent: {message.sid} to {to_phone}")
        
        # Agar order_id hai toh status update karein
        if order_id:
            order = Order.query.get(order_id)
            if order:
                # Identification ke liye check karein ke kis kism ka SMS tha
                if "placed successfully" in message_body.lower():
                    order.sms_status = "Placed_Sent"
                elif "approve" in message_body.lower():
                    order.sms_status = "Approved_Sent"
                
                order.last_sms_date = datetime.utcnow()
                db.session.commit()
                
        return True
    except Exception as e:
        print(f"[SwiftCart] SMS error: {str(e)}")
        if order_id:
            order = Order.query.get(order_id)
            if order:
                order.sms_status = f"Error: {str(e)}"
                db.session.commit()
        return False

def send_whatsapp_twilio(to_phone, message_body, order_id=None):
    """Send a WhatsApp message via Twilio (sandbox or production)."""
    # Ensure phone number has leading '+'
    formatted = to_phone if to_phone.startswith('+') else '+92' + to_phone.lstrip('0')
    client = Client(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)
    try:
        message = client.messages.create(
            body=message_body,
            from_=f"whatsapp:{TWILIO_WHATSAPP_NUMBER}",
            to=f"whatsapp:{formatted}"
        )
        print(f"[SwiftCart] WhatsApp (Twilio) sent: {message.sid} to {formatted}")
        if order_id:
            order = Order.query.get(order_id)
            if order:
                order.sms_status = (order.sms_status or '') + " | WhatsApp_Sent"
                order.last_sms_date = datetime.utcnow()
                db.session.commit()
        return True
    except Exception as e:
        print(f"[SwiftCart] WhatsApp (Twilio) error: {str(e)}")
        return False

def send_whatsapp_notification(to_phone, message_body, order_id=None):
    """
    WhatsApp from the web app: Twilio only.

    pywhatkit is not imported here: it depends on pyautogui and a GUI DISPLAY,
    which headless WSGI hosts (e.g. Passenger) do not provide.
    """
    if WHATSAPP_TWILIO_ENABLED:
        return send_whatsapp_twilio(to_phone, message_body, order_id)
    print("[SwiftCart] WhatsApp skipped: WHATSAPP_TWILIO_ENABLED is False.")
    return False

def send_customer_notification(customer_phone, order_id, status):
    """Deprecating in favor of send_sms_notification but keeping for compatibility if needed"""
    print(f"[SwiftCart] Legacy notification call for {order_id}")

@api_bp.route('/update-order-status', methods=['POST'])
def update_status():
    data = request.json or {}
    order_id = data.get('order_id')
    new_status = data.get('status')

    user_id = session.get('user_id')
    user = User.query.get(user_id) if user_id else None
    if not user or user.role != 'admin':
        return jsonify({"message": "Forbidden"}), 403

    order = Order.query.get(order_id)
    if not order:
        return jsonify({"message": "Order not found"}), 404

    from app_server.utils.order_notifications import apply_order_status_update

    apply_order_status_update(order, new_status)
    db.session.commit()
    return jsonify({"message": "Status updated & SMS triggered"}), 200

# ==========================================
# 🎁 11. COUPON MANAGEMENT
# ==========================================
@api_bp.route('/coupons', methods=['GET'])
def get_coupons():
    coupons = Coupon.query.all()
    out = []
    for c in coupons:
        out.append({
            "id": c.id,
            "code": c.code,
            "discount": c.discount,
            "active": c.active
        })
    return jsonify({"coupons": out})

@api_bp.route('/coupons', methods=['POST'])
def add_coupon():
    data = request.json
    code = data.get('code', '').upper().strip()
    discount = float(data.get('discount', 0))
    
    if Coupon.query.filter_by(code=code).first():
        return jsonify({"message": "Coupon already exists!"}), 400
        
    c = Coupon(code=code, discount=discount, active=True)
    db.session.add(c)
    db.session.commit()
    return jsonify({"message": "Coupon added successfully!"}), 201

@api_bp.route('/coupons/<int:c_id>', methods=['DELETE'])
def delete_coupon(c_id):
    c = Coupon.query.get(c_id)
    if not c:
        return jsonify({"message": "Not found"}), 404
    db.session.delete(c)
    db.session.commit()
    return jsonify({"message": "Coupon deleted"}), 200

# ==========================================
# 📒 12. KHATA & LEDGER SYSTEM
# ==========================================
@api_bp.route('/khata', methods=['GET'])
def get_khatas():
    accounts = KhataAccount.query.all()
    out = []
    for a in accounts:
        out.append({
            "id": a.id,
            "customer_name": a.customer_name,
            "contact_person": a.contact_person,
            "phone": a.phone,
            "whatsapp_number": a.whatsapp_number,
            "address": a.address,
            "balance": a.balance, # If > 0, customer owes us money
            "credit_limit": a.credit_limit,
            "category": a.category
        })
    return jsonify({"khatas": out})

@api_bp.route('/khata', methods=['POST'])
def add_khata():
    data = request.json
    name = data.get('customer_name', '').strip()
    phone = data.get('phone', '').strip()
    
    if not name or not phone:
        return jsonify({"message": "Name and Phone required"}), 400
        
    existing = KhataAccount.query.filter_by(phone=phone).first()
    cp = data.get('contact_person', '').strip()
    wa = data.get('whatsapp_number', '').strip()
    addr = data.get('address', '').strip()
    limit = float(data.get('credit_limit', 0.0))
    cat = data.get('category', '').strip()
    
    if existing:
        return jsonify({"message": "Account with this phone already exists", "id": existing.id}), 400
        
    k = KhataAccount(
        customer_name=name, phone=phone, balance=0.0,
        contact_person=cp, whatsapp_number=wa, address=addr,
        credit_limit=limit, category=cat
    )
    db.session.add(k)
    db.session.commit()
    return jsonify({"message": "Khata Account created successfully", "id": k.id}), 201

@api_bp.route('/khata/<int:k_id>', methods=['GET'])
def get_khata_details(k_id):
    k = KhataAccount.query.get(k_id)
    if not k:
        return jsonify({"message": "Khata not found"}), 404
        
    txs = []
    for t in k.transactions:
        txs.append({
            "id": t.id,
            "amount": t.amount,
            "type": t.t_type,
            "description": t.description,
            "date": t.date.strftime("%Y-%m-%d %H:%M")
        })
    
    # Sort descending
    txs = sorted(txs, key=lambda x: x['id'], reverse=True)
    
    return jsonify({
        "account": {
            "id": k.id,
            "customer_name": k.customer_name,
            "phone": k.phone,
            "balance": k.balance
        },
        "transactions": txs
    }), 200

@api_bp.route('/khata/<int:k_id>/transaction', methods=['POST'])
def add_khata_transaction(k_id):
    k = KhataAccount.query.get(k_id)
    if not k:
        return jsonify({"message": "Khata not found"}), 404
        
    data = request.json
    amount = float(data.get('amount', 0))
    t_type = data.get('t_type', 'CREDIT') # 'CREDIT' = Payment received, 'DEBIT' = Udhaar taken
    desc = data.get('description', '')
    
    if amount <= 0:
        return jsonify({"message": "Amount must be greater than zero"}), 400
        
    tx = KhataTransaction(khata_id=k.id, amount=amount, t_type=t_type, description=desc)
    db.session.add(tx)
    
    # Update balance (Debit means customer takes item without paying -> debt increases)
    if t_type == 'DEBIT':
        k.balance += amount
    elif t_type == 'CREDIT':
        k.balance -= amount
        
    db.session.commit()
    return jsonify({"message": "Transaction added successfully", "new_balance": k.balance}), 201

# Find Khata by Phone (Useful for Web Store User Profile)
@api_bp.route('/khata/by-phone/<path:phone>', methods=['GET'])
def khata_by_phone(phone):
    k = KhataAccount.query.filter_by(phone=phone).first()
    if not k:
        return jsonify({"message": "Khata not found"}), 404
        
    txs = []
    for t in k.transactions:
        txs.append({
            "amount": t.amount,
            "type": t.t_type,
            "description": t.description,
            "date": t.date.strftime("%Y-%m-%d %H:%M")
        })
    return jsonify({
        "id": k.id,
        "customer_name": k.customer_name,
        "balance": k.balance,
        "transactions": list(reversed(txs)) # Latest first
    }), 200

# ==========================================
# 📊 13. MANAGEMENT MODULESS (HR, Backup, Orders)
# ==========================================

# -- EMPLOYEES --
@api_bp.route('/employees', methods=['GET', 'POST'])
def handle_employees():
    if request.method == 'POST':
        data = request.json
        emp = Employee(
            name=data.get('name', 'Unknown'),
            phone=data.get('phone', ''),
            salary=float(data.get('salary', 0)),
            hire_date=data.get('hire_date') or datetime.utcnow().strftime('%Y-%m-%d')
        )
        db.session.add(emp)
        db.session.commit()
        return jsonify({"message": "Employee Added!"}), 201
    else:
        emps = Employee.query.all()
        return jsonify([{"id": e.id, "name": e.name, "phone": e.phone, "salary": e.salary, "hire_date": e.hire_date} for e in emps])

@api_bp.route('/employee/<int:id>', methods=['GET', 'PUT', 'DELETE'])
def update_employee(id):
    emp = Employee.query.get_or_404(id)
    if request.method == 'GET':
        return jsonify({
            "id": emp.id,
            "name": emp.name,
            "phone": emp.phone,
            "salary": emp.salary,
            "hire_date": emp.hire_date
        }), 200
    if request.method == 'DELETE':
        db.session.delete(emp)
        db.session.commit()
        return jsonify({"message": "Employee deleted!"}), 200
    else:
        data = request.json
        emp.name = data.get('name', emp.name)
        emp.phone = data.get('phone', emp.phone)
        emp.salary = float(data.get('salary', emp.salary))
        emp.hire_date = data.get('hire_date', emp.hire_date)
        db.session.commit()
        return jsonify({"message": "Employee updated!"}), 200

# -- ATTENDANCE / EARNINGS --
@api_bp.route('/attendance', methods=['GET', 'POST'])
def handle_attendance():
    if request.method == 'POST':
        data = request.json
        att = Attendance(
            employee_id=int(data.get('employee_id')),
            date=data.get('date', datetime.utcnow().strftime('%Y-%m-%d')),
            status=data.get('status', 'Present'),
            earning_amount=float(data.get('earning_amount', 0)),
            description=data.get('description', '')
        )
        db.session.add(att)
        db.session.commit()
        return jsonify({"message": "Attendance record added!"}), 201
    else:
        emp_id = request.args.get('employee_id')
        date_from = request.args.get('from')
        date_to = request.args.get('to')
        q = Attendance.query
        if emp_id:
            q = q.filter_by(employee_id=int(emp_id))
        if date_from:
            q = q.filter(Attendance.date >= date_from)
        if date_to:
            q = q.filter(Attendance.date <= date_to)
        records = q.order_by(Attendance.date.desc()).all()
        total_earnings = sum(r.earning_amount for r in records)
        return jsonify({
            "records": [{
                "id": r.id,
                "employee_id": r.employee_id,
                "employee_name": r.employee.name if r.employee else "Unknown",
                "date": r.date,
                "status": r.status,
                "earning_amount": r.earning_amount,
                "description": r.description
            } for r in records],
            "total_earnings": total_earnings
        })

@api_bp.route('/attendance/<int:id>', methods=['DELETE'])
def delete_attendance(id):
    att = Attendance.query.get_or_404(id)
    db.session.delete(att)
    db.session.commit()
    return jsonify({"message": "Attendance record deleted!"}), 200

# -- BACKUP SEETTINGS --
@api_bp.route('/backup-settings', methods=['GET', 'POST'])
def handle_backup_settings():
    setting = BackupSetting.query.first()
    if not setting:
        setting = BackupSetting()
        db.session.add(setting)
        db.session.commit()

    if request.method == 'POST':
        data = request.json
        setting.enable_daily = data.get('enable_daily', setting.enable_daily)
        setting.backup_time = data.get('backup_time', setting.backup_time)
        setting.backup_dir = data.get('backup_dir', setting.backup_dir)
        setting.instant_crit = data.get('instant_crit', setting.instant_crit)
        setting.on_close = data.get('on_close', setting.on_close)
        db.session.commit()
        return jsonify({"message": "Backup settings saved!"}), 200

    return jsonify({
        "enable_daily": setting.enable_daily,
        "backup_time": setting.backup_time,
        "backup_dir": setting.backup_dir,
        "instant_crit": setting.instant_crit,
        "on_close": setting.on_close,
        "last_backup": setting.last_backup
    })

# -- PURCHASE ORDERS --
@api_bp.route('/purchase-orders', methods=['GET', 'POST'])
def handle_pos():
    if request.method == 'POST':
        data = request.json
        po = PurchaseOrder(
            vendor_name=data.get('vendor_name', ''),
            product_name=data.get('product_name', ''),
            payment_method=data.get('payment_method', 'Cash'),
            order_date=data.get('order_date') or datetime.utcnow().strftime('%Y-%m-%d'),
            total_cost=float(data.get('total_cost', 0)),
            status=data.get('status', 'Pending')
        )
        db.session.add(po)
        db.session.commit()
        return jsonify({"message": "Purchase Order Created!"}), 201
    else:
        pos = PurchaseOrder.query.order_by(PurchaseOrder.id.desc()).all()
        return jsonify([{
            "id": p.id, "vendor_name": p.vendor_name, "product_name": p.product_name,
            "payment_method": p.payment_method, "order_date": p.order_date,
            "total_cost": p.total_cost, "status": p.status, "is_received": p.is_received
        } for p in pos])

@api_bp.route('/purchase-order/<int:id>', methods=['DELETE', 'PUT'])
def update_po(id):
    po = PurchaseOrder.query.get_or_404(id)
    if request.method == 'DELETE':
        db.session.delete(po)
        db.session.commit()
        return jsonify({"message": "Purchase order deleted!"}), 200
    else:
        # For marking as received or updating status
        data = request.json
        po.status = data.get('status', po.status)
        if po.status == "Received":
            po.is_received = True
        db.session.commit()
        return jsonify({"message": "Order updated!"}), 200