<?php

namespace App\Http\Controllers\Siswa;

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

class VisualizationController extends Controller
{
    public function index(Request $request)
    {
        $user = Auth::user();
        
        // Filter periode (default 30 hari)
        $period = $request->get('period', 30);
        $startDate = Carbon::today()->subDays($period);
        
        // Ambil data aktivitas
        $activities = ActivityLog::where('user_id', $user->id)
            ->whereDate('activity_date', '>=', $startDate)
            ->orderBy('activity_date', 'asc')
            ->get();

        // Ambil data rekomendasi untuk periode yang sama
        $recommendations = Recommendation::where('user_id', $user->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 = [];
        
        // PISAHKAN DUA ARRAY
        $categoriesRaw = [];     // untuk grafik & warna ('Ringan', 'Sedang', 'Intensif')
        $categoriesDisplay = []; // untuk tampilan teks di tabel
        
        // 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;
            
            if (isset($moodCount[$activity->mood])) {
                $moodCount[$activity->mood]++;
            }
            
            $sleep_hours[] = $activity->sleep_duration ?? $activity->sleep_hours ?? 7;
            
            // REKOMENDASI: simpan dua array
            if (isset($recommendations[$dateKey])) {
                $rec = $recommendations[$dateKey];
                $categoriesRaw[] = $rec->category;           // 'Ringan', 'Sedang', 'Intensif'
                $categoriesDisplay[] = $rec->display_category; // '📚 Konsisten', dll
            } else {
                $categoriesRaw[] = null;
                $categoriesDisplay[] = null;
            }
        }

        // Hitung statistik untuk grafik sebaran rekomendasi (pakai $categoriesRaw)
        $stats = [
            'total_hari' => $activities->count(),
            'rata_durasi' => $activities->count() > 0 ? round($activities->avg('duration_minutes'), 1) : 0,
            'mood_terbanyak' => $this->getMostFrequent($moodCount, '-'),
            'rekom_terbanyak' => $this->getMostFrequentCategory($categoriesRaw, '-'),
        ];

        $moodDistribution = array_filter($moodCount, function($count) {
            return $count > 0;
        });

        return view('siswa.visualization', compact(
            'dates',
            'durations',
            'moods',
            'sleep_hours',
            'categoriesRaw',     // untuk grafik & warna
            'categoriesDisplay', // untuk tampilan teks di tabel
            'stats',
            'moodDistribution',
            'period'
        ));
    }

    private function getMostFrequent($array, $default = '-')
    {
        if (empty($array)) return $default;
        
        arsort($array);
        $keys = array_keys($array);
        
        return !empty($keys) && $array[$keys[0]] > 0 ? $keys[0] : $default;
    }

    private function getMostFrequentCategory($categories, $default = '-')
    {
        $filtered = array_filter($categories);
        if (empty($filtered)) return $default;
        
        $counts = array_count_values($filtered);
        arsort($counts);
        
        return array_key_first($counts) ?? $default;
    }
}
