<?php

namespace App\Http\Controllers\Api\Employee;

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

class PermissionController extends Controller
{
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'start_date' => 'required|date|after_or_equal:today',
            'end_date' => 'required|date|after_or_equal:start_date',
            'category' => 'required|string|max:255',
            'reason' => 'required|string',
            'proof_photo' => 'nullable|file|mimes:jpeg,png,jpg,pdf|max:5120', // 5MB
        ]);

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

        $user = auth()->user();

        $overlapping = Permission::where('user_id', $user->id)
            ->where('status', '!=', 'rejected')
            ->where(function ($query) use ($request) {
                $query->whereBetween('start_date', [$request->start_date, $request->end_date])
                      ->orWhereBetween('end_date', [$request->start_date, $request->end_date])
                      ->orWhere(function ($q) use ($request) {
                          $q->where('start_date', '<=', $request->start_date)
                            ->where('end_date', '>=', $request->end_date);
                      });
            })
            ->exists();

        if ($overlapping) {
            return response()->json([
                'message' => 'Anda sudah memiliki pengajuan izin pada rentang tanggal tersebut.',
                'data' => null
            ], 422);
        }

        $proofPhotoPath = null;
        if ($request->hasFile('proof_photo')) {
            $photo = $request->file('proof_photo');
            $filename = time() . '_' . $user->id . '_permission.' . $photo->getClientOriginalExtension();
            $proofPhotoPath = $photo->storeAs('permissions', $filename, 'public');
        }

        $permission = Permission::create([
            'user_id' => $user->id,
            'start_date' => $request->start_date,
            'end_date' => $request->end_date,
            'category' => $request->category,
            'reason' => $request->reason,
            'proof_photo' => $proofPhotoPath,
            'status' => 'pending'
        ]);

        return response()->json([
            'message' => 'Pengajuan izin berhasil diajukan.',
            'data' => $permission
        ], 200);
    }

    public function history(Request $request)
    {
        $user = auth()->user();
        $data = Permission::where('user_id', $user->id);

        $search = $request->input('search', '');
        if (!empty($search)) {
            $data->where(function ($query) use ($search) {
                $query->where('category', 'like', '%' . $search . '%')
                      ->orWhere('reason', '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('category') && !empty($request->category)) {
            $data->where('category', 'like', '%' . $request->category . '%');
        }

        $total_data = $data->get()->count();
        $length = intval($request->input('length', 10));
        $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,
            'recordsTotal' => $total_data,
            'recordsFiltered' => $total_data,
        ], 200);
    }

    public function show(string $id)
    {
        $user = auth()->user();
        $data = Permission::where('user_id', $user->id)
            ->where('id', $id)
            ->with(['approvedBy'])
            ->first();

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

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

    public function cancel(string $id)
    {
        $user = auth()->user();
        $permission = Permission::where('user_id', $user->id)
            ->where('id', $id)
            ->where('status', 'pending')
            ->first();

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

        if (Carbon::parse($permission->start_date)->isPast()) {
            return response()->json([
                'message' => 'Izin yang sudah dimulai tidak dapat dibatalkan.',
                'data' => null
            ], 422);
        }

        $permission->update(['status' => 'rejected']);

        return response()->json([
            'message' => 'Pengajuan izin berhasil dibatalkan.',
            'data' => $permission
        ], 200);
    }

    public function statistics()
    {
        $user = auth()->user();
        $thisMonth = now()->format('Y-m');
        $thisYear = now()->format('Y');

        $stats = [
            'this_month' => [
                'total' => Permission::where('user_id', $user->id)
                    ->where('start_date', 'like', $thisMonth . '%')
                    ->count(),
                'pending' => Permission::where('user_id', $user->id)
                    ->where('start_date', 'like', $thisMonth . '%')
                    ->where('status', 'pending')
                    ->count(),
                'accepted' => Permission::where('user_id', $user->id)
                    ->where('start_date', 'like', $thisMonth . '%')
                    ->where('status', 'accepted')
                    ->count(),
                'rejected' => Permission::where('user_id', $user->id)
                    ->where('start_date', 'like', $thisMonth . '%')
                    ->where('status', 'rejected')
                    ->count(),
            ],
            'this_year' => [
                'total' => Permission::where('user_id', $user->id)
                    ->where('start_date', 'like', $thisYear . '%')
                    ->count(),
                'accepted' => Permission::where('user_id', $user->id)
                    ->where('start_date', 'like', $thisYear . '%')
                    ->where('status', 'accepted')
                    ->count(),
            ]
        ];

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