<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Models\Permission;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;

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

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

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

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

        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);
        }

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

        $data = $data->orderBy("created_at", "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 = Permission::with(['user.profile', 'approver'])->find($id);

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

        // return response()->json([
        //     'message' => 'Data berhasil diambil.',
        //     'data' => $data
        // ], 200);
        return response()->json([
            'message' => 'Data berhasil diambil.',
            'data' => [
                'id' => $data->id,
                'user' => $data->user,
                'category' => $data->category,
                'start_date' => $data->start_date,
                'end_date' => $data->end_date,
                'reason' => $data->reason,
                'status' => $data->status,
                'created_at' => $data->created_at,
                'approver' => $data->approver,
                'proof_photo' => $data->proof_photo, // nama file saja
                'proof_photo_url' => $data->proof_photo_url, // URL lengkap ke file foto
                'duration' => $data->duration
            ]
        ], 200);

    }

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

        if (!$permission) {
            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);
        }

        $permission->update([
            'status' => $request->status,
            'approved_by' => $request->user()->id,
            'approved_at' => now(),
        ]);

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

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

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

        $stats = [
            'total' => Permission::count(),
            'pending' => Permission::where('status', 'pending')->count(),
            'approved' => Permission::where('status', 'accepted')->count(),
            'rejected' => Permission::where('status', 'rejected')->count(),
            'this_month' => [
                'total' => Permission::where('created_at', 'like', $thisMonth . '%')->count(),
                'pending' => Permission::where('created_at', 'like', $thisMonth . '%')->where('status', 'pending')->count(),
                'approved' => Permission::where('created_at', 'like', $thisMonth . '%')->where('status', 'accepted')->count(),
                'rejected' => Permission::where('created_at', 'like', $thisMonth . '%')->where('status', 'rejected')->count(),
            ]
        ];

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

    // Di Admin/PermissionController.php

    public function ranking(Request $request)
    {
        $sort = $request->input('sort', 'desc');
        $currentMonth = Carbon::now()->month;
        $currentYear = Carbon::now()->year;

        $ranking = User::select('users.id', 'users.name')
            ->leftJoin('permissions', function($join) use ($currentMonth, $currentYear) {
                $join->on('users.id', '=', 'permissions.user_id')
                    ->whereMonth('permissions.start_date', $currentMonth)
                    ->whereYear('permissions.start_date', $currentYear)
                    ->where('permissions.status', 'accepted');
            })
            ->selectRaw('COUNT(permissions.id) as permission_count')
            ->groupBy('users.id', 'users.name')
            ->orderBy('permission_count', $sort)
            ->paginate(10);

        return view('ranking.index', compact('ranking', 'sort'));
    }
}
