<?php

namespace App\Http\Controllers\Api\Auth;

use App\Models\User;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Cookie;
use Laravel\Sanctum\PersonalAccessToken;
use Illuminate\Support\Facades\Validator;

class AuthController extends Controller
{
    public function login(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
            'password' => 'required',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'message' => Str::ucfirst($validator->errors()->first()),
                'data' => null
            ], 422);
        }

        $user = User::where('email', $request->email)->first();

        if (!$user || !Hash::check($request->password, $user->password)) {
            return response()->json([
                'message' => 'Email atau password salah.',
                'data' => null
            ], 401);
        }

        // ✅ Jika login dari mobile dan rolenya admin, tolak
        if ($request->header('X-Platform') === 'mobile' && $user->role === 'admin') {
            return response()->json([
                'message' => 'Admin tidak dapat login melalui aplikasi mobile.',
                'data' => null
            ], 403);
        }

        $user->tokens()->delete();

        $token = $user->createToken('auth_token')->plainTextToken;

        $userData = [
            'id' => $user->id,
            'name' => $user->name,
            'email' => $user->email,
            'role' => $user->role,
            'profile' => $user->profile,
            'token' => $token,
        ];

        return response()->json([
            'message' => 'Login berhasil.',
            'data' => $userData
        ], 200)->cookie(
            '_absensiku_karyawan_token',
            $token,
            60 * 24 * 1 + 5,
            '/',
            null,
            true,
            false,
            false,
            'Lax'
        );
    }


    public function getUserByToken($token)
    {
        $accessToken = PersonalAccessToken::findToken($token);

        if (!$accessToken) {
            return response()->json([
                'message' => 'Token tidak valid atau sudah kadaluarsa.',
                'data' => null
            ], 401);
        }

        if ($accessToken->expires_at && Carbon::parse($accessToken->expires_at)->isPast()) {
            $accessToken->delete();
            return response()->json([
                'message' => 'Token tidak valid atau sudah kadaluarsa.',
                'data' => null
            ], 401);
        }

        $user = $accessToken->tokenable->load('profile');

        return response()->json([
            'message' => 'User ditemukan.',
            'data' => $user
        ]);
    }

    public function logout(Request $request)
    {
        $user = $request->user();

        if ($user) {
            if ($request->bearerToken()) {
                $user->tokens()->delete();
            }
        }

        return response()->json([
            'message' => 'Logout berhasil.',
            'data' => null
        ], 200)->cookie(Cookie::forget('_absensiku_karyawan_token'));
    }

    public function profile(Request $request)
    {
        $user = $request->user()->load('profile');

        return response()->json([
            'message' => 'Profile berhasil diambil.',
            'data' => $user
        ], 200);
    }

    public function updateProfile(Request $request)
    {
        $user = $request->user();

        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'nip' => 'required|string|unique:user_profiles,nip,' . ($user->profile->id ?? 'null') . ',id',
            'position' => 'required|string|max:255',
            'phone_number' => 'required|string|max:20',
            'profile_photo' => 'nullable|image|mimes:jpeg,png,jpg|max:2048',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'message' => Str::ucfirst($validator->errors()->first()),
                'data' => null
            ], 422);
        }

        $user->update([
            'name' => $request->name,
        ]);

        $profileData = [
            'nip' => $request->nip,
            'position' => $request->position,
            'phone_number' => $request->phone_number,
        ];

        if ($request->hasFile('profile_photo')) {
            $photo = $request->file('profile_photo');
            $filename = time() . '_' . $photo->getClientOriginalName();
            $photo->storeAs('public/profiles', $filename);

            if ($user->profile && $user->profile->profile_photo) {
                $oldPhotoPath = storage_path('app/public/profiles/' . $user->profile->profile_photo);
                if (file_exists($oldPhotoPath)) {
                    unlink($oldPhotoPath);
                }
            }

            $profileData['profile_photo'] = $filename;
        }

        $user->profile()->updateOrCreate(
            ['user_id' => $user->id],
            $profileData
        );

        return response()->json([
            'message' => 'Profile berhasil diubah.',
            'data' => $user->load('profile')
        ], 200);
    }

    public function changePassword(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'current_password' => 'required',
            'new_password' => 'required|min:6|confirmed',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'message' => Str::ucfirst($validator->errors()->first()),
                'data' => null
            ], 422);
        }

        $user = $request->user();

        if (!Hash::check($request->current_password, $user->password)) {
            return response()->json([
                'message' => 'Password lama tidak sesuai.',
                'data' => null
            ], 422);
        }

        $user->update([
            'password' => Hash::make($request->new_password),
        ]);

        return response()->json([
            'message' => 'Password berhasil diubah.',
            'data' => null
        ], 200);
    }
    public function register(Request $request)
{
    $validator = Validator::make($request->all(), [
        'name' => 'required|string|max:255',
        'email' => 'required|email|unique:users,email',
        'role' => 'required|in:admin,karyawan',
        'password' => 'required|string|min:6|confirmed',
    ]);

    if ($validator->fails()) {
        return response()->json([
            'message' => $validator->errors()->first()
        ], 422);
    }

    $user = User::create([
        'name' => $request->name,
        'email' => $request->email,
        'role' => $request->role,
        'password' => Hash::make($request->password),
    ]);

    $token = $user->createToken('auth_token')->plainTextToken;

    return response()->json([
        'message' => 'Registrasi berhasil.',
        'data' => [
            'user' => $user,
            'token' => $token,
        ],
    ], 201);
}

}
