<?php

namespace App\Http\Controllers;

use App\Models\Attendance;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Storage;

class AdminUserController extends Controller
{
    public function index(Request $request)
    {
        $search = $request->input('search');
        $skill = $request->input('skill');
        
        $users = User::where('role', '!=', 'admin')
            ->when($search, function($query) use ($search) {
                return $query->where('name', 'like', "%{$search}%")
                           ->orWhere('email', 'like', "%{$search}%")
                           ->orWhere('nik', 'like', "%{$search}%");
            })
            ->when($skill, function($query) use ($skill) {
                return $query->where('skill', $skill);
            })
            ->orderBy('nik')
            ->orderBy('name')
            ->paginate(15) // 15 users per page
            ->withQueryString(); // Preserve search parameters in pagination links
            
        return view('admin.users.index', [
            'title' => 'Daftar Pengguna',
            'users' => $users,
            'search' => $search,
            'skill' => $skill
        ]);
    }
    public function show(User $user)
{
    $attendanceQuery = $user->attendances();

    $totalAbsensi = (clone $attendanceQuery)->count();
    $verifiedCount = (clone $attendanceQuery)
        ->whereNotNull('clock_in')
        ->whereNotNull('clock_out')
        ->count();
    $excusedCount = (clone $attendanceQuery)
        ->whereIn('status', ['sakit', 'izin'])
        ->count();

    $invalidCount = max($totalAbsensi - ($verifiedCount + $excusedCount), 0);

    $recentAttendances = $user->attendances()
        ->orderByDesc('clock_in')
        ->orderByDesc('created_at')
        ->take(10)
        ->get();

    return view('admin.users.show', [
        'title' => 'Profil Pegawai',
        'user' => $user,
        'attendanceSummary' => [
            'total' => $totalAbsensi,
            'verified' => $verifiedCount,
            'excused' => $excusedCount,
            'invalid' => $invalidCount,
        ],
        'attendanceRecords' => $recentAttendances,
    ]);
}
    public function toggleAttendance(Request $request, User $user)
    {
        $validated = $request->validate([
            'attendance_enabled' => ['required', 'boolean'],
        ]);

        $user->update([
            'attendance_enabled' => (bool) $validated['attendance_enabled'],
        ]);

        Cache::forget('sidebar_users_summary');

        return back()->with('status', 'Pengaturan absensi untuk ' . $user->name . ' telah diperbarui.');
    }

    public function toggleApproval(Request $request, User $user)
    {
        $validated = $request->validate([
            'is_approved' => ['required', 'boolean'],
        ]);

        $user->update([
            'is_approved' => (bool) $validated['is_approved'],
        ]);

        Cache::forget('sidebar_users_summary');

        return back()->with('status', 'Status persetujuan untuk ' . $user->name . ' telah diperbarui.');
    }

    public function destroy(User $user)
    {
        // Prevent deleting yourself
        if ($user->id === auth()->id()) {
            return redirect()->route('admin.users.index')
                ->with('error', 'Tidak dapat menghapus akun sendiri');
        }

        // Delete user's avatar if exists
        if ($user->avatar_path && Storage::exists($user->avatar_path)) {
            Storage::delete($user->avatar_path);
        }

        $user->delete();

        Cache::forget('sidebar_users_summary');

        return redirect()->route('admin.users.index')
            ->with('status', 'Pengguna berhasil dihapus');
    }

    public function enableAllAttendance()
    {
        User::query()->update(['attendance_enabled' => true]);
        Cache::forget('sidebar_users_summary');

        return back()->with('status', 'Absensi telah diaktifkan untuk semua pengguna.');
    }

    public function disableAllAttendance()
    {
        User::query()->update(['attendance_enabled' => false]);
        Cache::forget('sidebar_users_summary');

        return back()->with('status', 'Absensi telah dinonaktifkan untuk semua pengguna.');
    }
}
