import datetime
import os
import time
DATA_FILE = "hotel_data.txt"
ADMIN_PASSWORD = "admin123"
# Initial room list
rooms = {
    101: {'type': 'Single', 'AC': 'Yes', 'price': 2000, 'available': True},
    102: {'type': 'Double', 'AC': 'Yes', 'price': 3000, 'available': True},
    103: {'type': 'Single', 'AC': 'No', 'price': 1500, 'available': True},
    104: {'type': 'Double', 'AC': 'No', 'price': 2500, 'available': True},
    105: {'type': 'Suite', 'AC': 'Yes', 'price': 5000, 'available': True},
    106: {'type': 'Family', 'AC': 'Yes', 'price': 4500, 'available': True}
# Welcome banner
def banner():
    print("\n" + "=" * 50)
    print("           WELCOME TO GRAND HOTEL SYSTEM")
    print("=" * 50)
# Display rooms
def display_rooms():
    print("\nRoom Availability:")
    for rno, info in rooms.items():
      status = "Available" if info["available"] else "Booked"
    print(f"Room {rno}: Type: {info['type']} | AC: {info['AC']} | Price: ₹{info['price']} |
{status}")
# Get customer details
def get_customer_info():
  print("\nEnter Customer Details:")
  name = input("Full Name          : ")
  phone = input("Phone Number : ")
  email = input("Email Address : ")
  address = input("Residential Addr: ")
  while True:
    try:
      days = int(input("No. of Stay Days: "))
      break
    except:
      print("     Please enter a valid number of days.")
  return name, phone, email, address, days
# Write record to file
def write_customer_to_file(record):
  with open(DATA_FILE, "a") as f:
    f.write(",".join(str(x) for x in record) + "\n")
# Load customer records
def load_customer_data():
  if not os.path.exists(DATA_FILE):
    return []
  with open(DATA_FILE, "r") as f:
    return [line.strip().split(",") for line in f.readlines()]
# Save all customer records (overwrite file)
def save_customer_data(data):
 with open(DATA_FILE, "w") as f:
   for record in data:
     f.write(",".join(str(x) for x in record) + "\n")
# Admin login
def admin_login():
 pwd = input("Enter admin password: ")
 if pwd == ADMIN_PASSWORD:
   print("      Admin access granted.")
   return True
 else:
   print("      Wrong password.")
   return False
# MAIN MENU
def main_menu():
 banner()
 while True:
   print("\n      Main Menu:")
   print("1. Display Rooms")
   print("2. Book Room")
   print("3. View Customers")
   print("4. Search Customer")
   print("5. Checkout Customer")
   print("6. Admin: Update Room Prices")
   print("7. Admin: Delete All Records")
   print("8. Exit")
   ch = input("Choose option (1–8): ")
   if ch == "1":
        display_rooms()
   elif ch == "2":
        book_room()
   elif ch == "3":
        view_customers()
   elif ch == "4":
        search_customer()
   elif ch == "5":
        checkout_customer()
   elif ch == "6":
        update_room_prices()
   elif ch == "7":
        delete_all_records()
   elif ch == "8":
        print("    Thank you for using Grand Hotel System.")
        break
   else:
        print("    Invalid option. Try again.")
   input("\nPress Enter to return to menu...")
# Book a room
def book_room():
 display_rooms()
 try:
   room_no = int(input("\nEnter room number to book: "))
   if room_no not in rooms:
     print("      Room number does not exist.")
     return
   if not rooms[room_no]["available"]:
     print("      Room is already booked.")
     return
   name, phone, email, address, days = get_customer_info()
   price = rooms[room_no]["price"]
   total = price * days
   checkin = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
   checkout = "-"
   rooms[room_no]["available"] = False
   # Save to file
   record = [name, phone, email, address, room_no, price, days, total, checkin,
checkout]
   write_customer_to_file(record)
   print(f"\n       Room {room_no} booked for {days} days.")
   print(f"     Total bill: ₹{total}")
 except ValueError:
   print("      Invalid input. Try again.")
# View all customers
def view_customers():
 data = load_customer_data()
 if not data:
   print("\n     No customer records found.")
   return
 print("\n     Customer List:")
 for record in data:
   print("-" * 40)
   print(f"Name : {record[0]}")
   print(f"Phone : {record[1]}")
   print(f"Email : {record[2]}")
   print(f"Address : {record[3]}")
   print(f"Room : {record[4]} | Stay: {record[6]} days")
   print(f"Bill : ₹{record[7]}")
   print(f"Check-in: {record[8]}")
   print(f"Check-out: {record[9]}")
# Search customer
def search_customer():
 data = load_customer_data()
 name = input("        Enter customer name to search: ").strip().lower()
 found = False
 for record in data:
   if record[0].strip().lower() == name:
     print("\n✔ Customer Found:")
     print(f"Name : {record[0]}")
     print(f"Phone : {record[1]}")
     print(f"Email : {record[2]}")
     print(f"Address : {record[3]}")
     print(f"Room : {record[4]} | Stay: {record[6]} days")
     print(f"Bill : ₹{record[7]}")
     print(f"Check-in: {record[8]}")
     print(f"Check-out: {record[9]}")
     found = True
     break
 if not found:
   print("   No such customer found.")
# Customer checkout
def checkout_customer():
 data = load_customer_data()
 name = input("Enter customer name for checkout: ").strip().lower()
 updated_data = []
 found = False
 for record in data:
   if record[0].strip().lower() == name and record[9] == "-":
     record[9] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
     room_no = int(record[4])
     rooms[room_no]["available"] = True
     found = True
   updated_data.append(record)
 if found:
   save_customer_data(updated_data)
   print("   Checkout successful. Room is now available.")
 else:
   print("   No active booking found under that name.")
# Admin: Update room prices
def update_room_prices():
  if not admin_login():
    return
  display_rooms()
  try:
    rno = int(input("Enter room number to update price: "))
    if rno not in rooms:
         print("     Invalid room number.")
         return
    new_price = int(input("Enter new price: ₹"))
    rooms[rno]["price"] = new_price
    print(f"       Room {rno} price updated to ₹{new_price}")
  except:
    print("        Invalid input. Price not updated.")
# Admin: Delete all records
def delete_all_records():
  if not admin_login():
    return
   confirm = input("        Are you sure you want to delete ALL customer records? (yes/no):
").lower()
  if confirm == "yes":
    if os.path.exists(DATA_FILE):
         os.remove(DATA_FILE)
         for r in rooms:
           rooms[r]["available"] = True
         print("     All records deleted. Hotel is now empty.")
   else:
     print("No data file found.")
 else:
   print("Cancelled. No records were deleted.")
# Summary of total income
def hotel_summary():
 data = load_customer_data()
 total_income = sum(int(record[7]) for record in data)
 total_customers = len(data)
 print("\n    Hotel Summary Report:")
 print(f"Total Customers: {total_customers}")
 print(f"Total Income : ₹{total_income}")
 occupied = sum(1 for r in rooms.values() if not r["available"])
 print(f"Rooms Occupied : {occupied}")
 print(f"Rooms Available: {len(rooms) - occupied}")
# Help section
def help_section():
 print("\n    HELP MENU:")
 print("This is a Hotel Management System project.")
 print("Features:")
 print("1. Book rooms for guests")
 print("2. View and search customer records")
 print("3. Checkout process with billing")
 print("4. Admin controls for price updates and data wipe")
 print("5. Room availability tracking")
 print("6. Secure admin login")
 print("7. File-based record keeping using hotel_data.txt")
 print("\nTips:")
  print("- Use valid inputs (names, emails, room numbers)")
  print("- Admin password is required for critical actions")
  print("- System automatically tracks check-in and check-out time")
# Exit log
def exit_log():
  with open("exit_log.txt", "a") as log:
  log.write("System exited on " + datetime.datetime.now().strftime("%Y-%m-%d
%H:%M:%S") + "\n")
# Extended Main Menu (with help and summary)
def extended_menu():
  banner()
  while True:
    print("\n     MAIN MENU")
    print("1. Display Available Rooms")
    print("2. Book Room")
    print("3. View All Customers")
    print("4. Search Customer")
    print("5. Checkout Customer")
    print("6. Admin: Update Room Prices")
    print("7. Admin: Delete All Records")
    print("8. Hotel Summary Report")
    print("9. Help")
    print("10. Exit")
    choice = input("Enter choice (1–10): ")
    if choice == "1":
     display_rooms()
   elif choice == "2":
     book_room()
   elif choice == "3":
     view_customers()
   elif choice == "4":
     search_customer()
   elif choice == "5":
     checkout_customer()
   elif choice == "6":
     update_room_prices()
   elif choice == "7":
     delete_all_records()
   elif choice == "8":
     hotel_summary()
   elif choice == "9":
     help_section()
   elif choice == "10":
     exit_log()
     print("      Thank you for using the Grand Hotel System!")
     break
   else:
     print("      Invalid input, try again.")
   input("\nPress Enter to return to the menu...")
# Run the Program
if __name__ == "__main__":
 extended_menu()
def hotel_summary():
 if not os.path.exists(DATA_FILE):
   print("\n        No booking data available to show summary.")
   return
 total_bookings = 0
 total_revenue = 0
 occupied_rooms = 0
 available_rooms = 0
 room_type_count = {}
 # Count available and occupied rooms from dictionary
 for room_no, details in rooms.items():
   if details['available']:
     available_rooms += 1
   else:
     occupied_rooms += 1
   # Initialize count for room types
   room_type_count.setdefault(details['type'], 0)
 # Read booking data and accumulate stats
 with open(DATA_FILE, "r") as f:
   for line in f:
     details = line.strip().split(",")
     total_bookings += 1
     total_revenue += int(details[7]) # total price
     room_no = int(details[4])
     room_type = rooms[room_no]['type']
     room_type_count[room_type] = room_type_count.get(room_type, 0) + 1
 # Print summary
 print("\n    HOTEL SUMMARY REPORT")
 print("=" * 30)
 print(f"Total Bookings    : {total_bookings}")
 print(f"Total Revenue (Rs.) : {total_revenue}")
 print(f"Occupied Rooms       : {occupied_rooms}")
 print(f"Available Rooms    : {available_rooms}")
 print("\nBreakdown by Room Type:")
 for rtype, count in room_type_count.items():
   print(f" {rtype}: {count} bookings")
 print("=" * 30)
def help_menu():
 print("\n    HELP MENU")
 print("=" * 30)
 print("1. Display Room Availability - Shows all rooms with current status.")
 print("2. Book a Room - Allows booking available rooms by entering customer
details.")
 print("3. View All Customers - Lists all customers who have booked rooms.")
 print("4. Search Customer - Find booking details by customer name.")
 print("5. Checkout - Check out a customer and free their room.")
 print("6. Admin: Update Room Price - Change room prices (password protected).")
  print("7. Admin: Delete All Records - Remove all booking records (password
protected).")
 print("8. Hotel Summary Report - Shows booking statistics and revenue.")
 print("9. Help - Display this help menu.")
 print("10. Exit - Exit the program safely and save logs.")
 print("=" * 30)
def exit_program():
 exit_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
 with open("exit_log.txt", "a") as log_file:
   log_file.write(f"System exited on: {exit_time}\n")
 print("\nThank you for using the hotel system. Goodbye!")
 time.sleep(1) # Pause before exit
 exit()