<?php
// app/Models/User.php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Log; // Tambahkan ini

class User extends Authenticatable
{
    use HasFactory, Notifiable;

    protected $fillable = [
        'name',
        'email',
        'password',
        'avatar',
        'role',
        'ortu_code',
        'parent_id',
        'parent_code',
    ];

    protected $hidden = [
        'password',
        'remember_token',
    ];

    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
        ];
    }

    // Relasi untuk siswa ke orang tua
    public function parent()
    {
        return $this->belongsTo(User::class, 'parent_id');
    }

    // Relasi untuk orang tua ke anak-anak
    public function children()
    {
        return $this->hasMany(User::class, 'parent_id');
    }

    public function activityLogs()
    {
        return $this->hasMany(ActivityLog::class);
    }

    public function recommendations()
    {
        return $this->hasMany(Recommendation::class);
    }

    public function parentConnections()
    {
        return $this->hasMany(ParentConnection::class, 'parent_id');
    }

    public function studentConnections()
    {
        return $this->hasMany(ParentConnection::class, 'student_id');
    }

    public function isSiswa()
    {
        return $this->role === 'siswa';
    }

    public function isOrangTua()
    {
        return $this->role === 'orang_tua';
    }

    // Method untuk generate kode - TIDAK DIGUNAKAN, lebih baik gunakan yang di controller
    public function generateConnectionCode()
    {
        Log::info('generateConnectionCode dipanggil untuk user: ' . $this->id);
        
        do {
            $code = strtoupper(substr(md5(uniqid()), 0, 8));
        } while (self::where('ortu_code', $code)->exists());

        $this->ortu_code = $code;
        $this->save(); // Ini yang menyebabkan error karena parent_id tidak diisi
        
        Log::info('Kode berhasil digenerate: ' . $code);
        
        return $code;
    }
    /**
 * Cek apakah sudah input hari ini
 */
public function hasTodayActivity()
{
    return $this->activityLogs()
        ->whereDate('activity_date', \Carbon\Carbon::now('Asia/Jakarta')->toDateString())
        ->exists();
}

/**
 * Ambil aktivitas hari ini
 */
public function getTodayActivity()
{
    return $this->activityLogs()
        ->whereDate('activity_date', \Carbon\Carbon::now('Asia/Jakarta')->toDateString())
        ->first();
}
}