<div class="container-fluid command-center-wrapper">
    <!-- Header -->
    <div class="row mb-4 align-items-center">
        <div class="col-md-6">
            <h2 class="fw-bold mb-0 text-primary"><i class="fa-solid fa-bolt me-2 text-warning"></i> دفتر اليومية الذكي</h2>
            <p class="text-muted mb-0">مركز القيادة اليومي وتسجيل الإنجازات</p>
        </div>
        <div class="col-md-6 text-md-end mt-3 mt-md-0">
            <a href="<?= BASE_URL ?>/journal/timeline" class="btn btn-outline-primary btn-premium rounded-pill px-4 shadow-sm mb-3 d-inline-block">
                <i class="fa-solid fa-timeline me-1"></i> أرشيف اليوميات
            </a>
            <h4 class="mb-0 fw-bold d-inline-block ms-3" id="dailyDate"><?= date('l, d F Y') ?></h4>
            <div class="progress mt-2 shadow-sm rounded-pill bg-white" style="height: 10px;">
                <div id="dailyProgressBar" class="progress-bar bg-success rounded-pill" style="width: 0%;"></div>
            </div>
            <small class="text-muted" id="dailyProgressText">التقدم اليومي: 0%</small>
        </div>
    </div>

    <div class="row g-4">
        <!-- Center Column: Core Inputs & Tracking -->
        <div class="col-lg-8">
            
            <!-- Tasks Module -->
            <div class="card card-saas border-0 shadow-sm mb-4">
                <div class="card-header bg-white border-0 pt-4 pb-0 d-flex justify-content-between align-items-center">
                    <h5 class="fw-bold mb-0"><i class="fa-solid fa-list-check text-primary me-2"></i> المهام والإنجازات</h5>
                </div>
                <div class="card-body">
                    <form onsubmit="cmdAddRow('Todo', 'addTask', {title: this.title.value}); this.reset(); return false;" class="d-flex gap-2 mb-3">
                        <input type="text" name="title" class="form-control bg-light border-0" placeholder="ماذا أنجزت أو تريد إنجازه؟" required autocomplete="off">
                        <button type="submit" class="btn btn-primary px-4"><i class="fa-solid fa-plus"></i></button>
                    </form>
                    <div id="todoList" class="d-flex flex-column gap-2">
                        <?php foreach($tasks as $t): ?>
                            <?php if($t->status !== 'done'): ?>
                            <div class="p-3 bg-light rounded d-flex justify-content-between align-items-center cmd-item">
                                <span><?= htmlspecialchars($t->title) ?></span>
                                <button onclick="cmdAction('Todo', 'completeTask', {id: <?= $t->id ?>}, this)" class="btn btn-sm btn-outline-success rounded-circle"><i class="fa-solid fa-check"></i></button>
                            </div>
                            <?php endif; ?>
                        <?php endforeach; ?>
                        <?php if(empty(array_filter($tasks, fn($t)=>$t->status !== 'done'))): ?>
                            <p class="text-muted text-center mb-0 small" id="noTasksMsg">لا توجد مهام معلقة.</p>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Behavior Tracking -->
            <div class="card card-saas border-0 shadow-sm mb-4 border-end border-warning border-4">
                <div class="card-header bg-white border-0 pt-4 pb-0">
                    <h5 class="fw-bold mb-0"><i class="fa-solid fa-brain text-warning me-2"></i> تتبع السلوكيات</h5>
                </div>
                <div class="card-body">
                    <div class="row g-3">
                        <?php foreach($behaviors as $b): ?>
                        <div class="col-md-6">
                            <div class="px-3 py-2 <?= ($b->today_status == 1) ? 'bg-danger bg-opacity-10 border border-danger' : 'bg-light' ?> rounded d-flex justify-content-between align-items-center cmd-item transition-all">
                                <div class="d-flex flex-column">
                                    <span class="fw-bold fs-7 <?= ($b->today_status == 1) ? 'text-danger' : 'text-dark' ?>"><?= htmlspecialchars($b->name) ?></span>
                                    <small class="text-muted" style="font-size: 0.65rem;">صمود: <?= $b->current_streak ?> أيام</small>
                                </div>
                                <div>
                                    <?php if($b->today_status == 1): ?>
                                        <!-- It is logged as a fail today. Clicking will undo it (status: 0) -->
                                        <button onclick="if(confirm('هل تريد إلغاء تسجيل الإخفاق؟')) cmdAction('Behavior', 'toggleLog', {id: <?= $b->id ?>, status: 0}, this, false)" class="btn btn-sm btn-danger fw-bold px-3 lh-sm"><i class="fa-solid fa-triangle-exclamation d-block mb-1"></i> زلّة</button>
                                    <?php else: ?>
                                        <!-- Clean today. Clicking will log a fail (status: 1) -->
                                        <button onclick="cmdAction('Behavior', 'toggleLog', {id: <?= $b->id ?>, status: 1}, this, false)" class="btn btn-sm btn-outline-secondary fw-bold px-3 lh-sm" title="اضغط هنا إذا وقعت في هذا السلوك اليوم"><i class="fa-solid fa-shield-halved d-block mb-1"></i> نظيف</button>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>

            <!-- Health & Education Row -->
            <div class="row g-4 mb-4">
                <!-- Health Module -->
                <div class="col-md-6">
                    <div class="card card-saas border-0 shadow-sm h-100">
                        <div class="card-header bg-white border-0 pt-4 pb-0">
                            <h5 class="fw-bold mb-0"><i class="fa-solid fa-heart-pulse text-danger me-2"></i> الصحة والنشاط</h5>
                        </div>
                        <div class="card-body">
                            <form onsubmit="cmdAddRow('Health', 'addMeal', {description: this.description.value}); this.reset(); return false;" class="mb-3">
                                <div class="input-group">
                                    <input type="text" name="description" class="form-control bg-light border-0 text-sm" placeholder="ماذا أكلت؟ (وجبة)" required autocomplete="off">
                                    <button class="btn btn-danger text-white"><i class="fa-solid fa-utensils"></i></button>
                                </div>
                            </form>
                            <form onsubmit="cmdAddRow('Health', 'addActivity', {duration: this.duration.value, type: this.type.value}); this.reset(); return false;">
                                <div class="input-group">
                                    <select name="type" class="form-select bg-light border-0 text-sm" style="max-width: 120px;">
                                        <option value="Cardio">كارديو</option>
                                        <option value="Walking">مشي</option>
                                        <option value="Workout">تمرين</option>
                                    </select>
                                    <input type="number" name="duration" class="form-control bg-light border-0 text-sm" placeholder="دقائق" required>
                                    <button class="btn btn-danger text-white"><i class="fa-solid fa-person-running"></i></button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
                
                <!-- Education Module -->
                <div class="col-md-6">
                    <div class="card card-saas border-0 shadow-sm h-100">
                        <div class="card-header bg-white border-0 pt-4 pb-0">
                            <h5 class="fw-bold mb-0"><i class="fa-solid fa-graduation-cap text-info me-2"></i> التعلم والنمو</h5>
                        </div>
                        <div class="card-body">
                            <form onsubmit="cmdAddRow('Education', 'addLearning', {title: this.title.value}); this.reset(); return false;">
                                <div class="input-group">
                                    <input type="text" name="title" class="form-control bg-light border-0 text-sm" placeholder="ماذا تعلمت اليوم؟" required autocomplete="off">
                                    <button class="btn btn-info text-white"><i class="fa-solid fa-book"></i></button>
                                </div>
                            </form>
                            <div class="mt-3 text-center">
                                <p class="small text-muted mb-0">سيسجل كدورة "تعليم عام" مكتملة.</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Notes & Feelings -->
            <div class="card card-saas border-0 shadow-sm mb-4">
                <div class="card-header bg-white border-0 pt-4 pb-0">
                    <h5 class="fw-bold mb-0"><i class="fa-solid fa-feather text-secondary me-2"></i> أفكار وملاحظات</h5>
                </div>
                <div class="card-body">
                    <textarea id="journalNotes" class="form-control bg-light border-0" rows="4" placeholder="اكتب عذرك، إنجازك، أو مشاعرك بتفصيل..." onblur="saveJournalNotes()"><?= htmlspecialchars($todayJournal->notes ?? '') ?></textarea>
                </div>
            </div>

            <!-- History / Timeline (NEW LAYER) -->
            <div class="card card-saas border-0 shadow-sm mb-4 bg-light bg-opacity-50">
                <div class="card-header bg-transparent border-0 pt-4 pb-0">
                    <h5 class="fw-bold mb-0 text-secondary"><i class="fa-solid fa-clock-rotate-left me-2"></i> شريط الذكريات القريب</h5>
                </div>
                <div class="card-body">
                    <?php if (empty($recentEntries) || count($recentEntries) <= 1): ?>
                        <p class="text-muted small mb-0 text-center">لا توجد سجلات سابقة قريبة ليتم عرضها.</p>
                    <?php else: ?>
                        <div class="d-flex flex-column gap-3">
                            <?php foreach ($recentEntries as $entry): 
                                if ($entry->date === date('Y-m-d')) continue; // skip today
                                $moodIcons = ['', '😞', '😕', '😐', '😊', '🌟'];
                                $mIcon = $moodIcons[$entry->mood] ?? '😐';
                            ?>
                            <div class="bg-white p-3 rounded-3 shadow-sm border-start border-3" style="border-color: <?= $entry->mood >= 4 ? '#198754' : ($entry->mood <= 2 ? '#dc3545' : '#ffc107') ?> !important">
                                <div class="d-flex justify-content-between align-items-center mb-2">
                                    <span class="fw-bold text-dark fs-7"><?= date('l, d M', strtotime($entry->date)) ?></span>
                                    <span class="fs-5" title="المزاج"><?= $mIcon ?></span>
                                </div>
                                <p class="mb-0 text-secondary small text-truncate" style="max-height: 40px; overflow: hidden;">
                                    <?= htmlspecialchars($entry->notes ?: ($entry->achieved ?: 'لا توجد ملاحظات..')) ?>
                                </p>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

        </div> <!-- End Center Column -->

        <!-- Side Column: Finances & Bio -->
        <div class="col-lg-4">
            
            <!-- Quick Mood / Energy -->
            <div class="card card-saas border-0 shadow-sm mb-4 bg-primary text-white text-center pb-2">
                <div class="card-body pb-0">
                    <h5 class="fw-bold"><i class="fa-solid fa-battery-half me-2"></i> حاستي اليوم</h5>
                    <div class="row mt-4">
                        <div class="col-6">
                            <label class="small text-white-50 d-block mb-2">الطاقة</label>
                            <select id="journalEnergy" class="form-select bg-white bg-opacity-25 text-white border-0 text-center fw-bold" onchange="saveJournalNotes()">
                                <?php for($i=1; $i<=5; $i++): ?>
                                    <option value="<?= $i ?>" <?= ($todayJournal->energy_level ?? 3) == $i ? 'selected' : '' ?> class="text-dark"><?= $i ?>/5</option>
                                <?php endfor; ?>
                            </select>
                        </div>
                        <div class="col-6">
                            <label class="small text-white-50 d-block mb-2">المزاج</label>
                            <select id="journalMood" class="form-select bg-white bg-opacity-25 text-white border-0 text-center fw-bold" onchange="saveJournalNotes()">
                                <?php for($i=1; $i<=5; $i++): ?>
                                    <option value="<?= $i ?>" <?= ($todayJournal->mood ?? 3) == $i ? 'selected' : '' ?> class="text-dark"><?= $i ?>/5</option>
                                <?php endfor; ?>
                            </select>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Light Analytics (Trends) -->
            <div class="card card-saas border-0 shadow-sm mb-4 bg-light bg-opacity-50">
                <div class="card-body">
                    <h6 class="fw-bold text-secondary mb-3"><i class="fa-solid fa-chart-line me-2"></i> مؤشرات آخر 30 يوم</h6>
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <span class="small fw-bold">المزاج</span>
                        <span class="badge bg-<?= $moodTrend >= 3 ? 'success' : 'warning' ?>"><?= $moodTrend ?> / 5</span>
                    </div>
                    <div class="progress mb-3" style="height: 6px;">
                        <div class="progress-bar bg-<?= $moodTrend >= 3 ? 'success' : 'warning' ?>" style="width: <?= ($moodTrend / 5) * 100 ?>%"></div>
                    </div>

                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <span class="small fw-bold">الطاقة</span>
                        <span class="badge bg-<?= $energyTrend >= 3 ? 'primary' : 'warning' ?>"><?= $energyTrend ?> / 5</span>
                    </div>
                    <div class="progress" style="height: 6px;">
                        <div class="progress-bar bg-<?= $energyTrend >= 3 ? 'primary' : 'warning' ?>" style="width: <?= ($energyTrend / 5) * 100 ?>%"></div>
                    </div>
                </div>
            </div>

            <!-- Finance Module -->
            <div class="card card-saas border-0 shadow-sm mb-4">
                <div class="card-header bg-white border-0 pt-4 pb-0">
                    <h5 class="fw-bold mb-0"><i class="fa-solid fa-wallet text-success me-2"></i> المالية</h5>
                </div>
                <div class="card-body">
                    <!-- Income -->
                    <form onsubmit="cmdAddRow('Finance', 'addIncome', {amount: this.amount.value, source: this.source.value}, this); return false;" class="mb-3">
                        <label class="small text-success fw-bold mb-1">+ إضافة دخل</label>
                        <div class="input-group">
                            <input type="text" name="source" class="form-control bg-light border-0 text-sm" placeholder="المصدر" required autocomplete="off">
                            <input type="number" name="amount" class="form-control bg-light border-0 text-sm w-25" placeholder="المبلغ" required>
                            <button type="submit" class="btn btn-success text-white"><i class="fa-solid fa-plus"></i></button>
                        </div>
                    </form>
                    <hr class="border-secondary opacity-25">
                    <!-- Expense -->
                    <form onsubmit="cmdAddRow('Finance', 'addExpense', {amount: this.amount.value, category: this.category.value}, this); return false;">
                        <label class="small text-danger fw-bold mb-1">- إضافة مصروف</label>
                        <div class="input-group">
                            <input type="text" name="category" class="form-control bg-light border-0 text-sm" placeholder="السبب/التصنيف" required autocomplete="off">
                            <input type="number" name="amount" class="form-control bg-light border-0 text-sm w-25" placeholder="المبلغ" required>
                            <button type="submit" class="btn btn-danger text-white"><i class="fa-solid fa-minus"></i></button>
                        </div>
                    </form>
                </div>
            </div>

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

