<?php

namespace App\Http\Controllers\Api\Admin;

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 UserController extends Controller
{
    public function index(Request $request)
    {
        $data = User::with('profile');

        $search = $request->input('search.value', '');
        if (!empty($search)) {
            $data->where(function ($query) use ($search) {
                $query->where('name', 'like', '%' . $search . '%')
                    ->orWhere('email', 'like', '%' . $search . '%')
                    ->orWhereHas('profile', function ($q) use ($search) {
                        $q->where('nip', 'like', '%' . $search . '%')
                          ->orWhere('position', 'like', '%' . $search . '%');
                    });
            });
        }

        if ($request->has('role') && !empty($request->role)) {
            $data->where('role', $request->role);
        }

        $total_data = $data->get()->count();
        $length = intval($request->input('length', 0));
        $start = intval($request->input('start', 0));

        $data = $data->orderBy("id", "desc");
        if (!$length && !$start) {
            $data = $data->get();
        } else {
            $data = $data->skip($start)->take($length)->get();
        }

        return response()->json([
            'message' => 'Data berhasil diambil.',
            'data' => $data,
            'draw' => $request->input('draw'),
            'recordsTotal' => $total_data,
            'recordsFiltered' => $total_data,
        ], 200);
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users',
            'password' => 'required|min:6',
            'role' => 'required|in:admin,karyawan',
            'nip' => 'required|unique:user_profiles',
            '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 = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
            'role' => $request->role,
        ]);

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

        UserProfile::create([
            'user_id' => $user->id,
            'nip' => $request->nip,
            'position' => $request->position,
            'phone_number' => $request->phone_number,
            'profile_photo' => $profilePhoto,
        ]);

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

    public function show(string $id)
    {
        $data = User::with('profile')->find($id);

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

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

    public function update(Request $request, string $id)
    {
        $user = User::find($id);

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

        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email,' . $id,
            'password' => 'nullable|min:6',
            'role' => 'required|in:admin,karyawan',
            'nip' => 'required|unique:user_profiles,nip,' . $user->profile->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);
        }

        $userData = [
            'name' => $request->name,
            'email' => $request->email,
            'role' => $request->role,
        ];

        if ($request->filled('password')) {
            $userData['password'] = Hash::make($request->password);
        }

        $user->update($userData);

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

            $photo = $request->file('profile_photo');
            $profilePhoto = time() . '_' . $photo->getClientOriginalName();
            $photo->storeAs('public/profiles', $profilePhoto);
        }

        $user->profile->update([
            'nip' => $request->nip,
            'position' => $request->position,
            'phone_number' => $request->phone_number,
            'profile_photo' => $profilePhoto,
        ]);

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

    public function destroy(string $id)
    {
        $user = User::find($id);

        if ($user->id == auth()->user()->id) {
            return response()->json([
                'message' => 'Anda tidak dapat menghapus diri sendiri.',
                'data' => null
            ], 422);
        }

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

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

        $user->delete();

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

    public function all()
    {
        $data = User::with('profile')->where('role', 'karyawan')->get();

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