<?php
namespace App\Modules\Journal\Models;

class JournalModel extends \Core\Model {
    // Journal entries are keyed by (user_id, date). No soft delete — upsert pattern only.
    protected $useSoftDeletes = false;
    protected $logActions = false;

    /**
     * Get today's journal entry for a user
     */
    public function getTodayEntry($userId, $date = null) {
        if (!$date) $date = date('Y-m-d');
        $sql = "SELECT * FROM daily_journal WHERE user_id = ? AND date = ? LIMIT 1";
        return $this->db->query($sql, [$userId, $date])->fetch(\PDO::FETCH_OBJ);
    }

    /**
     * Upsert a journal entry (create or update for today)
     */
    public function saveEntry($userId, $data) {
        $date = $data['date'] ?? date('Y-m-d');
        $existing = $this->getTodayEntry($userId, $date);

        if ($existing) {
            $sql = "UPDATE daily_journal 
                    SET mood = ?, energy_level = ?, achieved = ?, failed = ?, notes = ?, updated_at = NOW()
                    WHERE user_id = ? AND date = ?";
            $this->db->query($sql, [
                $data['mood'] ?? 3,
                $data['energy_level'] ?? 3,
                $data['achieved'] ?? null,
                $data['failed'] ?? null,
                $data['notes'] ?? null,
                $userId,
                $date
            ]);
            return $existing->id;
        } else {
            $sql = "INSERT INTO daily_journal (user_id, date, mood, energy_level, achieved, failed, notes, created_at, updated_at)
                    VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), NOW())";
            $this->db->query($sql, [
                $userId,
                $date,
                $data['mood'] ?? 3,
                $data['energy_level'] ?? 3,
                $data['achieved'] ?? null,
                $data['failed'] ?? null,
                $data['notes'] ?? null
            ]);
            return $this->db->lastInsertId();
        }
    }

    /**
     * Get last N entries for summary/advisor
     */
    public function getRecentEntries($userId, $days = 7) {
        $sql = "SELECT * FROM daily_journal 
                WHERE user_id = ? AND date >= DATE_SUB(CURDATE(), INTERVAL ? DAY)
                ORDER BY date DESC";
        return $this->db->query($sql, [$userId, $days])->fetchAll(\PDO::FETCH_OBJ);
    }

    /**
     * Get average mood/energy for advisor integration
     */
    public function getAverages($userId, $days = 3) {
        $sql = "SELECT 
                    AVG(mood) as avg_mood, 
                    AVG(energy_level) as avg_energy,
                    COUNT(*) as entry_count
                FROM daily_journal 
                WHERE user_id = ? AND date >= DATE_SUB(CURDATE(), INTERVAL ? DAY)";
        return $this->db->query($sql, [$userId, $days])->fetch(\PDO::FETCH_OBJ);
    }
}
