<?php

namespace Modules\Admin\app\Http\Controllers;

use App\Helper\Cache\CurrentMonthTimekeeping;
use App\Http\Controllers\Controller;
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\Storage;
use Modules\Admin\app\Models\Admin;
use Modules\Admin\app\Models\MonthlyTimekeeping;
use Modules\Admin\app\Models\Tracking;

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);
        // $id = $request->get('id');

        // $tracking = Tracking::find($id);
        // $payload = $request->all();

        // if ($tracking) {
        //     $tracking->update($payload);
        // }
        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
        ]);
    }
}
