<?php

namespace App\Http\Controllers;

use App\Models\Attendance;
use App\Models\Notification;
use Illuminate\Http\Request;

class AdminAbsensiController extends Controller
{
    public function index(Request $request)
    {
        // Default to today's date if not provided
        $dateFilter = $request->input('date') ?? now()->format('Y-m-d');

        $items = Attendance::with(['user' => function($query) {
                $query->select('id', 'name', 'nik', 'skill');
            }])
            ->whereDate('clock_in', $dateFilter)
            ->orderByDesc('clock_in')
            ->orderByDesc('created_at')
            ->paginate(15)
            ->withQueryString();

        // Get count of people in each jobdesk for the selected date
        $jobdeskCounts = Attendance::select('jobdesk', \DB::raw('count(*) as count'))
            ->whereDate('clock_in', $dateFilter)
            ->whereNotNull('jobdesk')
            ->groupBy('jobdesk')
            ->pluck('count', 'jobdesk');

        return view('admin.absensi.index', [
            'title' => 'Data Absensi',
            'items' => $items,
            'jobdeskOptions' => $this->jobdeskOptions(),
            'filterDate' => $dateFilter,
            'jobdeskCounts' => $jobdeskCounts,
        ]);
    }

    public function destroy(Attendance $attendance)
    {
        $attendance->delete();

        return redirect()
            ->route('admin.absensi.index')
            ->with('success', 'Data absensi berhasil dihapus.');
    }

    public function assignJobdesk(Request $request, Attendance $attendance)
    {
        $options = $this->jobdeskOptions();

        $validated = $request->validate([
            'jobdesk' => ['nullable', 'in:' . implode(',', $options)],
            'admin_note' => ['nullable', 'string', 'max:500'],
        ]);

        $updates = [];

        if ($request->has('jobdesk')) {
            $updates['jobdesk'] = $validated['jobdesk'] ?? null;
        }

        if (array_key_exists('admin_note', $validated)) {
            $updates['admin_note'] = $validated['admin_note'] !== null
                ? trim($validated['admin_note'])
                : null;
        }

        if (empty($updates)) {
            return back()->with('info', 'Tidak ada perubahan yang disimpan.');
        }

        $attendance->fill($updates);

        $jobdeskChanged = $attendance->isDirty('jobdesk');
        $adminNoteChanged = $attendance->isDirty('admin_note');

        if (! $jobdeskChanged && ! $adminNoteChanged) {
            return back()->with('info', 'Tidak ada perubahan yang disimpan.');
        }

        $attendance->save();

        if ($jobdeskChanged || $adminNoteChanged) {
            $messages = [];

            if ($jobdeskChanged) {
                $messages[] = $attendance->jobdesk
                    ? 'Jobdesk kamu ditetapkan ke ' . strtoupper($attendance->jobdesk) . '.'
                    : 'Jobdesk kamu dihapus.';
            }

            if ($adminNoteChanged) {
                $messages[] = $attendance->admin_note
                    ? 'Catatan admin: ' . $attendance->admin_note
                    : 'Catatan admin telah dikosongkan.';
            }

            $clockIn = $attendance->clock_in
                ? $attendance->clock_in->timezone(config('app.timezone'))->format('d M Y')
                : now()->timezone(config('app.timezone'))->format('d M Y');

            Notification::create([
                'user_id' => $attendance->user_id,
                'title' => 'Perbaruan Absensi ' . $clockIn,
                'message' => implode("\n\n", $messages),
                'is_read' => false,
            ]);
        }

        return back()->with('success', 'Data admin berhasil diperbarui.');
    }

    protected function jobdeskOptions(): array
    {
        return [
            'km19',
            'port',
            'km7.5',
            'km 33',
            'workshop 22',
            'werehouse',
        ];
    }
}
