<?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 ChildrenController extends Controller
{
    /**
     * Menampilkan halaman daftar anak (koneksi anak)
     */
    public function index()
    {
        $user = Auth::user();
        
        // Ambil semua anak yang terkoneksi
        $children = User::where('parent_id', $user->id)->get();
        
        $childrenData = [];
        $stats = [
            'total_anak' => $children->count(),
            'today_input' => 0,
            'total_activities' => 0,
            'avg_mood' => 0,
        ];
        
        $totalMoodScore = 0;
        $moodCount = 0;
        
        // Skor mood untuk perhitungan
        $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', Carbon::today())
                ->orderBy('id', 'desc')
                ->first();
            
            if ($todayActivity) {
                $stats['today_input']++;
            }
            
            // Aktivitas 7 hari terakhir
            $weekActivities = ActivityLog::where('user_id', $child->id)
                ->whereDate('activity_date', '>=', Carbon::today()->subDays(7))
                ->get();
            
            $weekCount = $weekActivities->count();
            $stats['total_activities'] += $weekCount;
            
            // Rata-rata durasi 7 hari
            $avgDuration = $weekCount > 0 ? round($weekActivities->avg('duration_minutes')) : 0;
            
            // Mood terbanyak
            $moodCounts = [];
            foreach ($weekActivities as $activity) {
                $moodCounts[$activity->mood] = ($moodCounts[$activity->mood] ?? 0) + 1;
                
                // Hitung total mood score untuk statistik global
                $totalMoodScore += $moodScores[$activity->mood] ?? 3;
                $moodCount++;
            }
            
            $topMood = !empty($moodCounts) ? array_keys($moodCounts, max($moodCounts))[0] : null;
            
            // Rekomendasi terakhir
            $latestRecommendation = Recommendation::where('user_id', $child->id)
                ->latest()
                ->first();
            
            $childrenData[] = [
                'id' => $child->id,
                'name' => $child->name,
                'email' => $child->email,
                'today_activity' => $todayActivity,
                'week_count' => $weekCount,
                'avg_duration' => $avgDuration,
                'top_mood' => $topMood,
                'latest_recommendation' => $latestRecommendation,
            ];
        }
        
        // Hitung rata-rata mood global
        if ($moodCount > 0) {
            $stats['avg_mood'] = round($totalMoodScore / $moodCount, 1);
        }
        
        return view('orangtua.children', compact('childrenData', 'stats'));
    }

    /**
     * Menampilkan detail anak
     */
    public function detail($id)
    {
        $user = Auth::user();
        
        // Pastikan anak terhubung dengan orang tua ini
        $child = User::where('parent_id', $user->id)->findOrFail($id);
        
        // Ambil aktivitas terbaru
        $activities = ActivityLog::where('user_id', $child->id)
            ->with('recommendation')
            ->orderBy('activity_date', 'desc')
            ->paginate(15);
        
        // Statistik
        $totalActivities = ActivityLog::where('user_id', $child->id)->count();
        $totalDuration = ActivityLog::where('user_id', $child->id)->sum('duration_minutes');
        $avgDaily = $totalActivities > 0 ? round($totalDuration / $totalActivities) : 0;
        
        // Hitung konsistensi
        $firstDate = ActivityLog::where('user_id', $child->id)->min('activity_date');
        $consistency = 0;
        if ($firstDate) {
            $daysDiff = Carbon::parse($firstDate)->diffInDays(Carbon::today()) + 1;
            $consistency = round(($totalActivities / $daysDiff) * 100);
        }
        
        $stats = [
            'total_activities' => $totalActivities,
            'total_duration' => $totalDuration,
            'avg_daily' => $avgDaily,
            'consistency' => $consistency,
        ];
        
        return view('orangtua.child-detail', compact('child', 'activities', 'stats'));
    }

    /**
     * Menghubungkan anak dengan kode
     */
    public function connect(Request $request)
    {
        $request->validate([
            'connection_code' => 'required|string|size:8'
        ]);

        $user = Auth::user();
        
        // Cari anak berdasarkan kode koneksi - PERBAIKAN: gunakan whereNotNull untuk memastikan kode tidak null
        $child = User::where('role', 'siswa')
            ->where('parent_code', strtoupper($request->connection_code))
            ->whereNotNull('parent_code')
            ->first();

        if (!$child) {
            return back()->with('error', 'Kode koneksi tidak valid atau sudah kadaluarsa.');
        }

        // Cek apakah anak sudah terhubung dengan orang tua lain
        if ($child->parent_id && $child->parent_id != $user->id) {
            return back()->with('error', 'Anak ini sudah terhubung dengan orang tua lain.');
        }

        // Cek apakah anak sudah terhubung dengan orang tua ini
        if ($child->parent_id == $user->id) {
            return back()->with('error', 'Anak ini sudah terhubung dengan akun Anda.');
        }

        // Hubungkan anak dengan orang tua
        $child->parent_id = $user->id;
        $child->save();

        return redirect()->route('orangtua.children')->with('success', 'Berhasil terhubung dengan ' . $child->name);
    }

    /**
     * Memutuskan koneksi dengan anak
     */
    public function disconnect($id)
    {
        $user = Auth::user();
        
        // Cari anak yang terhubung dengan orang tua ini
        $child = User::where('parent_id', $user->id)->findOrFail($id);
        
        // Simpan nama anak untuk pesan sukses
        $childName = $child->name;
        
        // Putuskan koneksi dengan mengosongkan parent_id
        $child->parent_id = null;
        $child->save();
        
        return redirect()->route('orangtua.children')->with('success', 'Koneksi dengan ' . $childName . ' berhasil diputuskan.');
    }
}
