<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\ActivityLog;
use App\Models\Recommendation;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class DashboardController extends Controller
{
    /**
     * Dashboard utama berdasarkan role pengguna
     */
    public function index()
    {
        $user = Auth::user();

        if ($user->isSiswa()) {
            return $this->siswaDashboard();
        } else {
            return $this->orangTuaDashboard();
        }
    }

    /**
     * Dashboard untuk role Siswa
     */
    private function siswaDashboard()
    {
        $user = Auth::user();
        
        // SET TIMEZONE - Pastikan konsisten di seluruh aplikasi
        Carbon::setLocale('id');
        $now = Carbon::now('Asia/Jakarta');
        $todayDate = $now->toDateString(); // Format Y-m-d
        
        // DEBUG: Log untuk memantau
        Log::info('Siswa Dashboard - Pengecekan', [
            'user_id' => $user->id,
            'waktu_server' => now()->toDateTimeString(),
            'waktu_wib' => $now->toDateTimeString(),
            'today_date' => $todayDate
        ]);

        // DATA HARI INI - Gunakan query dengan whereDate untuk konsistensi
        $todayActivity = ActivityLog::where('user_id', $user->id)
            ->whereDate('activity_date', $todayDate)
            ->first();

        // DEBUG: Cek apakah ada data
        if ($todayActivity) {
            Log::info('Siswa - Aktivitas hari ini ditemukan', [
                'activity_id' => $todayActivity->id,
                'activity_date' => $todayActivity->activity_date,
                'duration' => $todayActivity->duration_minutes
            ]);
        } else {
            Log::info('Siswa - Tidak ada aktivitas hari ini', [
                'tanggal_yang_dicek' => $todayDate
            ]);
            
            // CEK MANUAL: Apakah ada data dengan tanggal yang sama tapi format berbeda?
            $alternativeCheck = ActivityLog::where('user_id', $user->id)
                ->whereRaw("DATE(activity_date) = ?", [$todayDate])
                ->first();
                
            if ($alternativeCheck) {
                Log::warning('Siswa - Data ditemukan dengan RAW query tapi tidak dengan whereDate!', [
                    'id' => $alternativeCheck->id,
                    'date' => $alternativeCheck->activity_date
                ]);
                $todayActivity = $alternativeCheck; // Gunakan yang ditemukan
            }
        }

        // STATISTIK 7 HARI TERAKHIR
        $weekStartDate = $now->copy()->subDays(7)->toDateString();
        $weekActivities = ActivityLog::where('user_id', $user->id)
            ->whereDate('activity_date', '>=', $weekStartDate)
            ->orderBy('activity_date', 'desc')
            ->get();

        // TOTAL HARI INPUT (semua waktu)
        $totalDays = ActivityLog::where('user_id', $user->id)->count();

        // RATA-RATA DURASI BELAJAR
        $avgDuration = ActivityLog::where('user_id', $user->id)
            ->avg('duration_minutes') ?? 0;

        // REKOMENDASI TERAKHIR
        $latestRecommendation = Recommendation::where('user_id', $user->id)
            ->latest()
            ->first();

        // GREETING BERDASARKAN WAKTU
        $greeting = $this->getGreeting($now);

        return view('dashboard.siswa', compact(
            'todayActivity',
            'weekActivities',
            'totalDays',
            'avgDuration',
            'latestRecommendation',
            'greeting'
        ));
    }

    /**
     * Dashboard untuk role Orang Tua
     */
    private function orangTuaDashboard()
    {
        $user = Auth::user();
        
        // SET TIMEZONE
        Carbon::setLocale('id');
        $now = Carbon::now('Asia/Jakarta');
        $todayDate = $now->toDateString();
        $weekStartDate = $now->copy()->subDays(7)->toDateString();
        
        // DEBUG
        Log::info('Orang Tua Dashboard - Pengecekan', [
            'parent_id' => $user->id,
            'waktu_wib' => $now->toDateTimeString(),
            'today_date' => $todayDate
        ]);
        
        // AMBIL SEMUA ANAK YANG TERKONEKSI
        $children = User::where('parent_id', $user->id)->get();
        
        $childrenData = [];
        $totalTodayInput = 0;
        $totalWeekActivities = 0;
        $totalMoodScore = 0;
        $moodCount = 0;
        
        // SKOR MOOD
        $moodScores = [
            'Bagus' => 5,
            'Lumayan' => 4,
            'Biasa Saja' => 3,
            'Cukup Jenuh' => 2,
            'Jenuh' => 1
        ];
        
        foreach ($children as $child) {
            // AKTIVITAS HARI INI
            $todayActivity = ActivityLog::where('user_id', $child->id)
                ->whereDate('activity_date', $todayDate)
                ->first();
            
            // DEBUG per anak
            Log::info('Orang Tua - Cek anak', [
                'child_id' => $child->id,
                'child_name' => $child->name,
                'today_activity' => $todayActivity ? 'ADA' : 'TIDAK ADA',
                'tanggal_dicek' => $todayDate
            ]);
            
            if ($todayActivity) {
                $totalTodayInput++;
            }
            
            // AKTIVITAS 7 HARI TERAKHIR
            $weekActivities = ActivityLog::where('user_id', $child->id)
                ->whereDate('activity_date', '>=', $weekStartDate)
                ->orderBy('activity_date', 'desc')
                ->get();
            
            $weekActivitiesCount = $weekActivities->count();
            $totalWeekActivities += $weekActivitiesCount;
            
            // TOTAL DURASI 7 HARI
            $weekTotalDuration = $weekActivities->sum('duration_minutes');
            
            // REKOMENDASI TERAKHIR
            $latestRecommendation = Recommendation::where('user_id', $child->id)
                ->latest()
                ->first();
            
            // RATA-RATA MOOD SCORE
            $averageMoodScore = 0;
            if ($weekActivitiesCount > 0) {
                $totalChildMood = 0;
                foreach ($weekActivities as $activity) {
                    $moodScore = $moodScores[$activity->mood] ?? 3;
                    $totalChildMood += $moodScore;
                    $totalMoodScore += $moodScore;
                    $moodCount++;
                }
                $averageMoodScore = round($totalChildMood / $weekActivitiesCount, 1);
            }
            
            // 5 AKTIVITAS TERAKHIR
            $recentActivities = ActivityLog::where('user_id', $child->id)
                ->orderBy('activity_date', 'desc')
                ->limit(5)
                ->get();
            
            $childrenData[] = [
                'child' => $child,
                'today_activity' => $todayActivity,
                'week_activities_count' => $weekActivitiesCount,
                'week_total_duration' => $weekTotalDuration,
                'average_mood_score' => $averageMoodScore,
                'latest_recommendation' => $latestRecommendation,
                'recent_activities' => $recentActivities,
            ];
        }
        
        // RATA-RATA MOOD GABUNGAN
        $averageMoodAll = $moodCount > 0 ? round($totalMoodScore / $moodCount, 1) : 0;

        // GREETING
        $greeting = $this->getGreeting($now);

        return view('dashboard.orangtua', compact(
            'childrenData',
            'totalTodayInput',
            'totalWeekActivities',
            'averageMoodAll',
            'greeting'
        ));
    }

    /**
     * Mendapatkan greeting berdasarkan waktu
     */
    private function getGreeting(Carbon $time)
    {
        $hour = (int) $time->format('H');
        
        if ($hour < 12) {
            return 'Selamat Pagi';
        } elseif ($hour < 15) {
            return 'Selamat Siang';
        } elseif ($hour < 18) {
            return 'Selamat Sore';
        } else {
            return 'Selamat Malam';
        }
    }

    /**
     * Method untuk debugging (opsional)
     */
    public function debugToday($userId = null)
    {
        $userId = $userId ?? Auth::id();
        
        $now = Carbon::now('Asia/Jakarta');
        $todayDate = $now->toDateString();
        
        $activities = ActivityLog::where('user_id', $userId)
            ->orderBy('activity_date', 'desc')
            ->limit(20)
            ->get();
        
        $todayActivity = ActivityLog::where('user_id', $userId)
            ->whereDate('activity_date', $todayDate)
            ->first();
        
        return response()->json([
            'success' => true,
            'debug_info' => [
                'server_time' => now()->toDateTimeString(),
                'wib_time' => $now->toDateTimeString(),
                'timezone' => date_default_timezone_get(),
                'today_date' => $todayDate,
                'user_id' => $userId,
                'has_today_activity' => $todayActivity ? true : false,
                'today_activity' => $todayActivity ? [
                    'id' => $todayActivity->id,
                    'date' => $todayActivity->activity_date,
                    'duration' => $todayActivity->duration_minutes,
                    'created_at' => $todayActivity->created_at,
                ] : null,
                'recent_activities' => $activities->map(function($a) {
                    return [
                        'id' => $a->id,
                        'date' => $a->activity_date,
                        'duration' => $a->duration_minutes,
                        'created_at' => $a->created_at,
                    ];
                }),
                'raw_query' => "SELECT * FROM activity_logs WHERE user_id = $userId AND DATE(activity_date) = '$todayDate'"
            ]
        ]);
    }
}
