<?php

namespace Modules\Admin\app\Http\Controllers;

use App\Events\WarningChekinLate;
use App\Http\Controllers\Controller;
use App\Mail\CheckinLateMail;
use App\Traits\AnalyzeData;
use App\Traits\HasFilterRequest;
use App\Traits\HasOrderByRequest;
use App\Traits\HasSearchRequest;
use Carbon\Carbon;
use DateTime;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;
use Modules\Admin\app\Models\Admin;
use Modules\Admin\app\Models\MonthlyTimekeeping;
use Modules\Admin\app\Models\Tracking;
use Illuminate\Support\Facades\DB;

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

    private $CHECK_IN = 'check in';
    private $CHECK_OUT = 'check out';

    public function __construct()
    {
        // Bỏ qua middleware 'checkApiToken' cho hàm 'myFunction'
        $this->middleware('api')->except('create');
    }

    public function get(Request $request)
    {
        $tracking = new Tracking;

        // Order by
        $this->orderByRequest($tracking, $request);

        $tracking->orderBy('created_at', 'desc');
        // Filter
        $this->filterRequest(
            builder: $tracking,
            request: $request,
            filterKeys: [
                'created_at' => self::F_IN_DATETIME,
                'time_string' => self::F_TEXT,
                'name' => self::F_TEXT,
                'status' => self::F_TEXT
            ]
        );

        $this->searchRequest(
            builder: $tracking,
            value: $request->get('search'),
            fields: [
                'name',
                'time_string',
                'status'
            ]
        );

        $responseData = array_merge(
            $tracking->paginate($request->get('per_page'))->toArray(),
            ['status' => true]
        );

        // $users = Admin::where('permission', '!=', 'admin')->get();
        $users = Admin::where('permission', 'like', '%staff%')->get();
        $responseData['users'] = $users;
        return response()->json($responseData);
    }

    public function create(Request $request)
    {
        try {
            $validatedData = $request->validate([
                'name' => 'required',
                'time_string' => 'required',
                'status' => 'required',
            ]);
            $payload = $request->only(['name', 'time_string', 'status']);
            if ($request->has('created_at')) {
                $payload['created_at'] = Carbon::create($request->created_at)->setTimezone(env('TIME_ZONE'));
            } else {
                $payload['created_at'] = Carbon::create(new DateTime())->setTimezone(env('TIME_ZONE'));
            }
            $user = Admin::where('name', $payload['name'])->first();
            $date = Carbon::create(new DateTime())->setTimezone(env('TIME_ZONE'))->format('Y-m-d');
            if ($user) {
                $payload['user_id'] = $user->id;
                $latest = Tracking::where('name', $payload['name'])->whereDate('created_at', $date)->latest()->first();
                if ($latest) {
                    if ($payload['status'] == $this->CHECK_IN || $payload['status'] == $this->CHECK_OUT) {
                        if ($latest->status == $this->CHECK_IN) {
                            $payload['status'] = $this->CHECK_OUT;
                        }
                        if ($latest->status == $this->CHECK_OUT) {
                            $payload['status'] = $this->CHECK_IN;
                        }
                        $tracking = Tracking::create($payload);
                        $this->createOrUpdateRecordForCurrentMonth($payload['created_at']->month, $payload['created_at']->year);
                        return response()->json([
                            'data' => $tracking,
                            'check_status' => $payload['status'],
                            'status' => true
                        ]);
                    } else {
                        return response()->json([
                            'data' => "STATUS INVALID",
                            'status' => false
                        ]);
                    }
                } else {
                    $payload['status'] = $this->CHECK_IN;
                    $tracking = Tracking::create($payload);
                    $this->createOrUpdateRecordForCurrentMonth($payload['created_at']->month, $payload['created_at']->year);
                    return response()->json([
                        'data' => $tracking,
                        'check_status' => $this->CHECK_IN,
                        'status' => true
                    ]);
                }
            }

            return response()->json([
                'data' => "USER NOT EXIST",
                'status' => false
            ]);
        } catch (\Illuminate\Validation\ValidationException $e) {
            return response()->json([
                'data' => "IMPORT DATA FAIL",
                'status' => false
            ], 422);
        }
    }

    public function update(Request $request)
    {
        $id = $request->get('id');

        $tracking = Tracking::find($id);
        $payload = $request->all();
        if ($request->has('created_at')) {
            $payload['created_at'] = Carbon::create($request->created_at)->setTimezone(env('TIME_ZONE'));
        } else {
            $payload['created_at'] = Carbon::create(new DateTime())->setTimezone(env('TIME_ZONE'));
        }
        if ($tracking) {
            $tracking->update($payload);
            $this->createOrUpdateRecordForCurrentMonth($payload['created_at']->month, $payload['created_at']->year);
        }
        return response()->json([
            'data' => $tracking,
            'status' => true
        ]);
    }

    public function saveImage(Request $request)
    {
        $id = $request->get('id');

        $tracking = Tracking::find($id);

        $user = Admin::find($tracking->user_id);
        $this->sendCheckinLateMail($user, $tracking->created_at, $tracking->status);
        if ($request->hasFile('image')) {
            $file = $request->file('image');
            $filename = $request->file_name;
            $path = 'screenshot' . "/$filename";

            Storage::disk('public')->put(
                path: $path,
                contents: $file->get()
            );
            $tracking->image = $path;

            $tracking->save();
            $date = Carbon::create(new DateTime())->setTimezone(env('TIME_ZONE'));
            $this->createOrUpdateRecordForCurrentMonth($date->month, $date->year);
        }
        return response()->json([
            'data' => $tracking,
            'status' => true
        ]);
    }

    public function delete(Request $request)
    {
        $id = $request->get('id');

        Tracking::destroy($id);
        $date = Carbon::create(new DateTime())->setTimezone(env('TIME_ZONE'));
        $this->createOrUpdateRecordForCurrentMonth($date->month, $date->year);
        return response()->json([
            'status' => true
        ]);
    }

    // public function sendCheckinLateMail()
    private function sendCheckinLateMail($user, $time, $status)
    {
        // $status = $this->CHECK_IN;
        // $lastCheck =Tracking::find(1)->created_at;
        // $user = Admin::where('name', 'LE TAN LUAN')->first();
        if ($status === $this->CHECK_IN) {
            $morning_time = Carbon::createFromTimeString('07:30AM')->setTimezone(env('TIME_ZONE'));
            $morning_condition_time = Carbon::createFromTimeString('07:40AM')->setTimezone(env('TIME_ZONE'));
            $afternoon_time = Carbon::createFromTimeString('11:30AM')->setTimezone(env('TIME_ZONE'));
            $afternoon_condition_time = Carbon::createFromTimeString('01:10PM')->setTimezone(env('TIME_ZONE'));
            $admin_mails = Admin::where('permission', 'like', '%admin%')->pluck('email');

            if ($time->greaterThan($morning_condition_time) && $time->lessThan($afternoon_time)) {
                $period = 'morning';
                $minutes_late = $morning_time->diffInMinutes($time);
                $data = array(
                    "email_template" => "email.checkin_late_notification",
                    "email" => $user->email,
                    "name" => $user->name,
                    "admin_mails" => $admin_mails,
                    "message1" => "Your " . $period . " starts " . $minutes_late . " minutes late",
                    "message2" => "You checked in at [" . $time . "]",
                    "url" => env('ADMIN_URL') . "/tracking?search=&per_page=10&page=1&timezone=Asia%2FSaigon&name=" . $user->name . "&time_string=" . $time->format("Y-m-d H:i") . "&status=check+in",
                    "subject" => "[Management System] Late warning - " . $user->name
                );
                Mail::to($user->email)->cc($admin_mails)->send(new CheckinLateMail($data));
            }

            // if ($time->greaterThan($afternoon_condition_time))
            // {
            //     $period = 'afternoon';
            //     $minutes_late = $afternoon_time->diffInMinutes($time);
            //     $data = array(
            //         "email_template" => "email.checkin_late_notification",
            //         "email" => $user->email,
            //         "name" => $user->name,
            //         "message1" => "Your ". $period ." starts <b>". $minutes_late ."</b> minutes late",
            //         "message2" => "You checked in at <b>[" . $time ."]</b>",
            //         "url" => env('ADMIN_URL')."/tracking?search=&per_page=10&page=1&timezone=Asia%2FSaigon&name=".$user->name."&time_string=".$time->format("Y-m-d H:i")."&status=check+in",
            //         "subject" => "[Management System] Late warning"
            //     );
            //     Mail::to($user->email)->cc($admin_mails)->send(new CheckinLateMail($data));
            // }


        }
    }

    public function getSummaryTracking(Request $request)
    {
        $request->validate([
            'userID' => 'required|exists:users,id',
            'fromDate' => 'nullable|date',
            'toDate' => 'nullable|date',
        ]);

        $userID = $request->input('userID');
        $startDate = $request->input('fromDate');
        $endDate = $request->input('toDate');

        $trackingData = Tracking::where('user_id', $userID);

        if ($startDate && $endDate) {
            $trackingData->whereBetween(
                DB::raw("STR_TO_DATE(time_string, '%Y-%m-%d %H:%i:%s')"),
                [$startDate, $endDate . ' 23:59:59']
            );
        } elseif ($startDate) {
            $trackingData->where(
                DB::raw("STR_TO_DATE(time_string, '%Y-%m-%d %H:%i:%s')"),
                '>=',
                $startDate
            );
        } elseif ($endDate) {
            $trackingData->where(
                DB::raw("STR_TO_DATE(time_string, '%Y-%m-%d %H:%i:%s')"),
                '<=',
                $endDate . ' 23:59:59'
            );
        }


        $onTimeMorning = 0;
        $lateMorning = 0;
        $onTimeAfternoon = 0;
        $lateAfternoon = 0;
        $returnTracking = $trackingData->get();
        $listLate = [];

        $returnTracking->groupBy(function ($record) {
            return Carbon::parse($record->time_string)->toDateString();
        })->each(function ($records, $date) use ($userID, &$listLate, &$onTimeMorning, &$lateMorning, &$onTimeAfternoon, &$lateAfternoon, &$datesChecked) {
            $morningCheck = $records->filter(function ($record) {
                return Carbon::parse($record->time_string)->hour < 12;
            })->sortBy('time_string')->first();

            $afternoonCheck = $records->filter(function ($record) {
                $time = Carbon::parse($record->time_string)->hour;
                return $time >= 12 && $time <= 14;
            })->sortBy('time_string')->first();

            $morningTime = Carbon::parse($date)->setTime(7, 40, 0);
            $afternoonTime = Carbon::parse($date)->setTime(13, 10, 0);
            $checkOutAfternoonTime = Carbon::parse($date)->setTime(15, 00, 0);


            if ($morningCheck) {
                $checkInTime = Carbon::parse($morningCheck->time_string);
                if ($checkInTime->lessThanOrEqualTo($morningTime)) {
                    $onTimeMorning++;
                } else {
                    array_push($listLate, $morningCheck->id);
                    $lateMorning++;
                }
            }

            if ($afternoonCheck) {
                $checkInTime = Carbon::parse($afternoonCheck->time_string);
                if ($checkInTime->lessThanOrEqualTo($afternoonTime)) {
                    $onTimeAfternoon++;
                } else {
                    array_push($listLate, $afternoonCheck->id);
                    $lateAfternoon++;
                }
            } else {
                // print ($date . "\n");
                $checkOutAfternoon = Tracking::where('user_id', $userID)->whereBetween(
                    DB::raw("STR_TO_DATE(time_string, '%Y-%m-%d %H:%i:%s')"),
                    [$date, $date . ' 23:59:59'],
                )->where("status", "check out")->first();
                // check if not check-in afternoon but has check out
                if ($checkOutAfternoon) {
                    $timeCheck = Carbon::parse($checkOutAfternoon->time_string);
                    // print ($timeCheck . "\n");
                    if ($checkOutAfternoon && $timeCheck->greaterThanOrEqualTo($checkOutAfternoonTime)) {
                        $onTimeAfternoon++;
                    }
                }
            }

        });

        // ** Add `isLate` flag to each record **
        foreach ($returnTracking as $record) {
            if (in_array($record->id, $listLate)) {
                $record->isLate = true;
            }
        }

        return AbstractController::ResultSuccess([
            'on_time_morning' => $onTimeMorning,
            'late_morning' => $lateMorning,
            'on_time_afternoon' => $onTimeAfternoon,
            'late_afternoon' => $lateAfternoon,
            'value' => $returnTracking
        ]);
    }
}
