from flask import Flask, render_template, request, redirect, url_for, flash
from flask_mysqldb import MySQL
import MySQLdb.cursors
import re
app = Flask(__name__)

app.secret_key = 'your secret key'

app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'root'
app.config['MYSQL_DB'] = 'login'
mysql = MySQL(app)






@app.route('/')
def Index():
    conn = mysql.connection
    cur = conn.cursor(MySQLdb.cursors.DictCursor)

    cur.execute('SELECT * FROM employee')
    data = cur.fetchall()

    cur.close()
    return render_template('index.html', employee=data)


@app.route('/add_contact', methods=['POST'])
def add_employee():
    conn = mysql.connection
    cur = conn.cursor(MySQLdb.cursors.DictCursor)
    if request.method == 'POST':
        id= request.form['id']
        fullname = request.form['fullname']
        phone = request.form['phone']
        email = request.form['email']
        cur.execute("INSERT INTO employee (id,fullname, email, phone) VALUES (%s,%s,%s,%s)", (id,fullname, email, phone))
        conn.commit()
        flash('Employee Added successfully')
        return redirect(url_for('Index'))


@app.route('/edit/<id>', methods=['POST', 'GET'])
def get_employee(id):
    conn = mysql.connection
    cur = conn.cursor(MySQLdb.cursors.DictCursor)

    cur.execute('SELECT * FROM employee WHERE id = %s', (id))
    data = cur.fetchall()
    cur.close()
    print(data[0])
    return render_template('edit.html', employee=data[0])


@app.route('/update/<id>', methods=['POST'])
def update_employee(id):
    if request.method == 'POST':
        fullname = request.form['fullname']
        phone = request.form['phone']
        email = request.form['email']
        conn = mysql.connection
        cur = conn.cursor(MySQLdb.cursors.DictCursor)
        cur.execute("""
            UPDATE employee
            SET name = %s,
                email = %s,
                phone = %s
            WHERE id = %s
        """, (fullname, email, phone, id))
        flash('Employee Updated Successfully')
        conn.commit()
        return redirect(url_for('Index'))


@app.route('/delete/<string:id>', methods=['POST', 'GET'])
def delete_employee(id):
    conn = mysql.connection
    cur = conn.cursor(MySQLdb.cursors.DictCursor)

    cur.execute('DELETE FROM employee WHERE id = {0}'.format(id))
    conn.commit()
    flash('Employee Removed Successfully')
    return redirect(url_for('Index'))


# starting the app

if __name__ == "__main__":
    app.run( debug=True)
