<?php
// habits_icon_map for add-form
$iconOptions = [
    'fa-fire'         => '🔥 النار',
    'fa-dumbbell'     => '💪 رياضة',
    'fa-book-open'    => '📖 قراءة',
    'fa-brain'        => '🧠 تعلم',
    'fa-droplet'      => '💧 ماء',
    'fa-moon'         => '🌙 نوم',
    'fa-apple-whole'  => '🍎 تغذية',
    'fa-heart-pulse'  => '❤️ صحة',
    'fa-person-walking' => '🚶 مشي',
    'fa-sack-dollar'  => '💰 مالية',
    'fa-star'         => '⭐ عام',
];
$colorOptions = ['#0d6efd','#198754','#dc3545','#ffc107','#6f42c1','#0dcaf0','#fd7e14'];
?>
<script src="https://cdn.jsdelivr.net/npm/canvas-confetti@1.6.0/dist/confetti.browser.min.js"></script>

<!-- CSS for Smooth UX Animations -->
<style>
.habit-card {
    transition: all 0.3s ease, transform 0.2s ease;
    border-radius: 20px !important;
}
.habit-card:hover {
    transform: translateY(-8px);
    box-shadow: 0 15px 30px rgba(0,0,0,0.1) !important;
}
.identity-badge {
    background: linear-gradient(135deg, #6366f1, #a855f7);
    color: white;
}
.score-ticker {
    font-variant-numeric: tabular-nums;
    transition: color 0.5s ease;
}
.mini-heatmap {
    display: grid;
    grid-template-columns: repeat(15, 1fr);
    grid-gap: 2px;
    direction: ltr;
}
.heatmap-cell {
    width: 10px;
    height: 10px;
    border-radius: 2px;
    background: #e2e8f0;
}
body.dark-mode .heatmap-cell { background: #334155; }
</style>

<!-- Page Header & Identity Layer -->
<div class="row mb-5 align-items-center">
    <div class="col-md-8">
        <h1 class="h2 fw-bold mb-1"><i class="fa-solid fa-fire text-danger me-2"></i>نظام تنفيذ الانضباط (DES)</h1>
        <p class="fs-5 text-info fw-bold mb-0">
            <span id="global-identity-text"><?= $identityNarrative ?></span>
        </p>
    </div>
    <div class="col-md-4 text-md-end mt-3 mt-md-0 d-flex gap-3 justify-content-md-end align-items-center">
        <div class="text-center bg-white shadow-sm p-3 rounded-4 border">
            <small class="text-muted d-block fw-bold mb-1">نقاط الانضباط</small>
            <span class="fs-3 fw-bold text-primary score-ticker" id="global-score-val"><?= $disciplineScore ?>%</span>
        </div>
        <button class="btn btn-primary rounded-pill px-4 py-2 fw-bold shadow-sm" data-bs-toggle="modal" data-bs-target="#addHabitModal">
            <i class="fa-solid fa-plus me-1"></i> عادة جديدة
        </button>
    </div>
</div>

<?php if (empty($habits)): ?>
<div class="text-center py-5">
    <i class="fa-solid fa-fire fa-4x text-muted mb-3"></i>
    <h4 class="text-muted">ابدأ ببناء عاداتك اليومية</h4>
    <p class="text-secondary">أضف عادتك الأولى وابدأ رحلة التحسين المستمر.</p>
    <button class="btn btn-primary rounded-pill px-5 mt-2" data-bs-toggle="modal" data-bs-target="#addHabitModal">
        أضف عادتك الأولى ✨
    </button>
</div>
<?php else: ?>

<!-- Habits Grid -->
<div class="row g-4" id="habits-grid">
    <?php foreach ($habits as $h): ?>
    <?php $checked = (bool)$h->checked_today; ?>
    <div class="col-sm-6 col-lg-4 col-xl-3" id="habit-card-<?= $h->id ?>">
        <div class="card border-0 shadow-sm h-100 rounded-4 overflow-hidden habit-card <?= $checked ? 'border-success border-2' : '' ?>" style="border-top: 4px solid <?= htmlspecialchars($h->color_hex) ?> !important;">
            <div class="card-body d-flex flex-column p-4">
                <!-- Icon + Title -->
                <div class="d-flex align-items-center gap-3 mb-3">
                    <div class="rounded-circle d-flex align-items-center justify-content-center fs-4" style="width:48px;height:48px;background:<?= htmlspecialchars($h->color_hex) ?>22;">
                        <i class="fa-solid <?= htmlspecialchars($h->icon) ?>" style="color:<?= htmlspecialchars($h->color_hex) ?>"></i>
                    </div>
                    <div>
                        <h5 class="fw-bold mb-0"><?= htmlspecialchars($h->name) ?></h5>
                        <small class="text-muted"><?= $h->frequency === 'daily' ? 'يومية' : $h->frequency ?></small>
                    </div>
                </div>

                <!-- Streak & Status -->
                <div class="d-flex align-items-center justify-content-between mb-3">
                    <span class="badge fs-6 px-3 py-2 rounded-pill" style="background:<?= htmlspecialchars($h->color_hex) ?>22; color:<?= htmlspecialchars($h->color_hex) ?>">
                        🔥 <strong id="streak-<?= $h->id ?>"><?= $h->streak ?></strong> يوم
                    </span>
                    <div id="check-badge-<?= $h->id ?>">
                        <?php if ($checked): ?>
                            <span class="badge bg-success-subtle text-success rounded-pill px-3 py-2">✅ تم اليوم</span>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- 30-day mini heatmap grid -->
                <div class="mb-4">
                    <small class="text-muted d-block mb-1 fs-8 fw-bold">النشاط الأخير (30 يوم)</small>
                    <div class="mini-heatmap" id="heatmap-<?= $h->id ?>">
                        <?php
                        for ($i = 29; $i >= 0; $i--):
                            $d = date('Y-m-d', strtotime("-{$i} days"));
                            $hasLog = isset($recentLogs[$h->id][$d]);
                        ?>
                        <div title="<?= $d ?>" class="heatmap-cell" style="<?= $hasLog ? 'background:'.htmlspecialchars($h->color_hex) : '' ?>" data-date="<?= $d ?>"></div>
                        <?php endfor; ?>
                    </div>
                </div>

                <!-- Action -->
                <div class="mt-auto d-flex gap-2" id="action-btns-<?= $h->id ?>">
                    <?php if (!$checked): ?>
                    <button class="btn btn-sm fw-bold flex-grow-1 rounded-pill btn-checkin" 
                            style="background:<?= htmlspecialchars($h->color_hex) ?>;color:#fff"
                            onclick="habitCheckin(<?= $h->id ?>, false, this, '<?= htmlspecialchars($h->color_hex) ?>')">
                        <i class="fa-solid fa-check me-1"></i> تمت
                    </button>
                    <?php else: ?>
                    <button class="btn btn-outline-secondary btn-sm flex-grow-1 rounded-pill btn-undo"
                            onclick="habitCheckin(<?= $h->id ?>, true, this, '<?= htmlspecialchars($h->color_hex) ?>')">
                        <i class="fa-solid fa-rotate-left me-1"></i> تراجع
                    </button>
                    <?php endif; ?>
                    <button class="btn btn-sm btn-outline-danger rounded-pill" onclick="deleteHabit(<?= $h->id ?>)">
                        <i class="fa-solid fa-trash"></i>
                    </button>
                </div>
            </div>
        </div>
    </div>
    <?php endforeach; ?>
</div>
<?php endif; ?>

<!-- Add Habit Modal -->
<div class="modal fade" id="addHabitModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content rounded-4 border-0 shadow">
            <div class="modal-header border-0 pb-0">
                <h5 class="modal-title fw-bold">إضافة عادة جديدة</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form action="<?= BASE_URL ?>/habits/store" method="POST">
                <input type="hidden" name="csrf_token" value="<?= generate_csrf_token() ?>">
                <div class="modal-body pt-3">
                    <div class="row g-3">
                        <div class="col-md-12">
                            <label class="form-label fw-bold">ما هي الهوية التي تود تعزيزها؟</label>
                            <input type="text" name="identity_statement" class="form-control rounded-3" placeholder="مثال: أنا شخص رياضي، أنا شخص مقتصد..." required>
                        </div>
                        <div class="col-md-8">
                            <label class="form-label fw-bold">اسم العادة</label>
                            <input type="text" name="name" class="form-control rounded-3" placeholder="مثال: قراءة 30 صفحة" required>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label fw-bold">النوع</label>
                            <select name="habit_type" class="form-select rounded-3">
                                <option value="build">بناء عادة (+)</option>
                                <option value="break">كسر عادة (-)</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-bold">الأيقونة</label>
                            <select name="icon" class="form-select rounded-3">
                                <?php foreach ($iconOptions as $val => $label): ?>
                                <option value="<?= $val ?>"><?= $label ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-bold">الأولوية/الكثافة</label>
                            <select name="intensity" class="form-select rounded-3">
                                <option value="1">عادية (1x)</option>
                                <option value="2">متوسطة (2x)</option>
                                <option value="3">عالية (3x)</option>
                                <option value="5">جوهرية (5x)</option>
                            </select>
                        </div>
                        
                        <hr class="my-2 opacity-25">
                        <h6 class="fw-bold text-primary mb-0"><i class="fa-solid fa-chart-line me-1"></i> القياس والتأثير</h6>
                        
                        <div class="col-md-4">
                            <label class="form-label small fw-bold">الهدف الرقمي</label>
                            <input type="number" name="target_value" class="form-control rounded-3" value="0">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label small fw-bold">الوحدة</label>
                            <input type="text" name="unit" class="form-control rounded-3" placeholder="كم، لتر، صفحة">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label small fw-bold">اللون</label>
                            <div class="d-flex flex-wrap gap-1">
                                <?php foreach ($colorOptions as $i => $clr): ?>
                                <label class="d-flex align-items-center justify-content-center rounded-circle cursor-pointer" style="width:28px;height:28px;background:<?= $clr ?>;cursor:pointer">
                                    <input type="radio" name="color_hex" value="<?= $clr ?>" class="visually-hidden" <?= $i===0?'checked':'' ?>>
                                    <i class="fa-solid fa-check text-white" style="font-size:0.6rem;opacity:<?= $i===0?'1':'0' ?>"></i>
                                </label>
                                <?php endforeach; ?>
                            </div>
                        </div>

                        <div class="col-md-6">
                            <label class="form-label small fw-bold">مجال التأثير</label>
                            <select name="impact_category" class="form-select rounded-3">
                                <option value="general">عام</option>
                                <option value="finance">مالي (توفير/صرف)</option>
                                <option value="health">صحي (حيوية)</option>
                                <option value="productivity">إنتاجي</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label small fw-bold">قيمة التأثير</label>
                            <input type="number" step="0.01" name="impact_amount" class="form-control rounded-3" value="0">
                        </div>
                    </div>
                </div>
                <div class="modal-footer border-0">
                    <button type="button" class="btn btn-light rounded-pill" data-bs-dismiss="modal">إلغاء</button>
                    <button type="submit" class="btn btn-primary rounded-pill px-4">إضافة العادة</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
const BASE = '<?= BASE_URL ?>';
const CSRF = '<?= generate_csrf_token() ?>';

// Success Sound
const successSound = new Audio('https://assets.mixkit.co/active_storage/sfx/2013/success-fanfare-trumpets-618.wav');
successSound.volume = 0.2;

async function habitCheckin(id, undo, btn, colorHex) {
    btn.disabled = true;
    const res = await fetch(`${BASE}/habits/checkin`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ habit_id: id, undo: undo, csrf_token: CSRF })
    });
    const data = await res.json();
    
    if (data.success) {
        // Ticker Animation for Global Score
        const scoreEl = document.getElementById('global-score-val');
        if (scoreEl) {
            scoreEl.classList.add('text-success');
            scoreEl.innerText = data.newScore + '%';
            setTimeout(() => scoreEl.classList.remove('text-success'), 1000);
        }

        // Streak Update
        const streakEl = document.getElementById('streak-' + id);
        if (streakEl) streakEl.textContent = data.streak;
        
        const card = document.getElementById('habit-card-' + id).querySelector('.habit-card');
        const badgeContainer = document.getElementById('check-badge-' + id);
        const actionBtns = document.getElementById('action-btns-' + id);
        const heatmap = document.getElementById('heatmap-' + id);
        const lastCell = heatmap.querySelector('.heatmap-cell:last-child');

        if (!undo) {
            // Success Feedback
            confetti({
                particleCount: 100, spread: 70, origin: { y: 0.6 },
                colors: [colorHex, '#ffffff']
            });
            successSound.play().catch(() => {}); // ignore if blocked by browser
            
            card.classList.add('border-success', 'border-2');
            badgeContainer.innerHTML = `<span class="badge bg-success-subtle text-success rounded-pill px-3 py-2 checkin-badge">✅ تم اليوم</span>`;
            if(lastCell) lastCell.style.background = colorHex;
            
            actionBtns.innerHTML = `
                <button class="btn btn-outline-secondary btn-sm flex-grow-1 rounded-pill" onclick="habitCheckin(${id}, true, this, '${colorHex}')">
                    <i class="fa-solid fa-rotate-left me-1"></i> تراجع
                </button>
                <button class="btn btn-sm btn-outline-danger rounded-pill" onclick="deleteHabit(${id})"><i class="fa-solid fa-trash"></i></button>`;
            
            if(typeof OTIS !== 'undefined') OTIS.toast('🎉 ' + data.message, 'رائع!', 'success');
        } else {
            card.classList.remove('border-success', 'border-2');
            badgeContainer.innerHTML = '';
            if(lastCell) lastCell.style.background = '';
            
            actionBtns.innerHTML = `
                <button class="btn btn-sm fw-bold flex-grow-1 rounded-pill btn-checkin" style="background:${colorHex};color:#fff" onclick="habitCheckin(${id}, false, this, '${colorHex}')">
                    <i class="fa-solid fa-check me-1"></i> تمت
                </button>
                <button class="btn btn-sm btn-outline-danger rounded-pill" onclick="deleteHabit(${id})"><i class="fa-solid fa-trash"></i></button>`;
        }
    } else {
        btn.disabled = false;
        if(typeof OTIS !== 'undefined') OTIS.toast('خطأ', 'حدث خطأ أثناء الاتصال.', 'danger');
    }
}

async function deleteHabit(id) {
    if (!confirm('سيتم حذف هذه العادة وسجلاتها. متأكد؟')) return;
    const res = await fetch(`${BASE}/habits/delete`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ habit_id: id })
    });
    const data = await res.json();
    if (data.success) {
        const card = document.getElementById('habit-card-' + id);
        if (card) { card.style.opacity = 0; setTimeout(() => card.remove(), 300); }
    }
}

// Color picker highlight
document.querySelectorAll('input[name="color_hex"]').forEach(r => {
    r.addEventListener('change', () => {
        document.querySelectorAll('input[name="color_hex"]').forEach(x => {
            x.parentElement.querySelector('i').style.opacity = x.checked ? '1' : '0';
        });
    });
});
</script>
