import streamlit as st
import sqlite3
import pandas as pd
import io
from PIL import Image
from pdf2image import convert_from_bytes
# --- 1. PREMIUM RESPONSIVE CONFIGURATION ---
st.set_page_config(
page_title="Difa E Ahlesunnat Smart System",
layout="centered",
initial_sidebar_state="collapsed"
)
DB_NAME = 'masjid_difa_system.db'
# --- 2. HIGH-SPEED ASYNCHRONOUS DATABASE ENGINE (WAL MODE) ---
def init_db():
conn = sqlite3.connect(DB_NAME, timeout=30.0)
try:
c = conn.cursor()
c.execute("PRAGMA journal_mode=WAL;")
c.execute("PRAGMA synchronous=NORMAL;")
c.execute("PRAGMA cache_size=-64000;") # 64MB Cache Allocation
# Masjid Core Architecture
c.execute('''CREATE TABLE IF NOT EXISTS masjids
(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, imam_pass TEXT,
fajr TEXT, zuhr TEXT, asr TEXT, maghrib TEXT, isha TEXT, jumma TEXT,
sehri TEXT, tuloo TEXT, guroob TEXT, zanaza TEXT, yearly TEXT,
extra TEXT, pink_box TEXT, top_img BLOB, bottom_img BLOB)''')
# Difa E Aqaid Infrastructure
c.execute('''CREATE TABLE IF NOT EXISTS global_aqaid
(id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, front_img BLOB)''')
c.execute('''CREATE TABLE IF NOT EXISTS aqaid_references
(id INTEGER PRIMARY KEY AUTOINCREMENT, topic_id INTEGER, manual_text TEXT,
ref_book TEXT, page_no TEXT, ref_img BLOB,
FOREIGN KEY(topic_id) REFERENCES global_aqaid(id) ON DELETE CASCADE)''')
# Quran Directory Structure
c.execute('''CREATE TABLE IF NOT EXISTS quran_folders
(id INTEGER PRIMARY KEY AUTOINCREMENT, folder_name TEXT, cover_img BLOB)''')
c.execute('''CREATE TABLE IF NOT EXISTS quran_sub_folders
(id INTEGER PRIMARY KEY AUTOINCREMENT, main_folder_id INTEGER, sub_folder_name TEXT,
FOREIGN KEY(main_folder_id) REFERENCES quran_folders(id) ON DELETE CASCADE)''')
c.execute('''CREATE TABLE IF NOT EXISTS quran_pages
(id INTEGER PRIMARY KEY AUTOINCREMENT, main_folder_id INTEGER, sub_folder_id INTEGER,
surah_verse TEXT, manually_text TEXT, quran_img BLOB, pdf_file BLOB, pdf_name TEXT,
voice_audio BLOB, voice_name TEXT,
FOREIGN KEY(main_folder_id) REFERENCES quran_folders(id) ON DELETE CASCADE,
FOREIGN KEY(sub_folder_id) REFERENCES quran_sub_folders(id) ON DELETE CASCADE)''')
# Fiqh Wa Masail Framework
# Notification System
c.execute('''CREATE TABLE IF NOT EXISTS fiqh_folders
(id INTEGER PRIMARY KEY AUTOINCREMENT,
category_name TEXT,
cover_img BLOB)''')
c.execute('''CREATE TABLE IF NOT EXISTS fiqh_masail
(id INTEGER PRIMARY KEY AUTOINCREMENT,
fiqh_folder_id INTEGER,
topic_title TEXT,
manual_text TEXT,
ref_details TEXT,
masail_img BLOB,
pdf_file BLOB,
pdf_name TEXT,
FOREIGN KEY(fiqh_folder_id) REFERENCES fiqh_folders(id) ON DELETE CASCADE)''')
# Fiqh Wa Masail Framework
c.execute('''CREATE TABLE IF NOT EXISTS fiqh_masail
(id INTEGER PRIMARY KEY AUTOINCREMENT,
fiqh_folder_id INTEGER,
topic_title TEXT,
manual_text TEXT,
ref_details TEXT,
masail_img BLOB,
pdf_file BLOB,
pdf_name TEXT,
FOREIGN KEY(fiqh_folder_id) REFERENCES fiqh_folders(id) ON DELETE CASCADE)''')
c.execute('''
CREATE TABLE IF NOT EXISTS notifications (
id INTEGER PRIMARY KEY AUTOINCREMENT,
masjid_id INTEGER,
masjid_name TEXT,
field_name TEXT,
old_value TEXT,
new_value TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
is_read INTEGER DEFAULT 0
)
''')
conn.commit()
conn.commit()
finally:
conn.close()
init_db()
def run_query(query, params=(), is_select=True):
conn = sqlite3.connect(DB_NAME, timeout=45.0)
conn.execute("PRAGMA journal_mode=WAL;")
try:
if is_select:
return pd.read_sql_query(query, conn, params=params)
else:
with conn:
cursor = conn.cursor()
cursor.execute(query, params)
return cursor.lastrowid
except sqlite3.OperationalError as e:
st.error(f"Engine Concurrency Busy: {e}")
return None
finally:
conn.close()
finally:
conn.close()
def create_notification(masjid_id, masjid_name, field_name, old_value, new_value):
run_query(
"""
INSERT INTO notifications
(
masjid_id,
masjid_name,
field_name,
old_value,
new_value
)
VALUES (?, ?, ?, ?, ?)
""",
(
masjid_id,
masjid_name,
field_name,
str(old_value),
str(new_value)
),
is_select=False
)
# --- 3. SESSION STATE ENGINE ---
states = ['role', 'logged_in_masjid', 'selected_aqaid_id', 'selected_quran_folder_id', 'selected_quran_sub_id', 'selected_fiqh_folder_id']
for state in states:
if state not in st.session_state:
st.session_state[state] = 'namzi' if state == 'role' else None
# --- 4. FLUID ULTRA-RESPONSIVE INTERFACE UI DESIGN ---
st.markdown("""
""", unsafe_allow_html=True)
st.markdown("
PRO ARCHITECTURE ENGINE BY UMAID RANGREZ
", unsafe_allow_html=True)
st.markdown("🕌 DIFA E AHLESUNNAT SMART SYSTEM
", unsafe_allow_html=True)
# --- 5. SIDEBAR AUTHENTICATION MODALITY ---
st.sidebar.markdown("### 🧭 ACCESS CONTROL CENTRE")
if st.session_state['role'] == 'namzi':
menu = st.sidebar.radio("Navigate Screen View:", ["📋 VIEW PUBLIC DASHBOARD", "⚙️ SYSTEM OWNER PORTAL", "🕌 MOSQUE IMAM LOG"])
if menu == "⚙️ SYSTEM OWNER PORTAL":
st.sidebar.markdown("---")
user = st.sidebar.text_input("System Owner UID", help="Enter master registration phone identifier")
pwd = st.sidebar.text_input("Master System Password", type="password")
if st.sidebar.button("VERIFY SYSTEM SECURITY", use_container_width=True):
if user == "9792188408" and pwd == "Umaid512008":
st.session_state['role'] = 'owner'
st.rerun()
else: st.sidebar.error("Master Security Tokens Failed.")
elif menu == "🕌 MOSQUE IMAM LOG":
st.sidebar.markdown("---")
all_m = run_query("SELECT id, name FROM masjids")
if all_m is not None and not all_m.empty:
m_id = st.sidebar.selectbox("Choose Target Mosque:", all_m['id'].tolist(), format_func=lambda x: all_m[all_m['id']==x]['name'].values[0] if not all_m[all_m['id']==x].empty else "Unknown Mosque")
im_pwd = st.sidebar.text_input("Assigned Mosque Security Pin", type="password")
if st.sidebar.button("INITIALIZE IMAM SESSION", use_container_width=True):
check_imam = run_query("SELECT id FROM masjids WHERE id=? AND imam_pass=?", (m_id, im_pwd))
if check_imam is not None and not check_imam.empty:
st.session_state['role'] = 'imam'
st.session_state['logged_in_masjid'] = m_id
st.rerun()
else: st.sidebar.error("Authorized Pin Disallowed.")
else: st.sidebar.warning("No Registered Mosques found.")
else:
st.sidebar.markdown(f"Current Mode: {st.session_state['role'].upper()}
", unsafe_allow_html=True)
if st.sidebar.button("🔴 CLEAR SESSION & LOGOUT", type="primary", use_container_width=True):
st.session_state['role'] = 'namzi'
st.session_state['logged_in_masjid'] = None
st.session_state['selected_aqaid_id'] = None
st.session_state['selected_quran_folder_id'] = None
st.session_state['selected_quran_sub_id'] = None
st.session_state['selected_fiqh_folder_id'] = None
st.rerun()
# --- 6. CORE LIVE SHARED ENGINE TABS ---
all_masjids = run_query("SELECT id, name FROM masjids")
tab_board, tab_quran, tab_aqaid, tab_fiqh = st.tabs(["📊 Time Management Board", "📖 Digital Quran Shareef", "🛡️ Difa E Global Aqaid", "📝 Fiqh Wa Masail Desk"])
# ==========================================
# --- TAB 1: MOSQUE TIME BOARD MANAGEMENT ---
# ==========================================
with tab_board:
if all_masjids is not None and not all_masjids.empty:
selected_id = st.selectbox("Choose Mosque Dashboard View:", all_masjids['id'].tolist(), format_func=lambda x: all_masjids[all_masjids['id']==x]['name'].values[0] if not all_masjids[all_masjids['id']==x].empty else "Unknown Mosque")
board_data = run_query("SELECT * FROM masjids WHERE id=?", (selected_id,))
if board_data is not None and not board_data.empty:
data = board_data.iloc[0]
# Safe Rendering Header Scan Image (Top Photo)
if data.get('top_img'):
st.image(data['top_img'], use_column_width=True)
st.markdown("", unsafe_allow_html=True)
st.markdown("
ببِسْمِ اللهِ الرَّحْمَنِ الرَّحِيمِ
", unsafe_allow_html=True)
st.markdown("
اِنَّا اَعْطَيْنَكَ الْكَوْثَرَ فَصَلِّ لِرَبِّكَ وَانْحَرُ إِنَّ شَانِئَكَ هُوَ الْابْتَرُ
", unsafe_allow_html=True)
st.markdown("
", unsafe_allow_html=True)
st.markdown(f"
{data.get('name') or 'Unnamed Mosque'}
", unsafe_allow_html=True)
st.markdown("
⏰ वक़्त-ए-नमाज़ समय सारणी
", unsafe_allow_html=True)
namaz_structure = [
{"field": "fajr", "labels": "Fajr / फज्र / فجر"}, {"field": "zuhr", "labels": "Zuhr / ज़ुहर / ظهر"},
{"field": "asr", "labels": "Asr / असर / عصر"}, {"field": "maghrib", "labels": "Maghrib / मग़रिब / مغرب"},
{"field": "isha", "labels": "Isha / ईशा / عشاء"}, {"field": "jumma", "labels": "Jumma / जुमा / جمعة"},
{"field": "tuloo", "labels": "Sunrise / तुलू / طلوع"}, {"field": "guroob", "labels": "Iftar / गु़रूब / غروب"},
{"field": "sehri", "labels": "Sehri End / सहरी / سحري"}
]
for item in namaz_structure:
st.markdown(f"
{data.get(item['field']) or '00:00'}
{item['labels']}
", unsafe_allow_html=True)
st.markdown("
", unsafe_allow_html=True)
# Safe Notice Arrays Box System with Defaults
st.markdown(f"🚨 जनाज़ा सूचना (Zanaza Alert)
{data.get('zanaza') or 'कोई वर्तमान घोषणा नहीं है।'}
", unsafe_allow_html=True)
st.markdown(f"🕋 ईद / सालाना जलसा अपडेट (Yearly Notice)
{data.get('yearly') or 'सालाना प्रोग्राम विवरण उपलब्ध नहीं है।'}
", unsafe_allow_html=True)
st.markdown(f"📢 विशेष एलान / ओनर संदेश
{data.get('extra') or 'सामान्य निर्देश उपलब्ध नहीं है।'}
", unsafe_allow_html=True)
st.markdown(f"💗 आवश्यक घोषणाएं (Pink Boxboard)
{data.get('pink_box') or 'कोई आवश्यक निर्देश नहीं है।'}
", unsafe_allow_html=True)
# Safe Rendering Footer Scan Image (Bottom Photo)
if data.get('bottom_img'):
st.image(data['bottom_img'], use_column_width=True)
# --- MOSQUE MODIFICATION CONTROLS ---
if st.session_state['role'] == 'owner':
st.markdown("", unsafe_allow_html=True)
with st.expander("Open Master Mosque Editor (Full Image + Text Control)"):
with st.form(f"m_owner_edit_form_{selected_id}"):
st.subheader("🖼️ Update Panel Photos")
top_f = st.file_uploader("Replace Top (Header) Image File Scan", type=['jpg', 'png', 'jpeg'])
bot_f = st.file_uploader("Replace Bottom (Footer) Image File Scan", type=['jpg', 'png', 'jpeg'])
st.subheader("⏰ Update Namaz Timings & Notices")
m_inputs = {}
col_a, col_b = st.columns(2)
for count, item in enumerate(namaz_structure):
with col_a if count % 2 == 0 else col_b:
m_inputs[item['field']] = st.text_input(f"Edit {item['labels']}", value=data.get(item['field']) or "00:00")
up_z = st.text_area("Update Zanaza Box Board", value=data.get('zanaza') or "")
up_y = st.text_area("Update Eid/Yearly Box Board", value=data.get('yearly') or "")
up_e = st.text_area("Update Owner Message Box Board", value=data.get('extra') or "")
up_p = st.text_area("Update Pink Notice Box Board", value=data.get('pink_box') or "")
if st.form_submit_button("💾 REFRESH AND SYNC LIVE DISPLAY BOARD (OWNER)", type="primary", use_container_width=True):
run_query("""UPDATE masjids SET fajr=?, zuhr=?, asr=?, maghrib=?, isha=?, jumma=?, tuloo=?, guroob=?, sehri=?,
zanaza=?, yearly=?, extra=?, pink_box=?, top_img=?, bottom_img=? WHERE id=?""",
(m_inputs['fajr'], m_inputs['zuhr'], m_inputs['asr'], m_inputs['maghrib'], m_inputs['isha'], m_inputs['jumma'], m_inputs['tuloo'], m_inputs['guroob'], m_inputs['sehri'],
up_z, up_y, up_e, up_p, top_f.getvalue() if top_f else data.get('top_img'), bot_f.getvalue() if bot_f else data.get('bottom_img'), selected_id), is_select=False)
st.success("Mosque Dashboard Modified and Synced on Owner Security Matrix!")
st.rerun()
elif st.session_state['role'] == 'imam' and st.session_state['logged_in_masjid'] == selected_id:
st.markdown("", unsafe_allow_html=True)
with st.expander("Open Imam Editor Panel (Image Updates Restricted)"):
with st.form(f"m_imam_edit_form_{selected_id}"):
m_inputs = {}
col_a, col_b = st.columns(2)
for count, item in enumerate(namaz_structure):
with col_a if count % 2 == 0 else col_b:
m_inputs[item['field']] = st.text_input(f"Modify {item['labels']}", value=data.get(item['field']) or "00:00")
up_z = st.text_area("Modify Zanaza Box Board", value=data.get('zanaza') or "")
up_y = st.text_area("Modify Eid/Yearly Box Board", value=data.get('yearly') or "")
up_e = st.text_area("Modify Owner Message Box Board", value=data.get('extra') or "")
up_p = st.text_area("Modify Pink Notice Box Board", value=data.get('pink_box') or "")
if st.form_submit_button("💾 UPDATE LIVE TIMETABLE (IMAM)", use_container_width=True):
run_query(...)
create_notification(
selected_id,
data.get('name'),
"Imam Update",
"Old Data",
"New Data Updated"
)
st.success("Timetable logs updated live on board layout!")
st.rerun()
else:
st.info("Selected mosque data could not be retrieved.")
else:
st.info("No authorized mosques registered inside database yet.")
# Master Global Control Block
if st.session_state['role'] == 'owner':
st.markdown("", unsafe_allow_html=True)
with st.expander("➕ Register Brand New Mosque Unit"):
with st.form("master_mosque_reg_flow", clear_on_submit=True):
m_new_name = st.text_input("New Mosque Display Title Name")
m_new_pass = st.text_input("Set Custom Access Pin for Imam Log")
if st.form_submit_button("Deploy Mosque Registry Entry", type="primary") and m_new_name and m_new_pass:
run_query("INSERT INTO masjids (name, imam_pass, fajr, zuhr, asr, maghrib, isha, jumma, sehri, tuloo, guroob, zanaza, yearly, extra, pink_box) VALUES (?, ?, '05:00', '01:15', '05:15', '06:45', '08:30', '01:00', '04:15', '05:30', '06:50', '', '', '', '')", (m_new_name, m_new_pass), is_select=False)
st.success("New structural module deployed on system data layer.")
st.rerun()
if all_masjids is not None and not all_masjids.empty:
with st.expander("✏️ Correct Metadata Identity or Wipe Mosque Frame"):
target_m_delete = st.selectbox("Select Target Registry Object to Manage:", all_masjids['id'].tolist(), format_func=lambda x: all_masjids[all_masjids['id']==x]['name'].values[0] if not all_masjids[all_masjids['id']==x].empty else "Unknown", key="m_wipe_select_v4")
m_res = run_query("SELECT name, imam_pass FROM masjids WHERE id=?", (target_m_delete,))
if m_res is not None and not m_res.empty:
fetch_cur_data = m_res.iloc[0]
with st.form("mosque_structural_alteration_form"):
corr_m_name = st.text_input("Alter/Correct Mosque Official Title Name:", value=fetch_cur_data.get('name') or "")
corr_m_pass = st.text_input("Alter/Modify System Assigned Imam Login Password:", value=fetch_cur_data.get('imam_pass') or "")
col_u, col_d = st.columns(2)
with col_u:
if st.form_submit_button("💾 OVERWRITE METADATA IDENTITY", use_container_width=True):
run_query("UPDATE masjids SET name=?, imam_pass=? WHERE id=?", (corr_m_name, corr_m_pass, target_m_delete), is_select=False)
st.success("Data parameters modified successfully.")
st.rerun()
with col_d:
if st.form_submit_button("🗑️ PURGE MOSQUE DATA MODULE", type="primary", use_container_width=True):
run_query("DELETE FROM masjids WHERE id=?", (target_m_delete,), is_select=False)
st.success("Target mosque profile records entirely purged.")
st.rerun()
# ==========================================
# --- TAB 2: QURAN SHAREEF INTEGRATION ENGINE ---
# ==========================================
with tab_quran:
st.markdown("### 📖 High-Fidelity Audio Quran & Digital Column System")
q_folders = run_query("SELECT * FROM quran_folders")
def display_unified_quran_block(df_records):
for p_idx, p_row in df_records.iterrows():
st.markdown(f"Item Registry ID: {p_row['id']}📖 {p_row.get('surah_verse') or 'Untitled'}
{p_row.get('manually_text') or ''}
", unsafe_allow_html=True)
if p_row.get('quran_img'):
st.image(p_row['quran_img'], caption=f"Visual Scan View", use_column_width=True)
if p_row.get('pdf_file'):
try:
pdf_bytes_stream = p_row['pdf_file']
st.markdown(f"", unsafe_allow_html=True)
with st.spinner("Processing PDF Matrix Pages to Native Viewers..."):
converted_images = convert_from_bytes(pdf_bytes_stream)
for i, p_img in enumerate(converted_images):
buffer_io = io.BytesIO()
p_img.save(buffer_io, format='PNG')
st.image(buffer_io.getvalue(), caption=f"Rendered Page View {i+1} / {len(converted_images)}", use_column_width=True)
except Exception as ex:
st.error(f"Integrated engine reader was unable to parse PDF content payload: {ex}")
if p_row.get('voice_audio'):
st.audio(p_row['voice_audio'], format="audio/mp3")
st.caption(f"🎵 Audio Stream Identifier: {p_row.get('voice_name') or 'Voice Clip'}")
st.markdown("
", unsafe_allow_html=True)
# Clean non-existent safe routing
if st.session_state['selected_quran_sub_id'] is not None:
sub_id = st.session_state['selected_quran_sub_id']
if st.button("⬅️ Return Back to Subcategories Navigation Frame", key="nav_back_qsub_v4"):
st.session_state['selected_quran_sub_id'] = None
st.rerun()
q_pages_df = run_query("SELECT * FROM quran_pages WHERE sub_folder_id=? ORDER BY id ASC", (sub_id,))
if q_pages_df is not None and not q_pages_df.empty:
display_unified_quran_block(q_pages_df)
else: st.info("No content data entries are populated in this subcategory frame block.")
elif st.session_state['selected_quran_folder_id'] is not None:
q_fid = st.session_state['selected_quran_folder_id']
if st.button("⬅️ Return Back to Main Categories Panel Grid", key="nav_back_qfold_v4"):
st.session_state['selected_quran_folder_id'] = None
st.session_state['selected_quran_sub_id'] = None
st.rerun()
if q_folders is not None and not q_folders.empty and q_fid in q_folders['id'].values:
cur_folder_meta = q_folders[q_folders['id'] == q_fid].iloc[0]
st.markdown(f"#### 📁 Structural Column Location: {cur_folder_meta.get('folder_name') or 'Main Category'}")
unbound_pages = run_query("SELECT * FROM quran_pages WHERE main_folder_id=? AND (sub_folder_id IS NULL OR sub_folder_id = 0) ORDER BY id ASC", (q_fid,))
if unbound_pages is not None and not unbound_pages.empty:
st.markdown("`📝 Uncategorized Main Column Page Rows:`")
display_unified_quran_block(unbound_pages)
st.markdown("---")
st.markdown("`📂 Sub-Category Nodes Under Selection Folder:`")
sub_folders_df = run_query("SELECT * FROM quran_sub_folders WHERE main_folder_id=?", (q_fid,))
if sub_folders_df is not None and not sub_folders_df.empty:
for idx, s_row in sub_folders_df.iterrows():
if st.button(f"➔ View Subcategory Column: {s_row.get('sub_folder_name') or 'Unnamed'}", key=f"q_sub_node_click_{s_row['id']}", use_container_width=True):
st.session_state['selected_quran_sub_id'] = int(s_row['id'])
st.rerun()
else:
if unbound_pages is None or unbound_pages.empty:
st.info("No subordinate data clusters allocated here yet.")
else:
st.session_state['selected_quran_folder_id'] = None
st.rerun()
else:
if q_folders is not None and not q_folders.empty:
q_columns_layout = st.columns(2)
for idx, row in q_folders.iterrows():
with q_columns_layout[idx % 2]:
st.markdown(f"📖 {row.get('folder_name') or 'Untitled'}
", unsafe_allow_html=True)
if row.get('cover_img'): st.image(row['cover_img'], use_column_width=True)
if st.button(f"Launch Base Column: {row.get('folder_name') or 'View'}", key=f"init_q_grid_btn_{row['id']}", use_container_width=True):
st.session_state['selected_quran_folder_id'] = int(row['id'])
st.rerun()
st.markdown("
", unsafe_allow_html=True)
else: st.info("Quran directory index structural modules are empty.")
# --- ADVANCED STRUCTURAL DATA MANIPULATION TERMINAL ---
if st.session_state['role'] == 'owner':
st.markdown("", unsafe_allow_html=True)
q_action_node = st.radio("Choose Modification Node Target Type:", [
"1. Instantiate Main Column Category (New Parent Folder)",
"2. Instantiate Structural Sub-Category Node (New Sub-Folder)",
"3. Execute Page Upload Pipeline (Bulk Scans, Single PDF, Voice Tracks)",
"4. Correct Data Matrix Entry / Replace Media Attachments",
"5. Wipe Structural Category Nodes or Delete Row Entries"
], key="owner_quran_radio_node_v4")
if q_action_node == "1. Instantiate Main Column Category (New Parent Folder)":
with st.form("q_main_instantiate_form", clear_on_submit=True):
n_f_title = st.text_input("New Main Category Title Name")
n_f_cover = st.file_uploader("Set Identity Category Thumbnail Scan Image", type=['jpg','png','jpeg'])
if st.form_submit_button("Deploy Main Structural Category Block") and n_f_title:
run_query("INSERT INTO quran_folders (folder_name, cover_img) VALUES (?, ?)", (n_f_title, n_f_cover.getvalue() if n_f_cover else None), is_select=False)
st.success("Successfully deployed new category parent layer.")
st.rerun()
elif q_action_node == "2. Instantiate Structural Sub-Category Node (New Sub-Folder)" and q_folders is not None and not q_folders.empty:
target_p_fold = st.selectbox("Assign Under Target Parent Category:", q_folders['id'].tolist(), format_func=lambda x: q_folders[q_folders['id']==x]['folder_name'].values[0] if not q_folders[q_folders['id']==x].empty else "Unknown")
with st.form("q_sub_instantiate_form", clear_on_submit=True):
n_s_title = st.text_input("Sub-Category Module Display Name")
if st.form_submit_button("Deploy Node Connection Matrix") and n_s_title:
run_query("INSERT INTO quran_sub_folders (main_folder_id, sub_folder_name) VALUES (?, ?)", (target_p_fold, n_s_title), is_select=False)
st.success("Structural branch configured inside system layer data tree.")
st.rerun()
elif q_action_node == "3. Execute Page Upload Pipeline (Bulk Scans, Single PDF, Voice Tracks)" and q_folders is not None and not q_folders.empty:
p_sel_id = st.selectbox("Assign Entry To Category Folder Location:", q_folders['id'].tolist(), format_func=lambda x: q_folders[q_folders['id']==x]['folder_name'].values[0] if not q_folders[q_folders['id']==x].empty else "Unknown", key="bulk_upload_p_sel_v4")
s_pool = run_query("SELECT id, sub_folder_name FROM quran_sub_folders WHERE main_folder_id=?", (p_sel_id,))
s_opts = [(0, "🚫 Unbound Content Page (Direct Parent Attachment Block Only)")]
if s_pool is not None and not s_pool.empty:
for s_i, s_r in s_pool.iterrows(): s_opts.append((int(s_r['id']), f"📂 Branch Subcategory Node Target: {s_r.get('sub_folder_name') or 'Unnamed'}"))
s_sel_id = st.selectbox("Assign Entry Under Structural Sub-Branch Node:", [o[0] for o in s_opts], format_func=lambda x: next((i[1] for i in s_opts if i[0] == x), "Unknown"))
with st.form("master_bulk_pipeline_form", clear_on_submit=True):
meta_verse_title = st.text_input("Surah / Verse Reference Index Identity Title Name")
meta_desc_text = st.text_area("Write Associated Exegesis / Manual Text Content")
file_voice = st.file_uploader("🎙️ Connect Voice Track / Recitation Audio Attachment File", type=['mp3', 'wav'])
file_pdf = st.file_uploader("📄 Connect Reference PDF E-Book Document Attachment File", type=['pdf'])
file_images_list = st.file_uploader("Select Sequence of Page Images / Graphic Assets", type=['jpg','png','jpeg'], accept_multiple_files=True)
if st.form_submit_button("🚀 INJECT ENTIRE ATTACHED DATA PACK LIVE INTO SERVER DATABASE"):
v_aud_bytes = file_voice.getvalue() if file_voice else None
v_aud_name = file_voice.name if file_voice else None
v_pdf_bytes = file_pdf.getvalue() if file_pdf else None
v_pdf_name = file_pdf.name if file_pdf else None
if file_images_list:
for counter, single_image in enumerate(file_images_list):
img_b_payload = single_image.getvalue()
auto_computed_title = f"{meta_verse_title} - Part {counter + 1}" if meta_verse_title else f"Automated Index Row Page Scan {counter + 1}"
run_query("""INSERT INTO quran_pages (main_folder_id, sub_folder_id, surah_verse, manually_text, quran_img, pdf_file, pdf_name, voice_audio, voice_name)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)""",
(p_sel_id, s_sel_id if s_sel_id != 0 else None, auto_computed_title, meta_desc_text, img_b_payload, v_pdf_bytes, v_pdf_name, v_aud_bytes, v_aud_name), is_select=False)
st.success("Successfully unrolled pipeline. Data injected safely.")
else:
run_query("""INSERT INTO quran_pages (main_folder_id, sub_folder_id, surah_verse, manually_text, quran_img, pdf_file, pdf_name, voice_audio, voice_name)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)""",
(p_sel_id, s_sel_id if s_sel_id != 0 else None, meta_verse_title, meta_desc_text, None, v_pdf_bytes, v_pdf_name, v_aud_bytes, v_aud_name), is_select=False)
st.success("Single entry matrix pipeline deployment verified successfully.")
st.rerun()
elif q_action_node == "4. Correct Data Matrix Entry / Replace Media Attachments":
all_qp_entries = run_query("SELECT id, surah_verse FROM quran_pages")
if all_qp_entries is not None and not all_qp_entries.empty:
target_qp_id = st.selectbox("Select Target Registry Data Row to Modify:", all_qp_entries['id'].tolist(), format_func=lambda x: f"Registry ID Node: {x} -> Title Index: {all_qp_entries[all_qp_entries['id']==x]['surah_verse'].values[0] if not all_qp_entries[all_qp_entries['id']==x].empty else 'Unknown'}")
qp_res = run_query("SELECT * FROM quran_pages WHERE id=?", (target_qp_id,))
if qp_res is not None and not qp_res.empty:
old_qp_row = qp_res.iloc[0]
with st.form("qp_data_row_rectification_form"):
corr_qp_title = st.text_input("Modify/Correct Reference Structural Title Name:", value=old_qp_row.get('surah_verse') or "")
corr_qp_text = st.text_area("Modify/Correct Manual Exegesis Text Content Data:", value=old_qp_row.get('manually_text') or "")
repl_qp_img = st.file_uploader("Replace Primary Image Scan Asset Graphic File", type=['jpg','png','jpeg'])
repl_qp_pdf = st.file_uploader("Replace Attached PDF Document Asset File", type=['pdf'])
repl_qp_aud = st.file_uploader("Replace Recitation Voice Audio Audio Asset File", type=['mp3','wav'])
if st.form_submit_button("🛠️ APPLY RECTIFIED SCHEMAS TO DATA LAYER", type="primary"):
f_img_b = repl_qp_img.getvalue() if repl_qp_img else old_qp_row.get('quran_img')
f_pdf_b = repl_qp_pdf.getvalue() if repl_qp_pdf else old_qp_row.get('pdf_file')
f_pdf_n = repl_qp_pdf.name if repl_qp_pdf else old_qp_row.get('pdf_name')
f_aud_b = repl_qp_aud.getvalue() if repl_qp_aud else old_qp_row.get('voice_audio')
f_aud_n = repl_qp_aud.name if repl_qp_aud else old_qp_row.get('voice_name')
run_query("""UPDATE quran_pages SET surah_verse=?, manually_text=?, quran_img=?, pdf_file=?, pdf_name=?, voice_audio=?, voice_name=? WHERE id=?""",
(corr_qp_title, corr_qp_text, f_img_b, f_pdf_b, f_pdf_n, f_aud_b, f_aud_n, target_qp_id), is_select=False)
st.success("Schema adjustments updated live.")
st.rerun()
else: st.info("No active page rows found.")
elif q_action_node == "5. Wipe Structural Category Nodes or Delete Row Entries":
destruction_level_node = st.radio("Choose Destruction Protocol Target Mode:", ["Wipe Single Specific Row Item Page Data", "Wipe Complete Structural Category Folder"])
if destruction_level_node == "Wipe Single Specific Row Item Page Data":
page_rows = run_query("SELECT id, surah_verse FROM quran_pages")
if page_rows is not None and not page_rows.empty:
trg_p_id = st.selectbox("Select Target Row Unique ID:", page_rows['id'].tolist(), format_func=lambda x: f"ID Node: {x} | Identifier: {page_rows[page_rows['id']==x]['surah_verse'].values[0] if not page_rows[page_rows['id']==x].empty else 'Unknown'}")
if st.button("🚨 PERMANENTLY PURGE DATA ROW ENTRY", type="primary", use_container_width=True):
run_query("DELETE FROM quran_pages WHERE id=?", (trg_p_id,), is_select=False)
st.success("Target content vector cleared completely.")
st.rerun()
else:
if q_folders is not None and not q_folders.empty:
trg_f_id = st.selectbox("Select Target Parent Category Block to Wipe Out:", q_folders['id'].tolist(), format_func=lambda x: q_folders[q_folders['id']==x]['folder_name'].values[0] if not q_folders[q_folders['id']==x].empty else "Unknown")
if st.button("🚨 TRIGGER CRITICAL FULL CASCADING CATEGORY DESTRUCTION", type="primary", use_container_width=True):
run_query("DELETE FROM quran_folders WHERE id=?", (trg_f_id,), is_select=False)
run_query("DELETE FROM quran_sub_folders WHERE main_folder_id=?", (trg_f_id,), is_select=False)
run_query("DELETE FROM quran_pages WHERE main_folder_id=?", (trg_f_id,), is_select=False)
st.success("Cascading database purge completed.")
st.session_state['selected_quran_folder_id'] = None
st.session_state['selected_quran_sub_id'] = None
st.rerun()
# ==========================================
# --- TAB 3: DIFA E GLOBAL AQAID INTEGRATION ---
# ==========================================
with tab_aqaid:
st.markdown("### 🛡️ Difa E Ahlesunnat Global Theological Aqaid Framework")
aqaid_data = run_query("SELECT * FROM global_aqaid")
if st.session_state['selected_aqaid_id'] is not None:
target_aqaid_id = st.session_state['selected_aqaid_id']
if aqaid_data is not None and not aqaid_data.empty and target_aqaid_id in aqaid_data['id'].values:
sel_topic_row = aqaid_data[aqaid_data['id'] == target_aqaid_id].iloc[0]
if st.button("⬅️ Return Back to Aqaid Folders Directory Panel", key="nav_back_aq_master_v4"):
st.session_state['selected_aqaid_id'] = None
st.rerun()
st.markdown(f"## 📂 Theological Folder: {sel_topic_row.get('title') or 'Untitled'}")
if sel_topic_row.get('front_img'): st.image(sel_topic_row['front_img'], width=160)
aq_references_df = run_query("SELECT * FROM aqaid_references WHERE topic_id=? ORDER BY id ASC", (target_aqaid_id,))
if aq_references_df is not None and not aq_references_df.empty:
for idx, ref_row in aq_references_df.iterrows():
st.markdown(f"Reference Node: {ref_row['id']}{ref_row.get('manual_text') or ''}
📚 Citation Source E-Book: {ref_row.get('ref_book') or 'Unknown'} | Page Coordinate: {ref_row.get('page_no') or 'N/A'}
", unsafe_allow_html=True)
if ref_row.get('ref_img'):
split_images_payload = ref_row['ref_img'].split(b"##IMG_SEP##")
for part_idx, img_binary_data in enumerate(split_images_payload):
if img_binary_data: st.image(img_binary_data, use_column_width=True)
else: st.info("No citation reference modules maps found configured under this category cluster.")
else:
st.session_state['selected_aqaid_id'] = None
st.rerun()
else:
if aqaid_data is not None and not aqaid_data.empty:
aq_cols_grid = st.columns(2)
for idx, row in aqaid_data.iterrows():
with aq_cols_grid[idx % 2]:
st.markdown(f"📁 {row.get('title') or 'Untitled'}
", unsafe_allow_html=True)
if row.get('front_img'): st.image(row['front_img'], use_column_width=True)
if st.button(f"Launch Folder Data: {row.get('title') or 'View'}", key=f"aq_folder_launcher_id_{row['id']}", use_container_width=True):
st.session_state['selected_aqaid_id'] = int(row['id'])
st.rerun()
st.markdown("
", unsafe_allow_html=True)
else: st.info("No ideological theological folders are set active.")
if st.session_state['role'] == 'owner':
st.markdown("", unsafe_allow_html=True)
aq_action_node = st.radio("Choose Action Mode Operation Configuration:", [
"1. Instantiate Aqaid Category Profile (New Parent Folder Location)",
"2. Deploy New Literature Evidence Citation Reference Row Block",
"3. Correct/Rectify Reference Citation Text or Replacement Book Scans File",
"4. Wipe Complete Structural Aqaid Category Folder"
], key="owner_aqaid_control_flow_v4")
if aq_action_node == "1. Instantiate Aqaid Category Profile (New Parent Folder Location)":
with st.form("aq_instantiate_parent_folder_form", clear_on_submit=True):
new_aq_folder_title = st.text_input("New Theological Aqaid Folder Title Identifier Name")
new_aq_folder_graphic = st.file_uploader("Set Identity Folder Cover Asset File Scan Image", type=['jpg','png','jpeg'])
if st.form_submit_button("Deploy Dynamic Category Cluster Block") and new_aq_folder_title:
run_query("INSERT INTO global_aqaid (title, front_img) VALUES (?, ?)", (new_aq_folder_title, new_aq_folder_graphic.getvalue() if new_aq_folder_graphic else None), is_select=False)
st.success("New structural category asset layer mapped safely.")
st.rerun()
elif aq_action_node == "2. Deploy New Literature Evidence Citation Reference Row Block" and aqaid_data is not None and not aqaid_data.empty:
target_aq_parent_id = st.selectbox("Select Target Aqaid Cluster Category Node:", aqaid_data['id'].tolist(), format_func=lambda x: aqaid_data[aqaid_data['id']==x]['title'].values[0] if not aqaid_data[aqaid_data['id']==x].empty else "Unknown")
with st.form("aq_new_citation_submission_form", clear_on_submit=True):
new_aq_text = st.text_area("Write Comprehensive Explanatory Argumentation / Literature Text Content")
new_aq_book = st.text_input("Authentic Citation Source E-Book Name Title")
new_aq_page = st.text_input("Page Number Location Identifier Index Coordinate")
new_aq_scans_list = st.file_uploader("Select Reference Book Graphic Scan Evidence Proofs Asset Files", type=['jpg','png','jpeg'], accept_multiple_files=True)
if st.form_submit_button("✅ DEPLOY CITATION RECORD BLOCK TO SYSTEM DATA MATRIX LAYER"):
glued_images_payload = b""
if new_aq_scans_list: glued_images_payload = b"##IMG_SEP##".join([f.getvalue() for f in new_aq_scans_list])
run_query("INSERT INTO aqaid_references (topic_id, manual_text, ref_book, page_no, ref_img) VALUES (?, ?, ?, ?, ?)", (target_aq_parent_id, new_aq_text, new_aq_book, new_aq_page, glued_images_payload), is_select=False)
st.success("New structural theological validation node appended online safely.")
st.rerun()
elif aq_action_node == "3. Correct/Rectify Reference Citation Text or Replacement Book Scans File":
all_aq_citations_pool = run_query("SELECT id, ref_book FROM aqaid_references")
if all_aq_citations_pool is not None and not all_aq_citations_pool.empty:
target_aq_edit_id = st.selectbox("Select Target Citation Entry Row Node to Rectify:", all_aq_citations_pool['id'].tolist(), format_func=lambda x: f"Registry Unique ID: {x} -> Source Book Reference: {all_aq_citations_pool[all_aq_citations_pool['id']==x]['ref_book'].values[0] if not all_aq_citations_pool[all_aq_citations_pool['id']==x].empty else 'Unknown'}")
aq_ref_res = run_query("SELECT * FROM aqaid_references WHERE id=?", (target_aq_edit_id,))
if aq_ref_res is not None and not aq_ref_res.empty:
old_aq_cit_data = aq_ref_res.iloc[0]
with st.form("aq_citation_correction_terminal_form"):
corr_aq_text = st.text_area("Modify/Correct Comprehensive Explanatory Text Content Data:", value=old_aq_cit_data.get('manual_text') or "")
corr_aq_book = st.text_input("Modify/Correct Authentic Source E-Book Nomenclature Name:", value=old_aq_cit_data.get('ref_book') or "")
corr_aq_page = st.text_input("Modify/Correct Page Number Index Coordinate Parameter:", value=old_aq_cit_data.get('page_no') or "")
repl_aq_scans_list = st.file_uploader("Upload New Scan Proof Files", type=['jpg','png','jpeg'], accept_multiple_files=True)
if st.form_submit_button("🛠️ APPLY RECTIFIED DATA STRUCTURAL PARAMETERS", type="primary"):
if repl_aq_scans_list:
recompiled_glued_payload = b"##IMG_SEP##".join([f.getvalue() for f in repl_aq_scans_list])
run_query("UPDATE aqaid_references SET manual_text=?, ref_book=?, page_no=?, ref_img=? WHERE id=?", (corr_aq_text, corr_aq_book, corr_aq_page, recompiled_glued_payload, target_aq_edit_id), is_select=False)
else:
run_query("UPDATE aqaid_references SET manual_text=?, ref_book=?, page_no=? WHERE id=?", (corr_aq_text, corr_aq_book, corr_aq_page, target_aq_edit_id), is_select=False)
st.success("Data parameters verified and applied onto live master registry nodes successfully.")
st.rerun()
else: st.info("No active citation records found.")
elif aq_action_node == "4. Wipe Complete Structural Aqaid Category Folder" and aqaid_data is not None and not aqaid_data.empty:
target_aq_purge_id = st.selectbox("Select Target Aqaid Category Profile to Purge completely:", aqaid_data['id'].tolist(), format_func=lambda x: aqaid_data[aqaid_data['id']==x]['title'].values[0] if not aqaid_data[aqaid_data['id']==x].empty else "Unknown")
if st.button("🚨 TRIGGER IRREVERSIBLE FULL CATEGORY DATA DESTRUCTION PROTOCOL", type="primary", use_container_width=True):
run_query("DELETE FROM global_aqaid WHERE id=?", (target_aq_purge_id,), is_select=False)
run_query("DELETE FROM aqaid_references WHERE topic_id=?", (target_aq_purge_id,), is_select=False)
st.success("Cascading database purge completed successfully.")
st.session_state['selected_aqaid_id'] = None
st.rerun()
# ==========================================
# --- TAB 4: FIQH WA MASAIL MANAGEMENT ENGINE ---
# ==========================================
with tab_fiqh:
st.markdown("### 📝 Fiqh Wa Masail Juristic Canonical Directives Directory")
fiqh_data = run_query("SELECT * FROM fiqh_folders")
if st.session_state['selected_fiqh_folder_id'] is not None:
target_f_id = st.session_state['selected_fiqh_folder_id']
if fiqh_data is not None and not fiqh_data.empty and target_f_id in fiqh_data['id'].values:
sel_fiqh_folder_row = fiqh_data[fiqh_data['id'] == target_f_id].iloc[0]
if st.button("⬅️ Return Back to Fiqh Categories Core Directory Panel", key="nav_back_fiqh_master_v4"):
st.session_state['selected_fiqh_folder_id'] = None
st.rerun()
st.markdown(f"#### 📂 Juristic Category Folder: {sel_fiqh_folder_row.get('category_name') or 'Untitled'}")
masail_records_df = run_query("SELECT * FROM fiqh_masail WHERE fiqh_folder_id=? ORDER BY id ASC", (target_f_id,))
if masail_records_df is not None and not masail_records_df.empty:
for m_idx, m_row in masail_records_df.iterrows():
st.markdown(f"Masla Registry Unique ID: {m_row['id']}📌 Canonical Topic Title Name: {m_row.get('topic_title') or 'Untitled'}
{m_row.get('manual_text') or ''}
📋 Approved Juristic Documentation Reference: {m_row.get('ref_details') or 'N/A'}
", unsafe_allow_html=True)
if m_row.get('masail_img'):
split_fiqh_images = m_row['masail_img'].split(b"##FIQH_SEP##")
for sub_f_idx, img_binary_data in enumerate(split_fiqh_images):
if img_binary_data: st.image(img_binary_data, use_column_width=True)
if m_row.get('pdf_file'):
try:
f_pdf_bytes_stream = m_row['pdf_file']
st.markdown(f"", unsafe_allow_html=True)
with st.spinner("Converting Document Vector Matrix to Interface Viewport Scans..."):
parsed_fiqh_images = convert_from_bytes(f_pdf_bytes_stream)
for i, p_img in enumerate(parsed_fiqh_images):
buffer_io = io.BytesIO()
p_img.save(buffer_io, format='PNG')
st.image(buffer_io.getvalue(), caption=f"Juristic Page View {i+1} / {len(parsed_fiqh_images)}", use_column_width=True)
except Exception as ex:
st.error(f"Integrated jurisprudence file engine reader was unable to parse attached document: {ex}")
st.markdown("
", unsafe_allow_html=True)
else: st.info("No juristic canonical records rows found configured inside this category cluster.")
else:
st.session_state['selected_fiqh_folder_id'] = None
st.rerun()
else:
if fiqh_data is not None and not fiqh_data.empty:
fiqh_cols_grid = st.columns(2)
for idx, row in fiqh_data.iterrows():
with fiqh_cols_grid[idx % 2]:
st.markdown(f"📝 {row.get('category_name') or 'Untitled'}
", unsafe_allow_html=True)
if row.get('cover_img'): st.image(row['cover_img'], use_column_width=True)
if st.button(f"Launch Category Module: {row.get('category_name') or 'View'}", key=f"fiqh_launcher_grid_id_{row['id']}", use_container_width=True):
st.session_state['selected_fiqh_folder_id'] = int(row['id'])
st.rerun()
st.markdown("
", unsafe_allow_html=True)
else: st.info("Juristic canonical framework folders category nodes directory indexing is empty.")
# --- ADVANCED FIQH DATA MANIPULATION TERMINAL ---
if st.session_state['role'] == 'owner':
st.markdown("", unsafe_allow_html=True)
fiqh_action_node = st.radio("Choose Action Protocol Mode Setup Configuration:", [
"1. Instantiate Juristic Category Module (New Parent Folder Location)",
"2. Deploy New Canonical Judgement Directive Row Block (Add New Masla Entry)",
"3. Correct/Rectify Masla Text, Citation References Info or Attachments (Image/PDF)",
"4. Wipe Complete Juristic Category Folder Matrix"
], key="owner_fiqh_control_dispatcher_v4")
if fiqh_action_node == "1. Instantiate Juristic Category Module (New Parent Folder Location)":
with st.form("fiqh_instantiate_parent_folder_form", clear_on_submit=True):
new_f_folder_title = st.text_input("New Juristic Folder Title Identifier Name")
new_f_folder_graphic = st.file_uploader("Set Identity Folder Cover Asset File Scan Image", type=['jpg','png','jpeg'])
if st.form_submit_button("Deploy Dynamic Category Cluster Block") and new_f_folder_title:
run_query("INSERT INTO fiqh_folders (category_name, cover_img) VALUES (?, ?)", (new_f_folder_title, new_f_folder_graphic.getvalue() if new_f_folder_graphic else None), is_select=False)
st.success("New structural jurisprudence folder layer mapped successfully.")
st.rerun()
elif fiqh_action_node == "2. Deploy New Canonical Judgement Directive Row Block (Add New Masla Entry)" and fiqh_data is not None and not fiqh_data.empty:
target_f_parent_id = st.selectbox("Select Target Jurisprudence Category Folder Node:", fiqh_data['id'].tolist(), format_func=lambda x: fiqh_data[fiqh_data['id']==x]['category_name'].values[0] if not fiqh_data[fiqh_data['id']==x].empty else "Unknown")
with st.form("fiqh_new_masla_submission_form", clear_on_submit=True):
new_f_title = st.text_input("Juristic Masla Core Subject Heading Title Name")
new_f_txt = st.text_area("Write Comprehensive Explanatory Juristic Decree / Canonical Text Content")
new_f_ref = st.text_input("Juristic Reference Book / Legal Authorization Decree Citations Details Info")
new_f_scans_list = st.file_uploader("Select Reference Book Graphic Scan Evidence Proofs Asset Files", type=['jpg','png','jpeg'], accept_multiple_files=True)
new_f_pdf = st.file_uploader("📄 Connect Reference PDF E-Book Document Asset File Attachment Option", type=['pdf'])
if st.form_submit_button("✅ DEPLOY JURISTIC MASLA BLOCK TO SYSTEM DATA MATRIX LAYER") and new_f_title:
glued_fiqh_images = b""
if new_f_scans_list: glued_fiqh_images = b"##FIQH_SEP##".join([f.getvalue() for f in new_f_scans_list])
f_pdf_b = new_f_pdf.getvalue() if new_f_pdf else None
f_pdf_n = new_f_pdf.name if new_f_pdf else None
run_query("""INSERT INTO fiqh_masail (fiqh_folder_id, topic_title, manual_text, ref_details, masail_img, pdf_file, pdf_name)
VALUES (?, ?, ?, ?, ?, ?, ?)""",
(target_f_parent_id, new_f_title, new_f_txt, new_f_ref, glued_fiqh_images, f_pdf_b, f_pdf_n), is_select=False)
st.success("New juristic verification directive entry row configured safely.")
st.rerun()
elif fiqh_action_node == "3. Correct/Rectify Masla Text, Citation References Info or Attachments (Image/PDF)":
all_fm_rows_pool = run_query("SELECT id, topic_title FROM fiqh_masail")
if all_fm_rows_pool is not None and not all_fm_rows_pool.empty:
target_fm_edit_id = st.selectbox("Select Target Masla Entry Row Node to Rectify:", all_fm_rows_pool['id'].tolist(), format_func=lambda x: f"Registry Unique ID: {x} -> Subject Heading: {all_fm_rows_pool[all_fm_rows_pool['id']==x]['topic_title'].values[0] if not all_fm_rows_pool[all_fm_rows_pool['id']==x].empty else 'Unknown'}")
fm_res = run_query("SELECT * FROM fiqh_masail WHERE id=?", (target_fm_edit_id,))
if fm_res is not None and not fm_res.empty:
old_fm_data_row = fm_res.iloc[0]
with st.form("fiqh_masla_correction_terminal_form"):
corr_fm_title = st.text_input("Modify/Correct Juristic Masla Core Subject Title Name:", value=old_fm_data_row.get('topic_title') or "")
corr_fm_text = st.text_area("Modify/Correct Explanatory Juristic Decree Canonical Text Content Data:", value=old_fm_data_row.get('manual_text') or "")
corr_fm_ref = st.text_input("Modify/Correct Reference Book / Decrees Citations Info Parameter:", value=old_fm_data_row.get('ref_details') or "")
repl_fm_scans = st.file_uploader("Replace Scans Graphic Proof Files", type=['jpg','png','jpeg'], accept_multiple_files=True)
repl_fm_pdf = st.file_uploader("Replace Attached Reference PDF Document Asset File", type=['pdf'])
if st.form_submit_button("🛠️ APPLY RECTIFIED DATA STRUCTURAL PARAMETERS", type="primary"):
final_scans_b = b"##FIQH_SEP##".join([f.getvalue() for f in repl_fm_scans]) if repl_fm_scans else old_fm_data_row.get('masail_img')
final_pdf_b = repl_fm_pdf.getvalue() if repl_fm_pdf else old_fm_data_row.get('pdf_file')
final_pdf_n = repl_fm_pdf.name if repl_fm_pdf else old_fm_data_row.get('pdf_name')
run_query("""UPDATE fiqh_masail SET topic_title=?, manual_text=?, ref_details=?, masail_img=?, pdf_file=?, pdf_name=? WHERE id=?""",
(corr_fm_title, corr_fm_text, corr_fm_ref, final_scans_b, final_pdf_b, final_pdf_n, target_fm_edit_id), is_select=False)
st.success("Juristic canonical entry parameters modified successfully.")
st.rerun()
else: st.info("No active juristic canonical masla data rows found available.")
elif fiqh_action_node == "4. Wipe Complete Juristic Category Folder Matrix" and fiqh_data is not None and not fiqh_data.empty:
target_f_purge_id = st.selectbox("Select Target Jurisprudence Category Folder to Purge completely:", fiqh_data['id'].tolist(), format_func=lambda x: fiqh_data[fiqh_data['id']==x]['category_name'].values[0] if not fiqh_data[fiqh_data['id']==x].empty else "Unknown")
if st.button("🚨 TRIGGER IRREVERSIBLE FULL JURISTIC CATEGORY DATA DESTRUCTION PROTOCOL", type="primary", use_container_width=True):
run_query("DELETE FROM fiqh_folders WHERE id=?", (target_f_purge_id,), is_select=False)
run_query("DELETE FROM fiqh_masail WHERE fiqh_folder_id=?", (target_f_purge_id,), is_select=False)
st.success("Cascading database purge completed successfully.")
st.session_state['selected_fiqh_folder_id'] = None
st.rerun()