<?php

namespace App\Http\Controllers\Admin\Manage;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Manage\AttendanceRequest;
use App\Models\Attendance;
use App\Traits\UploadAttachment;
use Carbon\Carbon;
use Illuminate\Contracts\View\View;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Yajra\DataTables\Facades\DataTables;

class AttendanceController extends Controller
{
    use UploadAttachment;

    public function index(Request $request): View|JsonResponse
    {
        if ($request->ajax()) {
            $attendances = Attendance::with('attachments')
                ->barbershop()
                ->when(in_array(auth()->user()->role_id, [4, 5]), function ($query) {
                    return $query->where('user_id', auth()->id());
                });

            return DataTables::eloquent($attendances)
                ->addIndexColumn()
                ->editColumn('created_at', function ($item) {
                    return formatDateIndo($item->created_at);
                })
                ->addColumn('working_time', function ($item) {
                    if ($item->check_in) {
                        $checkIn = Carbon::parse($item->check_in);

                        if (! $item->check_out && $item->created_at->isToday()) {
                            $checkOut = now();
                        } elseif (! $item->check_out && ! $item->created_at->isToday()) {
                            $checkOut = $checkIn->copy()->endOfDay();
                        } else {
                            $checkOut = Carbon::parse($item->check_out);
                        }

                        $diff = $checkIn->diff($checkOut);

                        if ($diff->h > 0) {
                            return $diff->format('%h jam %i menit %s detik');
                        } else {
                            return $diff->format('%i menit %s detik');
                        }
                    }

                    return '-';
                })
                ->editColumn('check_out', function ($item) {
                    return $item->check_out ?: '-';
                })
                ->addColumn('check_in_image', function ($item) {
                    if ($item->check_in) {
                        $imageUrl = Storage::url("attendances/{$item->attachments->first()->formatted_attachment}");

                        return '<a href="'.$imageUrl.'" ><img src="'.$imageUrl.'" alt="Check-in Image" height="77" width="77"></a>';
                    }

                    return '-';
                })
                ->addColumn('check_out_image', function ($item) {
                    if ($item->check_out) {
                        $imageUrl = Storage::url("attendances/{$item->attachments()->latest()->first()->formatted_attachment}");

                        return '<a href="'.$imageUrl.'" ><img src="'.$imageUrl.'" alt="Check-out Image" height="77" width="77"></a>';
                    }

                    return '-';
                })
                ->rawColumns(['check_in_image', 'check_out_image'])
                ->make();
        }

        return view('pages.admin.manage.attendances', [
            'pageTitle' => 'Kehadiran',
            'checkInAttendance' => Attendance::with('attachments')->where('user_id', Auth::id())->whereDate('created_at', today())->first(),
            'checkOutAttendance' => Attendance::with('attachments')->where('user_id', Auth::id())->whereDate('created_at', today())->whereNotNull('check_out')->first(),
        ]);
    }

    public function store(AttendanceRequest $request): JsonResponse
    {
        $validatedData = $request->validated();
        $checkInAttendance = Attendance::where('user_id', Auth::id())->whereDate('created_at', today())->first();
        DB::transaction(function () use ($validatedData, $checkInAttendance) {
            if (! $checkInAttendance) {
                $newAttendance = Attendance::create([
                    'user_id' => Auth::id(),
                    'barbershop_id' => Auth::user()->barbershop_id,
                    'check_in' => now(),
                ]);
            } else {
                $newAttendance = $checkInAttendance;
                $newAttendance->update([
                    'check_out' => now(),
                ]);
            }
            $this->uploadAttachment($validatedData['image'], 'attendances', Attendance::class, $newAttendance->id, ! $checkInAttendance ? 'check_in' : 'check_out');
        });

        return response()->json([
            'status' => 'success',
            'message' => 'Image saved successfully!',
        ], 200);
    }
}
