<?php

namespace App\Http\Controllers\Api\Employee;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\UserProfile;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;

class ProfileController extends Controller
{
    public function show()
    {
        $user = auth()->user();
        $data = User::with(['profile'])->find($user->id);

        if (!$data) {
            return response()->json([
                'message' => 'Data tidak ditemukan.',
                'data' => null
            ], 422);
        }

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

    public function update(Request $request)
    {
        $user = User::find(auth()->user()->id);

        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users,email,' . $user->id,
            'phone_number' => 'required|string|max:20',
            'nip' => 'required|string|max:50',
            'position' => 'required|string|max:255',
            'profile_photo' => 'nullable|image|mimes:jpeg,png,jpg|max:2048', // 2MB
        ]);

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

        // Update user dasar
        $user->update([
            'name' => $request->name,
            'email' => $request->email,
        ]);

        // Tangani foto jika ada
        $profilePhotoPath = $user->profile->profile_photo ?? null;
        if ($request->hasFile('profile_photo')) {
            if ($profilePhotoPath && file_exists(storage_path('app/public/' . $profilePhotoPath))) {
                unlink(storage_path('app/public/' . $profilePhotoPath));
            }
            $photo = $request->file('profile_photo');
            $filename = time() . '_' . $user->id . '_profile.' . $photo->getClientOriginalExtension();
            $profilePhotoPath = $photo->storeAs('profiles', $filename, 'public');
        }

        // Update atau create profile, termasuk position
        UserProfile::updateOrCreate(
            ['user_id' => $user->id],
            [
                'phone_number' => $request->phone_number,
                'nip' => $request->nip,
                'position' => $request->position,
                'profile_photo' => $profilePhotoPath,
            ]
        );

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

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

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

        $user = User::find(auth()->user()->id);

        if (!Hash::check($request->current_password, $user->password)) {
            return response()->json([
                'message' => 'Password saat ini 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 uploadPhoto(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'profile_photo' => 'required|image|mimes:jpeg,png,jpg|max:2048', // 2MB
        ]);

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

        $user = auth()->user();

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

            $photo = $request->file('profile_photo');
            $filename = time() . '_' . $user->id . '_profile.' . $photo->getClientOriginalExtension();
            $profilePhotoPath = $photo->storeAs('profiles', $filename, 'public');

            // Hanya update foto, posisi dll tetap
            UserProfile::updateOrCreate(
                ['user_id' => $user->id],
                ['profile_photo' => $profilePhotoPath]
            );

            return response()->json([
                'message' => 'Foto profil berhasil diupload.',
                'data' => [
                    'profile_photo' => $profilePhotoPath,
                    'profile_photo_url' => asset('storage/' . $profilePhotoPath)
                ]
            ], 200);
        }

        return response()->json([
            'message' => 'Tidak ada file yang diupload.',
            'data' => null
        ], 422);
    }

    public function deletePhoto()
    {
        $user = auth()->user();

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

            $user->profile->update(['profile_photo' => null]);

            return response()->json([
                'message' => 'Foto profil berhasil dihapus.',
                'data' => null
            ], 200);
        }

        return response()->json([
            'message' => 'Tidak ada foto profil yang ditemukan.',
            'data' => null
        ], 422);
    }
}