<style>
.command-center-wrapper { max-width: 1400px; margin: 0 auto; }
.cmd-item { transition: all 0.3s ease; }
.cmd-item.fade-out { opacity: 0; transform: scale(0.95); }
.text-sm { font-size: 0.9rem; }
input:focus, select:focus, textarea:focus { box-shadow: none !important; background-color: #fff !important; }
</style>

<script>
let completedActions = 0;
let totalActions = <?= count($tasks) > 0 ? count($tasks) : 1 ?>; // Base off tasks for progress

function updateProgress() {
    let pct = Math.min(100, Math.round((completedActions / totalActions) * 100));
    document.getElementById('dailyProgressBar').style.width = pct + '%';
    document.getElementById('dailyProgressText').innerText = `التقدم اليومي: ${pct}%`;
}

function showToast(msg, type='success') {
    let icon = type === 'success' ? 'fa-check-circle' : 'fa-info-circle';
    let bg = type === 'success' ? 'bg-success' : 'bg-primary';
    let html = `
    <div class="toast align-items-center text-white ${bg} border-0 shadow-lg position-fixed top-0 start-50 translate-middle-x mt-4" role="alert" aria-live="assertive" aria-atomic="true" style="z-index: 9999;">
      <div class="d-flex">
        <div class="toast-body fw-bold"><i class="fa-solid ${icon} me-2"></i> ${msg}</div>
      </div>
    </div>`;
    document.body.insertAdjacentHTML('beforeend', html);
    const tel = document.body.lastElementChild;
    const toast = new bootstrap.Toast(tel, {delay: 2000});
    toast.show();
    setTimeout(() => tel.remove(), 2500);
}

function cmdAction(module, action, data, btnElement = null, isRow = true) {
    if(btnElement) {
        btnElement.disabled = true;
        btnElement.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i>';
    }
    
    fetch('<?= BASE_URL ?>/journal/executeCmd', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ module: module, action: action, data: data })
    }).then(res => res.json()).then(res => {
        if(res.success) {
            if(btnElement && isRow) {
                let row = btnElement.closest('.cmd-item');
                row.classList.add('fade-out');
                setTimeout(() => row.remove(), 300);
                
                completedActions++;
                updateProgress();
            }
            showToast(res.message);
        } else {
            showToast('حدث خطأ', 'error');
            if(btnElement) {
                btnElement.disabled = false;
                btnElement.innerHTML = '<i class="fa-solid fa-check"></i>';
            }
        }
    });
}

