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

class HealthLog extends \Core\Model {
    protected $table = 'health_daily_logs';
    protected $moduleName = 'Health';

    public function getTodayLog($userId) {
        $today = date('Y-m-d');
        $stmt = $this->query("SELECT * FROM {$this->table} WHERE user_id = ? AND log_date = ? AND deleted_at IS NULL", [$userId, $today]);
        return $stmt->fetch();
    }

    public function upsertToday($userId, $data) {
        $today = date('Y-m-d');
        $existing = $this->getTodayLog($userId);
        
        if ($existing) {
            $sql = "UPDATE {$this->table} SET weight=?, blood_sugar=?, fasting_hours=?, food_streak_kept=?, water_cups=?, activity_minutes=?, medications_taken=?, notes=? WHERE id=?";
            $this->query($sql, [
                $data['weight'] ?: null, 
                $data['blood_sugar'] ?: null, 
                $data['fasting_hours'] ?: 0, 
                $data['food_streak_kept'], 
                $data['water_cups'] ?: 0, 
                $data['activity_minutes'] ?: 0, 
                $data['medications_taken'], 
                $data['notes'] ?: null, 
                $existing->id
            ]);
        } else {
            $sql = "INSERT INTO {$this->table} (user_id, log_date, weight, blood_sugar, fasting_hours, food_streak_kept, water_cups, activity_minutes, medications_taken, notes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            $this->query($sql, [
                $userId, $today, 
                $data['weight'] ?: null, 
                $data['blood_sugar'] ?: null, 
                $data['fasting_hours'] ?: 0, 
                $data['food_streak_kept'], 
                $data['water_cups'] ?: 0, 
                $data['activity_minutes'] ?: 0, 
                $data['medications_taken'],
                $data['notes'] ?: null
            ]);
        }
    }

    // Calculate Food Tracking Streak (Consecutive days food_streak_kept = 1)
    public function getFoodStreak($userId) {
        $stmt = $this->query("SELECT log_date, food_streak_kept FROM {$this->table} WHERE user_id = ? AND deleted_at IS NULL ORDER BY log_date DESC", [$userId]);
        $logs = $stmt->fetchAll();
        
        $streak = 0;
        $expectedDate = new DateTime();
        $expectedDate->setTime(0,0,0);
        
        foreach($logs as $log) {
            $logDate = new DateTime($log->log_date);
            $logDate->setTime(0,0,0);
            
            // Skip future logs if any exist
            if ($logDate > $expectedDate) continue; 
            
            // If there's a gap in days, streak is broken, 
            // UNLESS the gap is just today (they haven't logged today yet)
            $diff = $expectedDate->diff($logDate)->days;
            
            if ($diff > 1 || ($diff == 1 && $streak > 0)) {
                break; 
            }
            
            if ($log->food_streak_kept) {
                $streak++;
                $expectedDate->modify('-1 day');
            } else {
                break; // Broken streak recorded in logs
            }
        }
        return $streak;
    }

    // Calculate how much weight lost this month vs start weight
    public function getMonthlyWeightLost($userId, $startWeight) {
        $monthStart = date('Y-m-01');
        $stmt = $this->query("SELECT weight FROM {$this->table} WHERE user_id = ? AND log_date >= ? AND weight IS NOT NULL AND deleted_at IS NULL ORDER BY log_date DESC LIMIT 1", [$userId, $monthStart]);
        $latest = $stmt->fetch();
        
        if ($latest && $latest->weight > 0 && $startWeight > 0) {
            return $startWeight - $latest->weight;
        }
        return 0;
    }
}
