<?php
/**
 * OTIS Spiritual Dashboard (الروحانيات)
 * Premium RTL / Soft Design
 */
$csrf    = $_SESSION['csrf_token'] ?? '';
$date    = $date ?? date('Y-m-d');
$records = $records ?? ['max_perfect' => 0, 'max_overall' => 0]; // Defensive fallback
?>
<style>
@import url('https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700;800&display=swap');

.spiritual-dashboard { font-family: 'Tajawal', sans-serif; color: #374151; }
.bg-spiritual { background-color: #f0fdf4 !important; }
.bg-beige { background-color: #fef3c7 !important; }

.spiritual-card {
    border-radius: 24px; border: none; box-shadow: 0 10px 40px rgba(0,0,0,0.03);
    transition: all 0.4s cubic-bezier(0.16,1,0.3,1); background: #ffffff; overflow: hidden;
}
.spiritual-card:hover { transform: translateY(-5px); box-shadow: 0 15px 50px rgba(0,0,0,0.07); }
.spiritual-title { font-weight: 800; letter-spacing: -0.5px; color: #065f46; }

.spiritual-switch .form-check-input { width: 3.5rem; height: 1.75rem; background-color: #e5e7eb; border-color: transparent; cursor: pointer; transition: all 0.3s; }
.spiritual-switch .form-check-input:checked { background-color: #10b981; border-color: #10b981; }
.spiritual-switch .form-check-label { font-size: 1.25rem; font-weight: 700; margin-right: 1rem; cursor: pointer; color: #4b5563; transition: color 0.3s; }
.spiritual-switch .form-check-input:checked ~ .form-check-label { color: #059669; }

@keyframes fadeInUp { from { opacity:0; transform:translateY(20px); } to { opacity:1; transform:translateY(0); } }
.animate-fade-in { animation: fadeInUp 0.7s forwards; opacity: 0; }
.delay-1 { animation-delay: 0.1s; } .delay-2 { animation-delay: 0.2s; }
.delay-3 { animation-delay: 0.3s; } .delay-4 { animation-delay: 0.4s; }

.streak-box { background: linear-gradient(135deg, #10b981 0%, #059669 100%); color: white; border-radius: 20px; padding: 1.5rem; min-height: 140px; display: flex; flex-direction: column; justify-content: center; position: relative; overflow: hidden; transition: all 0.3s ease; border: 1px solid rgba(255,255,255,0.1); }
.streak-box:hover { transform: scale(1.02); box-shadow: 0 10px 25px rgba(16,185,129,0.3) !important; }
.streak-box.perfect { background: linear-gradient(135deg, #10b981 0%, #059669 100%); }
.streak-box.overall { background: linear-gradient(135deg, #0ea5e9 0%, #0284c7 100%); }
.streak-box::after { content: '\f06d'; font-family: 'Font Awesome 6 Free'; font-weight: 900; position: absolute; right: -5px; bottom: -15px; font-size: 4.5rem; opacity: 0.15; transform: rotate(-15deg); }
.streak-num { font-size: 2.8rem; font-weight: 800; line-height: 1; margin-bottom: 5px; text-shadow: 0 2px 4px rgba(0,0,0,0.1); }

@keyframes pulse-flame { 
    0% { transform: scale(1); filter: drop-shadow(0 0 0px #f59e0b); }
    50% { transform: scale(1.1); filter: drop-shadow(0 0 10px #f59e0b); }
    100% { transform: scale(1); filter: drop-shadow(0 0 0px #f59e0b); }
}
.streak-badge { font-size: 0.7rem; background: rgba(255,255,255,0.2); backdrop-filter: blur(4px); padding: 4px 10px; border-radius: 50px; display: inline-block; margin-top: 5px; border: 1px solid rgba(255,255,255,0.1); }
.flame-icon { color: #f59e0b; animation: pulse-flame 2s infinite; margin-left: 5px; }

.star-rating { direction: ltr; display: inline-flex; flex-direction: row-reverse; }
.star-rating input { display: none; }
.star-rating label { font-size: 2.5rem; color: #d1d5db; cursor: pointer; transition: all 0.2s; padding: 0 4px; }
.star-rating label:hover, .star-rating label:hover ~ label, .star-rating input:checked ~ label { color: #fbbf24; transform: scale(1.1); }

.heart-radio-group input[type="radio"] { display: none; }
.heart-radio-group label { background: #f3f4f6; border: 2px solid transparent; border-radius: 16px; padding: 0.8rem 1.5rem; font-weight: 700; cursor: pointer; transition: all 0.3s; flex: 1; text-align: center; }
.heart-radio-group input[type="radio"]:checked + label { background: #ecfdf5; border-color: #10b981; color: #065f46; transform: translateY(-2px); box-shadow: 0 4px 15px rgba(16,185,129,0.15); }
</style>

<div class="spiritual-dashboard bg-spiritual px-4 py-5 min-vh-100">

    <?php 
        $stateMap = [
            'high' => ['color' => '#10b981', 'bg' => '#d1fae5', 'icon' => 'fa-leaf', 'text' => 'مرتفع', 'msg' => 'سكينة عالية، حافظ على هذه الروح الطيبة.'],
            'medium' => ['color' => '#f59e0b', 'bg' => '#fef3c7', 'icon' => 'fa-seedling', 'text' => 'متوازن', 'msg' => 'حالة متوازنة، ابحث عن المزيد من الطمأنينة.'],
            'low' => ['color' => '#6366f1', 'bg' => '#e0e7ff', 'icon' => 'fa-cloud', 'text' => 'هادئ/منخفض', 'msg' => 'لا بأس، كل يوم هو فرصة جديدة لتجديد النية.']
        ];
        $currentState = $stateMap[$state ?? 'medium'];
    ?>

    <?php if ($is_locked): ?>
        <div class="alert alert-warning border-0 rounded-4 shadow-sm animate-fade-in fw-bold p-3 mb-4">
            <i class="fa-solid fa-lock me-2"></i> هذا اليوم مغلق لأنه في الماضي. السجل متاح للقراءة فقط ولن تُحفظ أي تعديلات.
        </div>
    <?php endif; ?>

    <!-- Status Banner Dynamic & Soft -->
    <div id="statusBanner" class="alert border-0 rounded-4 shadow-sm animate-fade-in px-4 py-3 mb-4 d-flex align-items-center justify-content-between" style="background-color: <?= $currentState['bg'] ?>; color: <?= $currentState['color'] ?>;">
        <div class="d-flex align-items-center">
            <i id="statusIcon" class="fa-solid <?= $currentState['icon'] ?> me-3 fs-3"></i> 
            <div>
                <strong class="d-block fs-5" id="statusTextTitle">الحالة الروحية: <?= $currentState['text'] ?></strong>
                <span id="statusTextMsg" class="opacity-75"><?= $currentState['msg'] ?></span>
            </div>
        </div>
        <div class="text-end">
            <small class="d-block fw-bold opacity-75">مؤشر الاستمرارية</small>
            <span class="fs-4 fw-bold" id="consistencyDisplay"><?= $consistency ?? 50 ?>%</span>
        </div>
    </div>

    <!-- Header -->
    <div class="row align-items-center mb-5 animate-fade-in">
        <div class="col-md-7">
            <div class="d-flex align-items-center mb-2">
                <h1 class="display-5 spiritual-title mb-0"><i class="fa-solid fa-kaaba text-success me-3"></i> السجل الروحاني</h1>
            </div>
            <p class="text-secondary fs-5 fw-semibold mb-0">مركز السكينة والمتابعة الإيمانية لليوم: <?= date('M d, Y', strtotime($date)) ?></p>
        </div>
        <div class="col-md-5 text-start text-md-end mt-4 mt-md-0 d-flex justify-content-end align-items-center gap-3">
            <a href="<?= BASE_URL ?>/spiritual/archive" class="btn btn-outline-success rounded-pill fw-bold px-4 py-2 shadow-sm d-flex align-items-center gap-2"><i class="fa-solid fa-clock-rotate-left"></i> سجل الروحانيات</a>
            <!-- Progress Doughnut visually represented via linear bar for calmness -->
            <div class="bg-white p-3 rounded-4 shadow-sm text-center" style="width: 250px;">
                <span class="d-block text-muted fw-bold mb-2">اكتمال المهام اليومية</span>
                <div class="progress rounded-pill bg-light" style="height: 18px;">
                    <div class="progress-bar bg-success progress-bar-striped progress-bar-animated" id="globalProgress" role="progressbar" style="width: <?= $progress ?>%; font-weight:bold; font-size:0.85rem;"><?= $progress ?>%</div>
                </div>
            </div>
        </div>
    </div>

    <div class="row g-4">
        <!-- COLUMN 1: Prayers & Activities -->
        <div class="col-xl-8">
            <!-- SPIRITUAL TIMELINE -->
            <div class="spiritual-card p-4 animate-fade-in delay-1 mb-4 position-relative">
                <h4 class="fw-bold mb-4 text-dark"><i class="fa-solid fa-timeline text-success me-2"></i> مسار اليوم (التدفق الروحاني)</h4>
                
                <div class="d-flex justify-content-between position-relative px-2 pb-4">
                    <!-- Timeline Line -->
                    <div class="position-absolute" style="top: 25px; left: 5%; right: 5%; height: 4px; background: #e5e7eb; z-index: 1; border-radius: 4px;"></div>
                    
                    <?php 
                    $timeline = [
                        ['id'=>'p_fajr', 'name'=>'الفجر', 'table'=>'spiritual_prayers', 'field'=>'fajr', 'val'=>$prayers->fajr, 'icon'=>'fa-moon'],
                        ['id'=>'a_morn', 'name'=>'الصباح', 'table'=>'spiritual_adhkar', 'field'=>'morning_done', 'val'=>$adhkar->morning_done, 'icon'=>'fa-sun'],
                        ['id'=>'p_dhuhr', 'name'=>'الظهر', 'table'=>'spiritual_prayers', 'field'=>'dhuhr', 'val'=>$prayers->dhuhr, 'icon'=>'fa-sun'],
                        ['id'=>'p_asr', 'name'=>'العصر', 'table'=>'spiritual_prayers', 'field'=>'asr', 'val'=>$prayers->asr, 'icon'=>'fa-cloud-sun'],
                        ['id'=>'p_maghrib', 'name'=>'المغرب', 'table'=>'spiritual_prayers', 'field'=>'maghrib', 'val'=>$prayers->maghrib, 'icon'=>'fa-sunset'],
                        ['id'=>'p_isha', 'name'=>'العشاء', 'table'=>'spiritual_prayers', 'field'=>'isha', 'val'=>$prayers->isha, 'icon'=>'fa-star'],
                        ['id'=>'a_eve', 'name'=>'المساء', 'table'=>'spiritual_adhkar', 'field'=>'evening_done', 'val'=>$adhkar->evening_done, 'icon'=>'fa-moon']
                    ];
                    foreach($timeline as $idx => $t): 
                        $isChecked = $t['val'] ? 'checked' : '';
                        $colClass = $t['val'] ? 'text-success' : 'text-muted';
                        $bgClass = $t['val'] ? 'bg-success' : 'bg-white border text-muted';
                    ?>
                    <div class="text-center position-relative" style="z-index: 2; width: 60px;">
                        <input class="form-check-input ajax-toggle position-absolute opacity-0" style="width:100%; height:100%; cursor:pointer; top:0; left:0; z-index:3;" type="checkbox" id="<?= $t['id'] ?>" data-table="<?= $t['table'] ?>" data-field="<?= $t['field'] ?>" <?= $isChecked ?> <?= $is_locked ? 'disabled' : '' ?>>
                        <div class="rounded-circle d-flex align-items-center justify-content-center mx-auto mb-2 transition-all timeline-node <?= $bgClass ?>" id="node_<?= $t['id'] ?>" style="width: 54px; height: 54px; box-shadow: 0 4px 10px rgba(0,0,0,0.05); <?= $t['val']?'color:white;':'' ?>">
                            <i class="fa-solid <?= $t['icon'] ?> fs-4"></i>
                        </div>
                        <span class="d-block fw-bold fs-6 timeline-label <?= $colClass ?>" id="label_<?= $t['id'] ?>"><?= $t['name'] ?></span>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>

            <style>
                .timeline-node { transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); }
                input:checked + .timeline-node { background-color: #10b981 !important; color: white !important; border-color: #10b981 !important; box-shadow: 0 0 15px rgba(16,185,129,0.4) !important; transform: scale(1.1); }
                input:checked ~ .timeline-label { color: #10b981 !important; font-weight: 800; }
                input:hover + .timeline-node { transform: scale(1.05); }
            </style>

            <div class="row g-4 mb-4">
                <!-- QURAN WIRD -->
                <div class="col-md-6 animate-fade-in delay-2">
                    <div class="spiritual-card p-4 h-100 bg-light">
                        <h5 class="fw-bold mb-4 text-dark"><i class="fa-solid fa-book-quran text-info me-2"></i> الورد القرآني</h5>
                        <div class="d-flex flex-column gap-3">
                            <div class="form-check form-switch spiritual-switch d-flex align-items-center bg-white p-3 rounded-4 shadow-sm">
                                <input class="form-check-input ms-3 ajax-toggle" type="checkbox" role="switch" id="q_w" data-table="spiritual_quran" data-field="wird_completed" <?= $quran->wird_completed ? 'checked' : '' ?> <?= $is_locked ? 'disabled' : '' ?>>
                                <label class="form-check-label mb-0" for="q_w">الورد اليومي</label>
                            </div>
                            <div class="row g-2">
                                <div class="col-6">
                                    <div class="form-check form-switch spiritual-switch d-flex align-items-center bg-white p-2 rounded-4 shadow-sm">
                                        <input class="form-check-input ms-2 ajax-toggle" type="checkbox" role="switch" id="q_y" data-table="spiritual_quran" data-field="yaseen" <?= $quran->yaseen ? 'checked' : '' ?> <?= $is_locked ? 'disabled' : '' ?>>
                                        <label class="form-check-label fs-5 mb-0" for="q_y">يس</label>
                                    </div>
                                </div>
                                <div class="col-6">
                                    <div class="form-check form-switch spiritual-switch d-flex align-items-center bg-white p-2 rounded-4 shadow-sm">
                                        <input class="form-check-input ms-2 ajax-toggle" type="checkbox" role="switch" id="q_q" data-table="spiritual_quran" data-field="waqiah" <?= $quran->waqiah ? 'checked' : '' ?> <?= $is_locked ? 'disabled' : '' ?>>
                                        <label class="form-check-label fs-5 mb-0" for="q_q">الواقعة</label>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- CHARITY -->
                <div class="col-md-6 animate-fade-in delay-3">
                    <div class="spiritual-card p-4 h-100 position-relative" style="background: linear-gradient(145deg, #f0fdf4, #dcfce7);">
                        <h5 class="fw-bold mb-4 text-dark"><i class="fa-solid fa-hand-holding-dollar text-success me-2"></i> العطاء والصدقة</h5>
                        <div class="d-flex flex-column gap-3">
                            <input type="number" id="charity_amount" class="form-control fw-bold text-center form-control-lg border-0 shadow-sm ajax-input rounded-4" data-field="amount" data-table="spiritual_charity" placeholder="المبلغ (جنيه)" value="<?= $charity->amount > 0 ? $charity->amount : '' ?>" <?= $is_locked ? 'disabled' : '' ?>>
                            <div class="form-check form-switch spiritual-switch d-flex justify-content-center align-items-center bg-white p-3 rounded-4 shadow-sm mb-0">
                                <input class="form-check-input ms-3 ajax-toggle" type="checkbox" role="switch" id="c_done" data-table="spiritual_charity" data-field="completed" <?= $charity->completed ? 'checked' : '' ?> <?= $is_locked ? 'disabled' : '' ?>>
                                <label class="form-check-label mb-0 fs-5" for="c_done">أخرجت صدقة اليوم</label>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
        </div>

        <!-- COLUMN 2: Experience & State -->
        <div class="col-xl-4">
            
            <!-- SMART FEEDBACK -->
            <div class="alert alert-info border-0 rounded-4 shadow-sm animate-fade-in delay-1 fw-bold p-3 mb-4 d-flex">
                <i class="fa-solid fa-robot mt-1 me-3 fs-3 text-primary"></i>
                <div class="ms-1">
                    <h6 class="fw-bold mb-1 text-primary">تحليل الذكاء الروحاني:</h6>
                    <span class="fs-6"><?= $feedback ?></span>
                </div>
            </div>

            <!-- HEART STATE -->
            <div class="spiritual-card p-4 animate-fade-in delay-1 mb-4 border-top border-4 border-success">
                <h5 class="fw-bold mb-4 text-center text-dark"><i class="fa-solid fa-heart text-danger me-2"></i> ما هو حال قلبك اليوم؟</h5>
                <div class="heart-radio-group d-flex flex-wrap gap-2">
                    <?php $hh = $log->heart_state; ?>
                    <input type="radio" name="heart" id="h1" value="مطمئن" class="ajax-string" data-field="heart_state" <?= $hh=='مطمئن'?'checked':'' ?> <?= $is_locked ? 'disabled' : '' ?>><label for="h1">مطمئن</label>
                    <input type="radio" name="heart" id="h2" value="نشيط" class="ajax-string" data-field="heart_state" <?= $hh=='نشيط'?'checked':'' ?> <?= $is_locked ? 'disabled' : '' ?>><label for="h2">نشيط</label>
                    <input type="radio" name="heart" id="h3" value="ثقيل" class="ajax-string" data-field="heart_state" <?= $hh=='ثقيل'?'checked':'' ?> <?= $is_locked ? 'disabled' : '' ?>><label for="h3">ثقيل</label>
                    <input type="radio" name="heart" id="h4" value="مشتت" class="ajax-string" data-field="heart_state" <?= $hh=='مشتت'?'checked':'' ?> <?= $is_locked ? 'disabled' : '' ?>><label for="h4">مشتت</label>
                </div>
            </div>

            <!-- DAILY GOAL -->
            <div class="spiritual-card p-4 animate-fade-in delay-2 mb-4 bg-light">
                <h5 class="fw-bold mb-3 text-dark"><i class="fa-solid fa-bullseye text-primary me-2"></i> نية وهدف روحاني اليوم</h5>
                <input type="text" id="daily_goal" class="form-control form-control-lg border-0 shadow-sm fw-bold ajax-input" data-field="daily_goal" placeholder="اكتب نية أو عمل صالح تهدف لفعله اليوم..." value="<?= htmlspecialchars($log->daily_goal ?? '') ?>" <?= $is_locked ? 'disabled' : '' ?>>
                <small class="text-muted mt-2 d-block">يتم الحفظ تلقائياً بمجرد الخروج من المربع</small>
            </div>

            <!-- DAILY RATING -->
            <div class="spiritual-card p-4 animate-fade-in delay-3 mb-4 text-center">
                <h5 class="fw-bold mb-2 text-dark">تقييمك ليومك الروحاني</h5>
                <div class="star-rating d-inline-block">
                    <?php $r = $log->daily_rating; ?>
                    <input type="radio" name="rating" id="s5" value="5" class="ajax-string" data-field="daily_rating" <?= $r==5?'checked':'' ?> <?= $is_locked ? 'disabled' : '' ?>><label for="s5">★</label>
                    <input type="radio" name="rating" id="s4" value="4" class="ajax-string" data-field="daily_rating" <?= $r==4?'checked':'' ?> <?= $is_locked ? 'disabled' : '' ?>><label for="s4">★</label>
                    <input type="radio" name="rating" id="s3" value="3" class="ajax-string" data-field="daily_rating" <?= $r==3?'checked':'' ?> <?= $is_locked ? 'disabled' : '' ?>><label for="s3">★</label>
                    <input type="radio" name="rating" id="s2" value="2" class="ajax-string" data-field="daily_rating" <?= $r==2?'checked':'' ?> <?= $is_locked ? 'disabled' : '' ?>><label for="s2">★</label>
                    <input type="radio" name="rating" id="s1" value="1" class="ajax-string" data-field="daily_rating" <?= $r==1?'checked':'' ?> <?= $is_locked ? 'disabled' : '' ?>><label for="s1">★</label>
                </div>
            </div>

            <!-- ADVANCED STREAKS -->
            <h5 class="fw-bold text-dark mt-4 mb-3 animate-fade-in delay-4"><i class="fa-solid fa-arrow-trend-up text-danger me-2"></i> سلاسل الاستمرارية 🔥</h5>
            <div class="row g-3 animate-fade-in delay-4 mb-5">
                <div class="col-6">
                    <div class="streak-box shadow-sm perfect">
                        <span class="fs-6 fw-bold opacity-90 mb-1">المثالية (100%) <i class="fa-solid fa-fire flame-icon"></i></span>
                        <div class="d-flex align-items-baseline">
                            <span class="streak-num" id="s_perfect"><?= $streaks['perfect'] ?></span>
                            <span class="ms-2 fw-bold fs-5">يوم</span>
                        </div>
                        <div class="streak-badge">
                            الرقم القياسي: <span class="fw-bold"><?= $records['max_perfect'] ?></span>
                        </div>
                    </div>
                </div>
                <div class="col-6">
                    <div class="streak-box shadow-sm overall">
                        <span class="fs-6 fw-bold opacity-90 mb-1">العامة (خال من الضعف)</span>
                        <div class="d-flex align-items-baseline">
                            <span class="streak-num" id="s_overall"><?= $streaks['overall'] ?></span>
                            <span class="ms-2 fw-bold fs-5">يوم</span>
                        </div>
                        <div class="streak-badge">
                            الرقم القياسي: <span class="fw-bold"><?= $records['max_overall'] ?></span>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', () => {
    
    // Abstracted Fetch Function for AJAX
    const postSpiritualData = async (url, payload) => {
        try {
            const response = await fetch('<?= BASE_URL ?>/spiritual/' + url, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ date: '<?= $date ?>', ...payload })
            });
            return await response.json();
        } catch (error) {
            console.error("Spiritual AJAX Error:", error);
            return {success: false};
        }
    };

    // Toggle Checks
    document.querySelectorAll('.ajax-toggle').forEach(el => {
        el.addEventListener('change', async (e) => {
            const table = e.target.getAttribute('data-table');
            const field = e.target.getAttribute('data-field');
            
            if (table === 'spiritual_charity' && field === 'completed') {
                const amount = document.getElementById('charity_amount').value;
                if(e.target.checked && amount) {
                    await postSpiritualData('updateText', { field: 'amount', value: amount, table: 'spiritual_charity' }); 
                }
            }

            const data = await postSpiritualData('toggle', { table, field });
            if (data.success) {
                // Update Progress Bar smoothly
                const pb = document.getElementById('globalProgress');
                pb.style.width = data.progress + '%';
                pb.innerText = data.progress + '%';
                
                // Update Streaks Live & Consistency
                document.getElementById('s_perfect').innerText = data.streaks.perfect;
                document.getElementById('s_overall').innerText = data.streaks.overall;
                if(document.getElementById('consistencyDisplay')) {
                    document.getElementById('consistencyDisplay').innerText = data.consistency + '%';
                }
                
                // Update Dynamic Banner states smoothly
                const banner = document.getElementById('statusBanner');
                const title = document.getElementById('statusTextTitle');
                const msg = document.getElementById('statusTextMsg');
                const icon = document.getElementById('statusIcon');
                
                const stateMap = {
                    'high': {color: '#10b981', bg: '#d1fae5', icon: 'fa-leaf', text: 'مرتفع', msg: 'سكينة عالية، حافظ على هذه الروح الطيبة.'},
                    'medium': {color: '#f59e0b', bg: '#fef3c7', icon: 'fa-seedling', text: 'متوازن', msg: 'حالة متوازنة، ابحث عن المزيد من الطمأنينة.'},
                    'low': {color: '#6366f1', bg: '#e0e7ff', icon: 'fa-cloud', text: 'هادئ/منخفض', msg: 'لا بأس، كل يوم هو فرصة جديدة لتجديد النية.'}
                };

                const s = stateMap[data.state || 'medium'];
                
                banner.style.backgroundColor = s.bg;
                banner.style.color = s.color;
                icon.className = 'fa-solid ' + s.icon + ' me-3 fs-3';
                title.innerText = 'الحالة الروحية: ' + s.text;
                msg.innerText = s.msg;

                if (data.status === 'perfect') {
                    if(typeof OTIS !== 'undefined') OTIS.toast('يوم هادئ 🌟', 'تم إنجاز أهدافك الروحية بنجاح.', 'success');
                }
            } else if (data.error) {
                if(typeof OTIS !== 'undefined') OTIS.toast('خطأ', data.error, 'danger');
                e.target.checked = !e.target.checked; // Revert visually
            }
        });
    });

    // Text & Radios (Heart State, Tags, Goals)
    document.querySelectorAll('.ajax-string').forEach(el => {
        el.addEventListener('change', async (e) => {
            const field = e.target.getAttribute('data-field');
            const value = e.target.value;
            const res = await postSpiritualData('updateText', { field, value });
            if(res.error && typeof OTIS !== 'undefined') OTIS.toast('خطأ', res.error, 'danger');
        });
    });

    document.querySelectorAll('.ajax-input').forEach(el => {
        el.addEventListener('blur', async (e) => {
            const field = e.target.getAttribute('data-field');
            const value = e.target.value;
            const table = e.target.getAttribute('data-table') || 'spiritual_daily_logs';
            const res = await postSpiritualData('updateText', { field, value, table });
            if(res.error && typeof OTIS !== 'undefined') OTIS.toast('خطأ', res.error, 'danger');
        });
    });

    // Unselect Radio Buttons Logic
    document.querySelectorAll('input[type="radio"].ajax-string').forEach(radio => {
        // Initialize state
        if(radio.checked) radio.dataset.wasChecked = 'true';
        else radio.dataset.wasChecked = 'false';
        
        radio.addEventListener('click', async function(e) {
            if(this.dataset.wasChecked === 'true') {
                this.checked = false;
                this.dataset.wasChecked = 'false';
                // Trigger backend update with empty value
                const field = this.getAttribute('data-field');
                const res = await postSpiritualData('updateText', { field, value: '' });
                if(res.error && typeof OTIS !== 'undefined') OTIS.toast('خطأ', res.error, 'danger');
            } else {
                // Update all others in same group
                document.querySelectorAll(`input[name="${this.name}"]`).forEach(r => r.dataset.wasChecked = 'false');
                this.dataset.wasChecked = 'true';
            }
        });
    });
});
</script>
