from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from db.db import get_db_connection
from config.auth import role_required
import mysql.connector
from datetime import datetime

payment_methods_bp = Blueprint('payment_methods', __name__)

# ================================
# Create a Payment Method
# ================================
@payment_methods_bp.route('/create_payment_method', methods=['POST'])
@jwt_required()
def create_payment_method():
    data = request.get_json()
    method_name = data.get('method_name')

    if not method_name:
        return jsonify({"error": "Payment method name is required"}), 400

    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        sql = "INSERT INTO payment_methods (method_name, created_at) VALUES (%s, %s)"
        cursor.execute(sql, (method_name, datetime.utcnow()))
        conn.commit()
        method_id = cursor.lastrowid
        cursor.close()
        conn.close()
        return jsonify({"message": "Payment method created", "id": method_id}), 201
    except mysql.connector.IntegrityError:
        return jsonify({"error": "Payment method already exists"}), 400
    except Exception as e:
        return jsonify({"error": str(e)}), 500

# @payment_methods_bp.route('/payment_methods', methods=['GET'])
# @jwt_required()
# @role_required('admin')
# def get_payment_methods():
#     try:
#         conn = get_db_connection()
#         cursor = conn.cursor(dictionary=True)
        
#         # ✅ FIXED: Use correct column name
#         cursor.execute("""
#             SELECT id, method_name as name, is_active, created_at 
#             FROM payment_methods 
#             WHERE is_active = 1
#             ORDER BY created_at DESC
#         """)
        
#         methods = cursor.fetchall()
#         cursor.close()
#         conn.close()
        
#         print(f"✅ Found {len(methods)} payment methods")
#         return jsonify(methods), 200
        
#     except Exception as e:
#         print(f"❌ Error: {e}")
#         return jsonify({"error": str(e)}), 500
   
   
@payment_methods_bp.route('/payment_methods', methods=['GET'])
@jwt_required()
def get_payment_methods():
    try:
        conn = get_db_connection()
        cursor = conn.cursor(dictionary=True)
        
        cursor.execute("""
            SELECT id, method_name as name, is_active, created_at 
            FROM payment_methods 
            WHERE is_active = 1
            ORDER BY method_name ASC
        """)
        
        methods = cursor.fetchall()
        cursor.close()
        conn.close()
        
        print(f"✅ Returning {len(methods)} payment methods")
        return jsonify(methods), 200
        
    except Exception as e:
        print(f"❌ Error: {e}")
        return jsonify({"error": str(e)}), 500   
    
    
# ================================
# Edit / Update Payment Method
# ================================
@payment_methods_bp.route('/update_payment_method/<int:method_id>', methods=['PUT'])
@jwt_required()
@role_required('admin')
def update_payment_method(method_id):
    data = request.get_json()
    method_name = data.get('method_name')
    is_active = data.get('is_active')

    if method_name is None and is_active is None:
        return jsonify({"error": "Nothing to update"}), 400

    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        updates = []
        params = []

        if method_name:
            updates.append("method_name = %s")
            params.append(method_name)
        if is_active is not None:
            updates.append("is_active = %s")
            params.append(is_active)

        params.append(method_id)
        sql = f"UPDATE payment_methods SET {', '.join(updates)} WHERE id = %s"
        cursor.execute(sql, tuple(params))
        conn.commit()
        cursor.close()
        conn.close()
        return jsonify({"message": "Payment method updated"}), 200
    except mysql.connector.IntegrityError:
        return jsonify({"error": "Payment method name already exists"}), 400
    except Exception as e:
        return jsonify({"error": str(e)}), 500

# ================================
# Delete Payment Method
# ================================
@payment_methods_bp.route('/delete_payment_method/<int:method_id>', methods=['DELETE'])
@jwt_required()
@role_required('admin')
def delete_payment_method(method_id):
    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        cursor.execute("DELETE FROM payment_methods WHERE id = %s", (method_id,))
        conn.commit()
        cursor.close()
        conn.close()
        return jsonify({"message": "Payment method deleted"}), 200
    except Exception as e:
        return jsonify({"error": str(e)}), 500
