<?php

namespace Modules\Admin\app\Http\Controllers;

use App\Helper\Cache\CurrentMonthTimekeeping;
use App\Http\Controllers\Controller;
use App\Models\Notes;
use App\Traits\AnalyzeData;
use App\Traits\HasFilterRequest;
use App\Traits\HasOrderByRequest;
use App\Traits\HasSearchRequest;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Modules\Admin\app\Models\Admin;
use Modules\Admin\app\Models\MonthlyTimekeeping;
use Modules\Admin\app\Models\Tracking;

class TimekeepingController extends Controller
{
    use HasOrderByRequest;
    use HasFilterRequest;
    use HasSearchRequest;
    use AnalyzeData;

    public function get(Request $request)
    {
        $currentDate = Carbon::now();
        $currentMonth = $currentDate->month;
        $currentYear = $currentDate->year;
        $data = MonthlyTimekeeping::where('month', '=', $request->month)->where('year', '=', $request->year)->first();
        if ($currentMonth == (int)$request->month && $currentYear == (int)$request->year) {
            $cacheData = CurrentMonthTimekeeping::getCacheCurrentMonthTimekeeping();
            if ($cacheData) {
                $cacheData->data = json_decode($cacheData->data, true);
                return response()->json(['status' => true, 'data' => $cacheData->data, 'working_days' => $cacheData->working_days, 'message' => 'Get from cache']);
            } else {
                $result = $this->analyzeCurrentMonthTimeKeepingData($currentMonth, $currentYear);
                if ($data) {
                    $data->update(['data' => json_encode($result)]);
                    return response()->json(['status' => true, 'data' => $result, 'message' => 'Get from analyzeCurrentMonthTimeKeepingData + update record']);
                }
                MonthlyTimekeeping::create(['month' => $currentMonth, 'year' => $currentYear, 'working_days' => $currentDate->daysInMonth, 'data' => json_encode($result)]);
                return response()->json(['status' => true, 'data' => $result, 'message' => 'Get from analyzeCurrentMonthTimeKeepingData + create record']);
            }
        } else {
            if ($data) {
                $data['data'] = json_decode($data['data']);
                return response()->json(['status' => true, 'data' => $data['data'], 'working_days' => $data['working_days'], 'message' => 'Get from DB']);
            } else {
                $result = $this->analyzeCurrentMonthTimeKeepingData($request->month, $request->year);
                MonthlyTimekeeping::create(['month' => $request->month, 'year' => $request->year, 'working_days' => Carbon::create((int)$request->year, (int)$request->month)->daysInMonth, 'data' => json_encode($result)]);
                return response()->json(['status' => true, 'data' => $result, 'message' => 'Get from analyzeCurrentMonthTimeKeepingData']);
            }
        }
        return response()->json(['status' => false, 'mewssage' => 'Get data failed!']);
    }

    public function addWorkingTimeForMultipleUser(Request $request)
    {
        $user_ids = $request->users;
        $year = $request->year;
        $month = $request->month;
        $day = $request->day;
        $type = $request->type;
        foreach ($user_ids as $id) {
            $user = Admin::find($id);
            $date = Carbon::create($year, $month, $day)->setTimezone(env('TIME_ZONE'));
            $start = $date->copy()->setTime(7, 31, 11);
            $end = $type == 'half' ? $date->copy()->setTime(11, 31, 11) : $date->copy()->setTime(17, 1, 11);
            Tracking::insert([
                [
                    'name' => $user->name,
                    'user_id' => $user->id,
                    'status' => 'check in',
                    'time_string' => $start->format('Y-m-d H:i:s'),
                    'created_at' => $start->setTimezone('UTC')
                ],
                [
                    'name' => $user->name,
                    'user_id' => $user->id,
                    'status' => 'check out',
                    'time_string' => $end->format('Y-m-d H:i:s'),
                    'created_at' => $end->setTimezone('UTC')
                ]
            ]);
        }
        $this->createOrUpdateRecordForCurrentMonth($month, $year);
        return response()->json(['status' => true, 'message' => 'Add successfully']);
    }

    public function saveWorkingDays(Request $request)
    {
        $data = MonthlyTimekeeping::where('month', '=', $request->month)->where('year', '=', $request->year)->first();
        if ($data) {
            $data->update(['working_days' => $request->working_days]);
            $this->createOrUpdateRecordForCurrentMonth($request->month, $request->year);
            return response()->json(['status' => true, 'message' => 'Update successful']);
        }

        return response()->json(['status' => false, 'message' => 'Update failed']);
    }

    public function addNoteForUser(Request $request)
    {
        $user_id = $request->users["id"] ?? "";
        $month = $request->month;
        $year = $request->year;
        $day = $request->day;
        $time_type = $request->type;
        $reason = $request->reason;
        $note = $request->note;

        if ($user_id == "") {
            return response()->json(['status' => false, 'message' => 'User not found!']);
        }

        $existingNote = Notes::where('n_user_id', $user_id)
            ->where('n_day', $day)
            ->where('n_month', $month)
            ->where('n_year', $year)
            ->where('n_reason', $reason)
            ->first();

        if ($existingNote) {
            // Cập nhật bản ghi nếu đã tồn tại
            $existingNote->update([
                'n_day' => $day,
                'n_month' => $month,
                'n_year' => $year,
                'n_time_type' => $time_type,
                'n_reason' => $reason,
                'n_note' => $note
            ]);
        } else {
            // Chèn bản ghi mới nếu không tồn tại
            Notes::create([
                'n_user_id' => $user_id,
                'n_day' => $day,
                'n_month' => $month,
                'n_year' => $year,
                'n_time_type' => $time_type,
                'n_reason' => $reason,
                'n_note' => $note
            ]);
        }

        $this->createOrUpdateRecordForCurrentMonth($month, $year);

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


    public function updateCacheMonth(Request $request)
    {
        $month = $request->month;
        $year = $request->year;

        $this->createOrUpdateRecordForCurrentMonth($month, $year);

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

    public function deleteNote(Request $request)
    {
        $rules = [
            'id' => 'required'
        ];

        // Validate the request
        $request->validate($rules);

        $id = $request->input('id');

        $month = $request->month;
        $year = $request->year;

        $note = Notes::find($id);
        if ($note) {
            $note->delete();
            $this->createOrUpdateRecordForCurrentMonth($month, $year);
            return response()->json(['message' => 'Delete success', 'status' => true]);
        }

        return response()->json(['message' => 'Delete fail', 'status' => false]);
    }
}
