<?php

namespace App\Http\Controllers\OrangTua;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use App\Models\ActivityLog;
use App\Models\Recommendation;
use Carbon\Carbon;

class ChildVisualizationController extends Controller
{
    public function index(Request $request, $childId)
    {
        $user = Auth::user();
        
        // Pastikan anak terhubung dengan orang tua ini
        $child = User::where('parent_id', $user->id)
            ->findOrFail($childId);
        
        $period = $request->get('period', 7);
        if (!in_array($period, [7, 30, 90])) {
            $period = 7;
        }
        
        $startDate = Carbon::today()->subDays($period);
        
        // Ambil data aktivitas - INI YANG DIBUTUHKAN
        $activities = ActivityLog::where('user_id', $child->id)
            ->whereDate('activity_date', '>=', $startDate)
            ->orderBy('activity_date', 'asc')
            ->get();
        
        // Ambil data rekomendasi untuk periode yang sama
        $recommendations = Recommendation::where('user_id', $child->id)
            ->whereDate('recommendation_date', '>=', $startDate)
            ->get()
            ->keyBy(function($item) {
                return $item->recommendation_date instanceof Carbon 
                    ? $item->recommendation_date->format('Y-m-d')
                    : Carbon::parse($item->recommendation_date)->format('Y-m-d');
            });
        
        // Siapkan data untuk chart
        $dates = [];
        $durations = [];
        $moods = [];
        $sleep_hours = [];
        $categories = [];
        
        // Statistik mood counter
        $moodCount = [
            'Bagus' => 0,
            'Lumayan' => 0,
            'Biasa Saja' => 0,
            'Cukup Jenuh' => 0,
            'Jenuh' => 0
        ];
        
        foreach ($activities as $activity) {
            $dateKey = $activity->activity_date instanceof Carbon 
                ? $activity->activity_date->format('Y-m-d')
                : Carbon::parse($activity->activity_date)->format('Y-m-d');
            
            $dates[] = $dateKey;
            $durations[] = $activity->duration_minutes;
            $moods[] = $activity->mood;
            
            // Increment mood counter
            if (isset($moodCount[$activity->mood])) {
                $moodCount[$activity->mood]++;
            }
            
            // Sleep hours - handle both column names
            $sleep_hours[] = $activity->sleep_duration ?? $activity->sleep_hours ?? 7;
            
            // Cari rekomendasi berdasarkan tanggal
            if (isset($recommendations[$dateKey])) {
                $categories[] = $recommendations[$dateKey]->category;
            } else {
                $categories[] = null;
            }
        }
        
        // Hitung statistik
        $stats = [
            'total_hari' => $activities->count(),
            'rata_durasi' => $activities->count() > 0 ? round($activities->avg('duration_minutes')) : 0,
            'mood_terbanyak' => $this->getMostFrequentMood($moodCount),
            'konsistensi' => $period > 0 ? round(($activities->count() / $period) * 100) : 0,
            'total_durasi' => array_sum($durations),
            'rata_tidur' => count($sleep_hours) > 0 ? round(array_sum($sleep_hours) / count($sleep_hours), 1) : 0,
        ];
        
        // Hitung distribusi mood untuk chart
        $moodDistribution = array_filter($moodCount, function($count) {
            return $count > 0;
        });
        
        return view('orangtua.child-visualization', compact(
            'child',
            'period',
            'dates',
            'durations',
            'moods',
            'sleep_hours',
            'categories',
            'stats',
            'moodDistribution',
            'activities' // TAMBAHKAN INI!
        ));
    }
    
    private function getMostFrequentMood($moodCount)
    {
        if (empty($moodCount) || max($moodCount) == 0) {
            return '-';
        }
        
        arsort($moodCount);
        return array_key_first($moodCount);
    }
}