function cmdAddRow(module, action, data, formElement = null) {
    fetch('<?= BASE_URL ?>/journal/executeCmd', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ module: module, action: action, data: data })
    }).then(res => res.json()).then(res => {
        if(res.success) {
            completedActions++;
            totalActions++;
            updateProgress();
            showToast(res.message);
            if(formElement) formElement.reset();
            
            // If it's a task, add to UI visually
            if(module === 'Todo') {
                let noMsg = document.getElementById('noTasksMsg');
                if(noMsg) noMsg.remove();
                
                let list = document.getElementById('todoList');
                let html = `
                <div class="p-3 bg-light rounded d-flex justify-content-between align-items-center cmd-item">
                    <span>${data.title}</span>
                    <button onclick="cmdAction('Todo', 'completeTask', {id: ${res.new_id}}, this)" class="btn btn-sm btn-outline-success rounded-circle"><i class="fa-solid fa-check"></i></button>
                </div>`;
                list.insertAdjacentHTML('afterbegin', html);
            }
        }
    });
}

let journalTimeout;
function saveJournalNotes() {
    clearTimeout(journalTimeout);
    journalTimeout = setTimeout(() => {
        const data = {
            notes: document.getElementById('journalNotes').value,
            mood: document.getElementById('journalMood').value,
            energy_level: document.getElementById('journalEnergy').value,
            achieved: '', // Legacy columns
            failed: ''    // Legacy columns
        };
        fetch('<?= BASE_URL ?>/journal/save', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(data)
        }).then(res => res.json()).then(res => {
            if(res.success) {
                showToast('تم حفظ اليومية ✔️');
            }
        });
    }, 1000);
}
</script>
