from tkinter import *
from tkinter import ttk  # Import ttk for themed widgets
from tkcalendar import DateEntry
from datetime import datetime
from tkinter import StringVar
import sqlite3
import random
import time;
import tkinter.messagebox


class Hospital:
    def __init__(self, root):
        self.root = root
        self.root.title("Hospital Management System")
        self.root.geometry("1350x750")
        self.root.configure(background='powder blue')
        self.conn = sqlite3.connect('Myhospital.db')
        self.cursor = self.conn.cursor()


        cmbNameTablets = StringVar()
        Ref = StringVar()
        Dose = StringVar()
        NumberTables = StringVar()
        AppointmentDate = StringVar()
        IssuedDate = StringVar()
        HowtoUseMedication = StringVar()  # Added HowtoUseMedication variable
        PatientID = StringVar()
        PatientNHSNo = StringVar()
        PatientName = StringVar()
        DateOfBirth = StringVar()
        PatientAddress = StringVar()
        Prescription = StringVar()
        DoctorName = StringVar()

        # Create the patients table if it doesn't exist
        self.cursor.execute('''
            CREATE TABLE IF NOT EXISTS patients (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                reference_no TEXT,
                issued_date TEXT,
                appointment_date TEXT,
                patient_id TEXT,
                patient_name TEXT,
                date_of_birth TEXT,
                patient_address TEXT,
                nhs_number TEXT,
                name_of_tablets TEXT,
                no_of_tablets TEXT,
                dose TEXT,
                use_medication TEXT,
                doctor_name TEXT
            )
        ''')

        self.cursor.execute('''
            CREATE INDEX IF NOT EXISTS idx_appointment_date
            ON patients (appointment_date)
        ''')
        
        self.conn.commit()


        def openMedicationWindow():
            # Create a new window for medication details
            medication_window = Toplevel()
            medication_window.title("Medication Details")
            medication_window.geometry("400x300")
            
            # Medication labels and entry widgets in the new window
            lblNameTablet = Label(medication_window, font=('arial', 12, 'bold'), text="Name of Tablets:", padx=2, pady=2)
            lblNameTablet.grid(row=0, column=0, sticky=W)
            cboNameTablet = ttk.Combobox(medication_window, textvariable=cmbNameTablets, state='readonly', font=('arial', 12, 'bold'), width=23)
            cboNameTablet['values'] = ('', 'Ibuprofen', 'Co-codamol', 'Paracetamol', 'Amlodipine','Acetaminophen','Adderall','Amitriptyline','Amlodipine','Amoxicillin','Ativan')
            cboNameTablet.current(0)
            cboNameTablet.grid(row=0, column=1, sticky=W)

            lblNoOfTablets = Label(medication_window, font=('arial', 12, 'bold'), text="No. of Tablets:", padx=2 ,pady=2)
            lblNoOfTablets.grid(row=1, column=0, sticky=W)
            txtNoOfTablets = Entry(medication_window, font=('arial', 12, 'bold'), textvariable=NumberTables, width=25)
            txtNoOfTablets.grid(row=1, column=1)
            
            lblDose = Label(medication_window, font=('arial', 12, 'bold'), text="Dose:", padx=2 , pady=4)
            lblDose.grid(row=2, column=0, sticky=W)
            txtDose = Entry(medication_window, font=('arial', 12, 'bold'), textvariable=Dose, width=25)
            txtDose.grid(row=2, column=1)
            

            btnSaveMedication = Button(medication_window, text='Save Medication', font=('arial', 12, 'bold'), width=24, bd=4, command=saveMedication)
            btnSaveMedication.grid(row=4, column=1)

        def saveMedication():
            name_tablets = cmbNameTablets.get()
            no_of_tablets = NumberTables.get()
            dose = Dose.get()

            self.cursor.execute('''
                INSERT INTO patients (name_of_tablets, no_of_tablets, dose)
                VALUES (?, ?, ?)
            ''', (name_tablets, no_of_tablets, dose))


            self.conn.commit()
            tkinter.messagebox.showinfo("Success", "Medication details saved successfully!")

        #======================================function mdeclaration=============================================

        def iExit():
            iExit=tkinter.messagebox.askyesno("Hospital Managment System","Confirm if you want to exit")
            if iExit>0:
                root.destroy()
                return


        def iPrescription():

            # Get data from entry widgets

            reference_no = Ref.get()
            issued_date = IssuedDate.get()
            appointment_date = AppointmentDate.get()
            patient_id = PatientID.get()
            patient_name = PatientName.get()
            date_of_birth = DateOfBirth.get()
            patient_address = PatientAddress.get()
            nhs_number = PatientNHSNo.get()
            name_of_tablets = cmbNameTablets.get()
            no_of_tablets = NumberTables.get()
            dose = Dose.get()
            use_medication = self.txtUseMedication.get("1.0", "end-1c")  # Get content from txtUseMedication Text widget
            doctor_name = DoctorName.get()


          # Insert data into the database
            self.cursor.execute('''
                INSERT INTO patients (
                    reference_no, issued_date, appointment_date, patient_id, patient_name, date_of_birth,
                    patient_address, nhs_number, name_of_tablets, no_of_tablets, dose, use_medication, doctor_name
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ''', (
                reference_no, issued_date, appointment_date, patient_id, patient_name, date_of_birth,
                patient_address, nhs_number, name_of_tablets, no_of_tablets, dose, use_medication,
                doctor_name
            ))
            self.conn.commit()

            # Display prescription data in textPrescription
            prescription_data = (
                f"Reference No: {reference_no}\n"
                f"Issued Date: {issued_date}\n"
                f"Appointment Date: {appointment_date}\n"
                f"Patient ID: {patient_id}\n"
                f"Patient Name: {patient_name}\n"
                f"Date of Birth: {date_of_birth}\n"
                f"Patient Address: {patient_address}\n"
                f"NHS Number: {nhs_number}\n"
                f"Name of Tablets: {name_of_tablets}\n"
                f"No. of Tablets: {no_of_tablets}\n"
                f"Dose: {dose}\n"
                f"Use Medication: {use_medication}\n"
                f"Doctor Name: {doctor_name}\n\n"
            )
            self.textPrescription.insert(END, prescription_data)

            # Display use_medication in FrameDetail
            self.textFrameDetail.insert(END, f"Use Medication: {use_medication}\n")
  
            
        def iDelete():

            Ref.set("")
            HowtoUseMedication.set("")
            DoctorName.set("")
            AppointmentDate.set("")
            IssuedDate.set("")
            PatientID.set("")
            PatientNHSNo.set("")
            PatientName.set("")
            DateOfBirth.set("")
            PatientAddress.set("")
            Prescription.set("")
            self.textPrescription.delete("1.0",END)
            self.textFrameDetail.delete("1.0",END)

            return


        def iReset():

            Ref.set("")
            HowtoUseMedication.set("")
            DoctorName.set("")
            AppointmentDate.set("")
            IssuedDate.set("")
            PatientID.set("")
            PatientNHSNo.set("")
            PatientName.set("")
            DateOfBirth.set("")
            PatientAddress.set("")
            Prescription.set("")
            self.textPrescription.delete("1.0",END)
            self.textFrameDetail.delete("1.0",END)

            return


        def sort_records():
            # Fetch sorted records from the database
            sorted_records = fetch_sorted_records()

            # Clear the textFrameDetail before displaying sorted records
            self.textFrameDetail.delete("1.0", END)

            # Display the sorted records in the textFrameDetail
            for record in sorted_records:
                self.textFrameDetail.insert(END, f"{record[0]}\t{record[1]}\t{record[2]}\t{record[3]}\t"
                                                  f"{record[4]}\t{record[5]}\t{record[6]}\t{record[7]}\t"
                                                  f"{record[8]}\t{record[9]}\t{record[10]}\t{record[11]}\n")

        def fetch_sorted_records():
            # Fetch records from the database and sort them by appointment date
            self.cursor.execute('''
                SELECT reference_no, issued_date, appointment_date, patient_id, patient_name, date_of_birth,
                patient_address, nhs_number, name_of_tablets, no_of_tablets, dose, use_medication
                FROM patients
                ORDER BY appointment_date ASC''')
            records = self.cursor.fetchall()
            return records
        #===========================================frame=========================================================
        MainFrame = Frame(self.root)
        MainFrame.grid()

        TitleFrame = Frame(MainFrame, bd=20, width=1350, padx=20, relief=RIDGE)
        TitleFrame.pack(side=TOP)

        self.lblTitle = Label(TitleFrame, font=('arial', 40, 'bold'), text="Hospital Management System", padx=2)
        self.lblTitle.grid()

        FrameDetail = Frame(MainFrame, bd=20, width=1350, height=100, padx=20, relief=RIDGE)
        FrameDetail.pack(side=BOTTOM)

        ButtonFrame = Frame(MainFrame, bd=20, width=1350, height=50, padx=20, relief=RIDGE)
        ButtonFrame.pack(side=BOTTOM)

        DataFrame = Frame(MainFrame, bd=20, width=1350, height=400, padx=20, relief=RIDGE)
        DataFrame.pack(side=BOTTOM)

        DataFrameLEFT = LabelFrame(DataFrame, bd=10, width=800, height=300, padx=20, relief=RIDGE
                              , font=('arial', 12, 'bold'), text="Patient Information:",)
        DataFrameLEFT.pack(side=LEFT)

        DataFrameRIGHT = LabelFrame(DataFrame, bd=10, width=450, height=300, padx=20, relief=RIDGE
                                    , font=('arial', 12, 'bold'), text="Prescription:",)
        DataFrameRIGHT.pack(side=RIGHT)

        #=============================================DataFrameLEFT==============================================


        self.lblRef = Label(DataFrameLEFT, font=('arial', 12, 'bold'), text="Reference No:", padx=2 , pady=2)
        self.lblRef.grid(row=0, column=0)
        self.txtRef = Entry(DataFrameLEFT, font=('arial', 12, 'bold'),textvariable=Ref, width=25)
        self.txtRef.grid(row=0, column=1)


        self.lblIssuedDate = Label(DataFrameLEFT, font=('arial', 12, 'bold'), text="Issued Date:", padx=2, pady=2)
        self.lblIssuedDate.grid(row=0, column=2)
        self.txtIssuedDate = DateEntry(DataFrameLEFT, font=('arial', 12, 'bold'), textvariable=IssuedDate, width=23)
        self.txtIssuedDate.grid(row=0, column=3)


        self.lblAppointmentDate = Label(DataFrameLEFT, font=('arial', 12, 'bold'), text="AppointmentDate", padx=2, pady=2)
        self.lblAppointmentDate.grid(row=1, column=0)
        self.txtAppointmentDate = DateEntry(DataFrameLEFT, font=('arial', 12, 'bold'), textvariable=AppointmentDate, width=23)
        self.txtAppointmentDate.grid(row=1, column=1)


        self.lblPatientID = Label(DataFrameLEFT, font=('arial', 12, 'bold'), text="Patient ID:", padx=2, pady=2)
        self.lblPatientID.grid(row=1, column=2)
        self.txtPatientID = Entry(DataFrameLEFT, font=('arial', 12, 'bold'),textvariable=PatientID , width=25)
        self.txtPatientID.grid(row=1, column=3)

        
        self.lblPatientName = Label(DataFrameLEFT, font=('arial', 12, 'bold'), text="Patient Name:", padx=2, pady=2)
        self.lblPatientName.grid(row=2, column=0)
        self.txtPatientName = Entry(DataFrameLEFT, font=('arial', 12, 'bold'),textvariable=PatientName , width=25)
        self.txtPatientName.grid(row=2, column=1)


        self.lblDateOfBirth = Label(DataFrameLEFT, font=('arial', 12, 'bold'), text="Date Of Birth:", padx=2, pady=2)
        self.lblDateOfBirth.grid(row=2, column=2)
        self.txtDateOfBirth = DateEntry(DataFrameLEFT, font=('arial', 12, 'bold'), textvariable=DateOfBirth, width=23)
        self.txtDateOfBirth.grid(row=2, column=3)


        self.lblPatientAddress = Label(DataFrameLEFT, font=('arial', 12, 'bold'), text="Patient Address:", padx=2, pady=2)
        self.lblPatientAddress.grid(row=3, column=0)
        self.txtPatientAddress= Entry(DataFrameLEFT, font=('arial', 12, 'bold'),textvariable=PatientAddress , width=25)
        self.txtPatientAddress.grid(row=3, column=1)

        
        self.lblNHSNumber = Label(DataFrameLEFT, font=('arial', 12, 'bold'), text="NHS Number:", padx=2, pady=2)
        self.lblNHSNumber.grid(row=3, column=2)
        self.txtNHSNumber = Entry(DataFrameLEFT, font=('arial', 12, 'bold'),textvariable=PatientNHSNo , width=25)
        self.txtNHSNumber.grid(row=3, column=3)
        

        self.lblUseMedication = Label(DataFrameLEFT, font=('arial', 12, 'bold'), text="Use Medication:", padx=2, pady=2)
        self.lblUseMedication.grid(row=4, column=0)
        self.txtUseMedication = Text(DataFrameLEFT, font=('arial', 12), height=2, width=25)
        self.txtUseMedication.grid(row=4, column=1)



        self.lblDoctorName= Label(DataFrameLEFT, font=('arial', 12, 'bold'), text="  Doctor Name:", padx=2 ,pady=2)
        self.lblDoctorName.grid(row=4, column=2)
        self.txtDoctorName = Entry(DataFrameLEFT, font=('arial', 12, 'bold'),textvariable=DoctorName , width=25)
        self.txtDoctorName.grid(row=4, column=3)



        
        #====================================DataFrameRIGHT=====================================================================
        
        self.textPrescription=Text(DataFrameRIGHT, font=('arial', 12, 'bold'),width=43, height=14, padx=2, pady=2)
        self.textPrescription.grid(row=0, column=0)



        #=====================================ButtonFrame==================================================================

        self.btnPrescription=Button(ButtonFrame,text='Prescription', font=('arial', 12, 'bold'),width=24 ,bd=4
                                    ,command=iPrescription)
        self.btnPrescription.grid(row=0, column=0)

        self.btnMedicationDetails=Button(ButtonFrame,text='Medication Details', font=('arial', 12, 'bold'),width=24 ,bd=4,
                                    command=openMedicationWindow)
        self.btnMedicationDetails.grid(row=0, column=1)


        self.btnDelete=Button(ButtonFrame,text='Delete', font=('arial', 12, 'bold'),width=24 ,bd=4
                              ,command=iDelete)
        self.btnDelete.grid(row=0, column=2)

        self.btnReset=Button(ButtonFrame,text='Reset', font=('arial', 12, 'bold'),width=24 ,bd=4
                             ,command=iReset)
        self.btnReset.grid(row=0, column=3)
        
        self.btnExit=Button(ButtonFrame,text='Exit', font=('arial', 12, 'bold'),width=24 ,bd=4
                            ,command=iExit)
        self.btnExit.grid(row=0, column=4)


        
        #=====================================FrameDetail======================================================================

        self.lblLabel = Label(FrameDetail, font=('arial', 10, 'bold'), pady=8,
                    text="Type of medical condition/Does the patient use medications?")
        self.lblLabel.grid(row=0, column=0)

        
        self.textFrameDetail=Text(FrameDetail,font=('arial', 12, 'bold'),width=141, height=4, padx=2, pady=4)
        self.textFrameDetail.grid(row=1, column=0)




        




if __name__ == '__main__':
    root = Tk()
    application = Hospital(root)
    root.mainloop()
