<?php

namespace App\Http\Controllers;

use App\Http\Requests\ProfileUpdateRequest;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Hash;
use Illuminate\View\View;
use App\Models\User;

class ProfileController extends Controller
{
    /**
     * Display the user's profile form.
     */
    public function edit(Request $request): View
    {
        $user = Auth::user();
        
        // Statistik tambahan untuk siswa
        $stats = [];
        if ($user->isSiswa()) {
            $stats = [
                'total_aktivitas' => \App\Models\ActivityLog::where('user_id', $user->id)->count(),
                'total_durasi' => \App\Models\ActivityLog::where('user_id', $user->id)->sum('duration_minutes'),
                'joined_since' => $user->created_at->format('d M Y'),
                'konsistensi' => $this->calculateConsistency($user->id),
            ];
        } else {
            // Statistik untuk orang tua
            $stats = [
                'total_anak' => \App\Models\User::where('parent_id', $user->id)->count(),
                'joined_since' => $user->created_at->format('d M Y'),
            ];
        }
        
        return view('profile.edit', [
            'user' => $user,
            'stats' => $stats
        ]);
    }

    /**
     * Update the user's profile information.
     */
    public function update(ProfileUpdateRequest $request): RedirectResponse
    {
        $user = $request->user();
        $user->fill($request->validated());

        if ($user->isDirty('email')) {
            $user->email_verified_at = null;
        }

        $user->save();

        return Redirect::route('profile.edit')->with('success', 'Profile berhasil diperbarui.');
    }

    /**
     * Update the user's password.
     */
    public function updatePassword(Request $request): RedirectResponse
    {
        $request->validate([
            'current_password' => ['required', 'current_password'],
            'new_password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);

        $user = $request->user();
        $user->password = Hash::make($request->new_password);
        $user->save();

        return Redirect::route('profile.edit')->with('success', 'Password berhasil diubah.');
    }

    /**
     * Update the user's avatar.
     */
    /**
 * Update the user's avatar.
 */
public function updateAvatar(Request $request): RedirectResponse
{
    $request->validate([
        'avatar' => ['required', 'image', 'mimes:jpeg,png,jpg,gif', 'max:2048'],
    ]);

    $user = $request->user();
    
    if ($request->hasFile('avatar')) {
        $avatar = $request->file('avatar');
        
        // Generate nama file unik
        $filename = time() . '_' . $user->id . '_' . uniqid() . '.' . $avatar->getClientOriginalExtension();
        
        // Pastikan folder avatars ada
        $avatarPath = public_path('avatars');
        if (!file_exists($avatarPath)) {
            mkdir($avatarPath, 0755, true);
        }
        
        // Simpan ke folder public/avatars
        $avatar->move($avatarPath, $filename);
        
        // Hapus avatar lama jika bukan default dan file exists
        if ($user->avatar && $user->avatar != 'default.png' && file_exists($avatarPath . '/' . $user->avatar)) {
            unlink($avatarPath . '/' . $user->avatar);
        }
        
        // Update database
        $user->avatar = $filename;
        $user->save();
        
        return Redirect::route('profile.edit')->with('success', 'Avatar berhasil diperbarui.');
    }

    return Redirect::route('profile.edit')->with('error', 'Gagal mengupload avatar.');
}

    /**
     * Delete the user's account.
     */
    public function destroy(Request $request): RedirectResponse
    {
        $request->validateWithBag('userDeletion', [
            'password' => ['required', 'current_password'],
        ]);

        $user = $request->user();

        Auth::logout();

        $user->delete();

        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return Redirect::to('/');
    }

    /**
     * Menghitung konsistensi untuk siswa
     */
    private function calculateConsistency($userId)
    {
        $total = \App\Models\ActivityLog::where('user_id', $userId)->count();
        if ($total == 0) return 0;
        
        $firstDate = \App\Models\ActivityLog::where('user_id', $userId)->min('activity_date');
        if (!$firstDate) return 0;
        
        $daysDiff = \Carbon\Carbon::parse($firstDate)->diffInDays(\Carbon\Carbon::today()) + 1;
        
        return round(($total / $daysDiff) * 100);
    }
}