<?php

namespace Modules\Admin\app\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Jobs\InitializeLeaveDays;
use App\Models\LeaveDays;
use App\Models\Notes;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class LeaveManagementController extends Controller
{
    public function get(Request $request)
    {
        $yearNow = $request->query('year', now()->year);
        $year = $request->year ?? $yearNow;

        $leaveDays = self::getDataByYear($year);
        if ($leaveDays->count() == 0) {
            InitializeLeaveDays::dispatch($year);
            $leaveDays = self::getDataByYear($year);
        }
        return AbstractController::ResultSuccess($leaveDays);
    }

    public function getDataByYear($year)
    {
        $totalLeaveDaysByMonth = Notes::join('categories', function ($join) {
            $join->on('notes.n_time_type', '=', 'categories.c_code')
                ->where('categories.c_type', 'TIME_TYPE');
        })
            ->leftJoin("categories as reason", function ($join) {
                $join->on('n_reason', '=', 'reason.c_code');
                $join->on('reason.c_type', DB::raw("CONCAT('REASON')"));
            })
            ->select(
                DB::raw('notes.n_user_id as n_user_id'),
                DB::raw('notes.n_time_type as time_type'),
                DB::raw('notes.n_year as year'),
                DB::raw('notes.n_month as month'),
                DB::raw('categories.c_value as leave_days'),
                DB::raw('notes.n_day as day'),
                'reason.c_name as reason_name',
                'categories.c_name as time_type_name',
                // DB::raw('SUM(categories.c_value) as leave_days')
            )
            // ->where('notes.n_user_id', "1")
            ->where('notes.n_year', $year)
            ->where('notes.n_reason', 'ONLEAVE')
            // ->groupBy("notes.n_user_id")
            ->orderBy('notes.n_month')
            ->orderBy('notes.n_day')
            ->get()
            ->map(function ($item) {
                return [
                    "day" => $item->day,
                    "n_user_id" => $item->n_user_id,
                    // "time_type" => $item->time_type,
                    "reason_name" => $item->reason_name,
                    "time_type_name" => $item->time_type_name,
                    "month" => $item->month,
                    "leave_days" => $item->leave_days
                ];
            })
            ->toArray();
        // dd($totalLeaveDaysByMonth);
        $leaveDays = LeaveDays::join('users', 'leave_days.ld_user_id', '=', 'users.id')
            ->select(
                'leave_days.*',
                'users.id as user_id',
                'users.name as user_name',
                'users.email',
                'users.created_at as user_created_at',
                'users.permission',
                'users.updated_at as user_updated_at',
                'users.remember_token',
                'users.email_verified_at'
            )
            ->where('leave_days.ld_year', $year)
            ->get()
            ->map(function ($item) use ($totalLeaveDaysByMonth) {
                $monthlyLeaveDays = [];
                foreach ($totalLeaveDaysByMonth as $key => $totalDays) {
                    if ($item->ld_user_id == $totalDays["n_user_id"]) {
                        $monthlyLeaveDays[] = $totalDays;
                    }
                }
                return [
                    'user' => [
                        'id' => $item->user_id,
                        'name' => $item->user_name,
                        'email' => $item->email,
                        'created_at' => $item->user_created_at,
                        'permission' => $item->permission,
                        'updated_at' => $item->user_updated_at,
                        'remember_token' => $item->remember_token,
                        'email_verified_at' => $item->email_verified_at,
                    ],
                    'leaveDay' => [
                        'id' => $item->id,
                        'ld_user_id' => $item->ld_user_id,
                        'ld_day' => $item->ld_day,
                        'ld_year' => $item->ld_year,
                        'ld_date_additional' => $item->ld_date_additional,
                        'ld_note' => $item->ld_note,
                        'created_at' => $item->created_at,
                        'updated_at' => $item->updated_at,
                    ],
                    'monthlyLeaveDays' => $monthlyLeaveDays,
                ];
            });
        return $leaveDays;
    }

    public function saveNoteLeave(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'totalLeave' => 'required|numeric|min:0|max:20',
            // 'dayAdditional' => 'required|numeric|min:0|max:20',
            // 'note' => 'required|string|max:255',
        ]);

        if ($validator->fails()) {
            return AbstractController::ResultError($validator->errors());
        }

        $validatedData = $request->all();
        $leaveDays = LeaveDays::find($validatedData['id']);

        $leaveDays->ld_day = $validatedData['totalLeave'];
        $leaveDays->ld_date_additional = $validatedData['dayAdditional']; // Assuming you have this field to store additional days
        $leaveDays->ld_note = $validatedData['note'];

        $leaveDays->save();

        return response()->json(['status' => true, 'message' => 'Updated successfully']);
    }
}
