<?php

namespace App\Http\Controllers;

use App\Models\Presensi;
use Auth;
use Illuminate\Http\Request;
use App\Models\UserProfile;
use App\Models\CompanyUser;
use Symfony\Component\HttpFoundation\IpUtils;

class PresensiController extends Controller
{

    public function __construct()
    {
        $this->middleware('checkStaff');
    }
    
    // public function create(Request $request,$id)
    // {
    //     try {
    //         $presensi = Presensi::where('user_id', $id)->whereDate('created_at', now()->toDateString())->first();
    //         if($presensi) {
    //             return response()->json(['message' => 'Anda Sudah Presensi Untuk Hari ini'], 400);
    //         }
    //         $presensi = new Presensi;
    //         $presensi->user_id = $request->id;
    //         // cek selain user_type_id (3 dan 5) akan dilakukan pengecekan jaringan
    //         // tambahkan disini pengecekan terhubung ke jaringan wifi kantor 
    //         $presensi->masuk = now()->setTimezone('Asia/Jakarta')->format('H:i:s');
    //         $presensi->status = now()->setTimezone('Asia/Jakarta')->format('H:i') > '08:30'? 'Late' : (now()->setTimezone('Asia/Jakarta')->format('H:i') < '08:00'? 'Early' : null);
    //         $presensi->save();

    //         return response()->json(['message' => 'Presensi masuk berhasil'], 200);
    //     } catch (\Exception $e) {
    //         return response()->json(['message' => 'Failed to create presensi', 'error' => $e->getMessage()], 500);
    //     }
    // }

    public function create(Request $request, $id)
    {
        try {
            
            $presensi = Presensi::where('user_id', $id)->whereDate('created_at', now()->toDateString())->first();
            if ($presensi) {
                return response()->json(['message' => 'Anda Sudah Presensi Untuk Hari ini'], 400);
            }

            $user = UserProfile::find($id);
            if (!$user) {
                return response()->json(['message' => 'User tidak ditemukan'], 404);
            }
            
            $companyUser = CompanyUser::where('user_id', $id)->first();
            if (!$companyUser) {
                return response()->json(['message' => 'Company User tidak ditemukan'], 404);
            }
            
            $presensi = new Presensi;
            $presensi->user_id = $id;
            $presensi->company_id = $companyUser->company_id; 
            $presensi->masuk = now()->setTimezone('Asia/Jakarta')->format('H:i:s');
            $presensi->status = now()->setTimezone('Asia/Jakarta')->format('H:i') > '08:30' 
                ? 'Late' 
                : (now()->setTimezone('Asia/Jakarta')->format('H:i') < '08:00' ? 'Early' : null);
            $presensi->save();

            return response()->json(['message' => 'Presensi masuk berhasil'], 200);
        } catch (\Exception $e) {
            return response()->json(['message' => 'Failed to create presensi', 'error' => $e->getMessage()], 500);
        }
    }


    // public function update($id)
    // {
    //     try {
    //         $presensi = Presensi::where('id', $id)->whereDate('created_at', now()->toDateString())->first();
    //         if(!$presensi) {
    //             return response()->json(['message' => 'Anda Belum Melakukan Presensi Hari ini'], 400);
    //         }
    //         $presensi->keluar = now()->setTimezone('Asia/Jakarta')->format('H:i:s');
    //         $presensi->save();

    //         return response()->json(['message' => 'Presensi keluar berhasil'], 200);
    //     } catch (\Exception $e) {
    //         return response()->json(['message' => 'Failed to update presensi', 'error' => $e->getMessage()], 500);
    //     }
    // }
    public function update($user_id)
    {
        try {
            // Mencari presensi terbaru untuk pengguna pada hari ini
            $presensi = Presensi::where('user_id', $user_id)
                ->whereDate('created_at', now()->toDateString())
                ->orderBy('created_at', 'desc') // Mengambil presensi terbaru
                ->first();

            // Jika presensi tidak ditemukan, kembalikan respons error
            if(!$presensi) {
                return response()->json(['message' => 'Anda Belum Melakukan Presensi Hari ini'], 400);
            }

            // Jika presensi keluar sudah ada data maka tampilkan pesan anda sudah check out
            if($presensi->keluar) {
                return response()->json(['message' => 'Anda Sudah Check Out'], 400);
            }

            // Mengisi waktu keluar pada presensi yang ditemukan
            $presensi->keluar = now()->setTimezone('Asia/Jakarta')->format('H:i:s');
            $presensi->save();

            return response()->json(['message' => 'Presensi keluar berhasil'], 200);
        } catch (\Exception $e) {
            return response()->json(['message' => 'Gagal memperbarui presensi', 'error' => $e->getMessage()], 500);
        }
    }


    public function getAllForAdmin()
    {
        try {
            $currentUser = Auth::user();

            if (!in_array($currentUser->user_type_id, [1, 2, 3])) {
                return response()->json(['error' => 'Akses Ditolak.'], 403);
            }
            // $presensi = Presensi::orderBy('created_at', 'desc')->take(7)->get();
            $presensi = Presensi::with('userProfile:id,id,name')
            ->orderBy('created_at', 'desc')
            ->take(7)
            ->get()
            ->map(function ($item) {
                return [
                    'id' => $item->id,
                    'user_id' => $item->userProfile->name ?? 'Unknown', // Ambil nama atau default "Unknown"
                    'masuk' => $item->masuk,
                    'keluar' => $item->keluar,
                    'status' => $item->status,
                    'updated_at' => $item->updated_at,
                ];
            });
            return response()->json($presensi);
        } catch (\Exception $e) {
            return response()->json(['message' => 'Failed to get all presensi', 'error' => $e->getMessage()], 500);
        }
    }

    public function getAllForUser()
    {
        try {
            $presensi = Presensi::where('user_id', Auth::id())
                ->orderBy('created_at', 'desc')
                ->take(7)
                ->get();
            return response()->json($presensi);
        } catch (\Exception $e) {
            return response()->json(['message' => 'Failed to get presensi for user', 'error' => $e->getMessage()], 500);
        }
    }
}
