<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Models\Attendance;
use App\Models\Location;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;

class AttendanceController extends Controller
{
    public function index(Request $request)
    {
        $data = Attendance::with(['user.profile', 'location']);

        $search = $request->input('search.value', '');
        if (!empty($search)) {
            $data->where(function ($query) use ($search) {
                $query->whereHas('user', function ($q) use ($search) {
                    $q->where('name', 'like', '%' . $search . '%')
                      ->orWhereHas('profile', function ($p) use ($search) {
                          $p->where('nip', 'like', '%' . $search . '%');
                      });
                });
            });
        }

        if ($request->has('start_date') && !empty($request->start_date)) {
            $data->where('start_date', '>=', $request->start_date);
        }

        if ($request->has('end_date') && !empty($request->end_date)) {
            $data->where('end_date', '<=', $request->end_date);
        }

        if ($request->has('status') && !empty($request->status)) {
            $data->where('status', $request->status);
        }

        if ($request->has('type') && !empty($request->type)) {
            $data->where('type', $request->type);
        }

        $total_data = $data->get()->count();
        $length = intval($request->input('length', 0));
        $start = intval($request->input('start', 0));

        $data = $data->orderBy("date", "desc")->orderBy("time", "desc");
        if (!$length && !$start) {
            $data = $data->get();
        } else {
            $data = $data->skip($start)->take($length)->get();
        }

        return response()->json([
            'message' => 'Data berhasil diambil.',
            'data' => $data,
            'draw' => $request->input('draw'),
            'recordsTotal' => $total_data,
            'recordsFiltered' => $total_data,
        ], 200);
    }

    public function show(string $id)
    {
        $data = Attendance::with(['user.profile', 'location'])->find($id);

        if (!$data) {
            return response()->json([
                'message' => 'Data tidak ditemukan.',
                'data' => null
            ], 422);
        }

        return response()->json([
            'message' => 'Data berhasil diambil.',
            'data' => $data
        ], 200);
    }

    public function approve(Request $request, string $id)
    {
        $attendance = Attendance::find($id);

        if (!$attendance) {
            return response()->json([
                'message' => 'Data tidak ditemukan.',
                'data' => null
            ], 422);
        }

        $validator = Validator::make($request->all(), [
            'status' => 'required|in:accepted,rejected',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'message' => Str::ucfirst($validator->errors()->first()),
                'data' => null
            ], 422);
        }

        $attendance->update([
            'status' => $request->status,
        ]);

        $message = $request->status === 'accepted' ? 'Absensi berhasil disetujui.' : 'Absensi berhasil ditolak.';

        return response()->json([
            'message' => $message,
            'data' => $attendance->load(['user.profile', 'location'])
        ], 200);
    }

    public function statistics(Request $request)
    {
        $today = now()->toDateString();
        $thisMonth = now()->format('Y-m');

        $stats = [
            'today' => [
                'total' => Attendance::whereDate('date', $today)->count(),
                'present' => Attendance::whereDate('date', $today)->where('status', 'accepted')->count(),
                'pending' => Attendance::whereDate('date', $today)->where('status', 'pending')->count(),
            ],
            'this_month' => [
                'total' => Attendance::where('date', 'like', $thisMonth . '%')->count(),
                'present' => Attendance::where('date', 'like', $thisMonth . '%')->where('status', 'accepted')->count(),
                'pending' => Attendance::where('date', 'like', $thisMonth . '%')->where('status', 'pending')->count(),
            ]
        ];

        return response()->json([
            'message' => 'Statistik berhasil diambil.',
            'data' => $stats
        ], 200);
    }
    public function area()
{
    $area = Location::first(); // atau sesuai logic
    return response()->json([
        'center_lat' => $area->center_lat,
        'center_lng' => $area->center_lng,
        'radius' => $area->radius,
    ]);
}
}
