<?php

namespace App\Http\Controllers;

use App\Models\UserProfile;
use Illuminate\Http\Request;
use App\Models\StaffDetail;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;
use App\Models\UsersDetail;
use App\Models\User;
// use App\Models\UserDetail;

class DetailProfileController extends Controller
{
    public function index()
    {
        try {
            $userDetails = UsersDetail::with('user')->latest()->paginate(10);

            return response()->json([
                'success' => true,
                'data' => $userDetails
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch user details: ' . $e->getMessage()
            ], 500);
        }
    }


    public function getUserDetailById()
    {
        try {
            $currentUser = Auth::user();
            $userDetaill = UsersDetail::with('user')->where('user_id', $currentUser->id)->firstOrFail();
            return response()->json(['data' => $userDetaill], 200);
        } catch (\Throwable $th) {
            return response()->json(['message' => 'User detail not found', 'error' => $th->getMessage()], 404); // Mengembalikan pesan kesalahan jika tidak ditemukan
        }
    }

    public function searchUserDetails(Request $request)
    {
        try {
            $query = UsersDetail::with('user');
            
            // Filter berdasarkan relasi user
            if ($request->has('name')) {
                $query->whereHas('user', function ($q) use ($request) {
                    $q->where('name', 'like', '%' . $request->name . '%');
                });
            }

            if ($request->has('email')) {
                $query->whereHas('user', function ($q) use ($request) {
                    $q->where('email', 'like', '%' . $request->email . '%');
                });
            }

            // Filter langsung dari kolom UserDetail
            if ($request->has('phone_number')) {
                $query->where('phone_number', 'like', '%' . $request->phone_number . '%');
            }

            if ($request->has('university')) {
                $query->where('university', 'like', '%' . $request->university . '%');
            }

            $results = $query->latest()->paginate(10);

            return response()->json([
                'success' => true,
                'data' => $results
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Gagal melakukan pencarian: ' . $e->getMessage()
            ], 500);
        }
    }

    public function createOrUpdateUserDetail(Request $request)
{
    try {
        $userId = auth()->id();
        if (!$userId) {
            return response()->json(['message' => 'Unauthorized'], 401);
        }

        // Validasi data
        $data = $request->validate([
            'gender'        => 'nullable|in:male,female',
            'dob'           => 'nullable|date',
            'hobby'         => 'nullable|string',
            'sosmed_link'   => 'nullable|url',
            'address'       => 'nullable|string',
            'phone_number'  => 'nullable|string|unique:user_details,phone_number,' . $userId . ',user_id',
            'id_card'       => 'nullable|image|max:2048',
            'profile_photo' => 'nullable|image|max:2048',
            'cover_photo'   => 'nullable|image|max:2048',
        ]);

        // Ambil data existing (jika ada)
        $userDetail = UsersDetail::where('user_id', $userId)->first();

        // ✅ Upload file jika ada
        $data['profile_photo'] = $this->handlePhotoUpload($request, 'profile_photo', 'profileUser/', $userDetail?->profile_photo);
        $data['cover_photo']   = $this->handlePhotoUpload($request, 'cover_photo', 'coverUser/', $userDetail?->cover_photo);
        $data['id_card']       = $this->handlePhotoUpload($request, 'id_card', 'idCardUser/', $userDetail?->id_card);

        // Tambahkan user_id untuk create
        $data['user_id'] = $userId;

        // ✅ Update atau Buat Baru
        if ($userDetail) {
            $userDetail->update(array_filter($data));
        } else {
            $userDetail = UsersDetail::create(array_filter($data));
        }

        // ✅ Cek validasi: Jika upload foto, maka data penting tidak boleh kosong
        $isPhotoFilled = $request->hasFile('profile_photo') || $request->hasFile('cover_photo') || $request->hasFile('id_card');
        $isDetailEmpty = empty($userDetail->dob) || empty($userDetail->gender) || empty($userDetail->address) || empty($userDetail->phone_number);

        if ($isPhotoFilled && $isDetailEmpty) {
            return response()->json([
                'message' => 'Lengkapi detail profil terlebih dahulu sebelum upload foto.'
            ], 422);
        }

        return response()->json([
            'userDetail' => $userDetail->load('user')
        ], 200);

    } catch (\Exception $e) {
        return response()->json(['message' => 'Failed to process user detail: ' . $e->getMessage()], 500);
    }
}


    private function handlePhotoUpload(Request $request, $key, $folder, $oldFile = null)
    {
        if ($request->hasFile($key)) {
            if ($oldFile) {
                $this->deleteFile($folder . basename($oldFile));
            }
            return $this->uploadFile($request->file($key), $key, $folder);
        }
        return $oldFile;
    }

    private function uploadFile($file, $type, $folder)
    {
        $filename = time() . '_' . $type . '.' . $file->getClientOriginalExtension();
        $file->move(public_path('storage/' . $folder), $filename);
        return Storage::url($folder . $filename);
    }

    private function deleteFile($path)
    {
        $fullPath = public_path('storage/' . $path);
        if (file_exists($fullPath)) {
            unlink($fullPath);
        }
    }



}
