<?php

namespace App\Http\Controllers;

use App\Models\Pegawai;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class PegawaiController extends Controller
{
    // 1. Tampil Semua Data
    public function index()
    {
        $data = Pegawai::with('user:id,email,role')->get();
        return response()->json(['status' => true, 'data' => $data], 200);
    }

    // 2. Simpan Data Baru (Oleh Admin/Super Admin)
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name'     => 'required|string|max:255',
            'email'    => 'required|email|unique:users,email',
            'password' => 'required|string|min:6',
            'nip'      => 'required|string|unique:pegawai,nip',
            'nama'     => 'required|string|max:255',
            'jabatan'  => 'required|string|max:255',
            'role'     => 'nullable|in:super_admin,admin,pegawai',
        ]);

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

        DB::beginTransaction();
        try {
            $user = User::create([
                'name'     => $request->name,
                'email'    => $request->email,
                'password' => Hash::make($request->password),
                'role'     => $request->role ?? 'pegawai',
            ]);

            Pegawai::create([
                'nip'     => $request->nip,
                'nama'    => $request->nama,
                'jabatan' => $request->jabatan,
                'user_id' => $user->id,
            ]);

            DB::commit();
            return response()->json(['status' => true, 'message' => 'Pegawai berhasil ditambah'], 201);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['status' => false, 'error' => $e->getMessage()], 500);
        }
    }

    // 3. Lihat Detail
    public function show($id)
    {
        $pegawai = Pegawai::with('user:id,email,role')->find($id);
        if (!$pegawai) return response()->json(['status' => false, 'message' => 'Data tidak ditemukan'], 404);
        return response()->json(['status' => true, 'data' => $pegawai], 200);
    }

    // 4. Update Data
    public function update(Request $request, $id)
    {
        $pegawai = Pegawai::find($id);
        if (!$pegawai) return response()->json(['message' => 'Data tidak ditemukan'], 404);

        DB::beginTransaction();
        try {
            $pegawai->update([
                'nip'     => $request->nip ?? $pegawai->nip,
                'nama'    => $request->nama ?? $pegawai->nama,
                'jabatan' => $request->jabatan ?? $pegawai->jabatan,
            ]);

            $user = User::find($pegawai->user_id);
            if ($user) {
                $user->update([
                    'name' => $request->nama ?? $user->name,
                    'role' => $request->role ?? $user->role,
                ]);
            }

            DB::commit();
            return response()->json(['status' => true, 'message' => 'Data berhasil diupdate']);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['status' => false, 'error' => $e->getMessage()], 500);
        }
    }

    /**
     * 5. HAPUS PEGAWAI (REVISI SESUAI REQUEST DOSEN)
     * Ditambahkan input 'alasan_hapus'
     */
    public function destroy(Request $request, $id)
    {
        $pegawai = Pegawai::find($id);
        if (!$pegawai) return response()->json(['message' => 'Data tidak ditemukan'], 404);

        // Validasi alasan hapus (Request Dosen)
        $request->validate([
            'alasan_hapus' => 'required|string'
        ]);

        // Simpan alasan ke database sebelum di-soft delete
        $pegawai->update([
            'alasan_hapus' => $request->alasan_hapus
        ]);

        $pegawai->delete(); 

        return response()->json([
            'status' => true, 
            'message' => 'Pegawai berhasil dipindahkan ke tempat sampah dengan alasan: ' . $request->alasan_hapus
        ]);
    }

    // 6. Melihat "Tong Sampah" (Sesuai request dosen: Dashboard tidak perlu detail, detail di sini)
    public function trash()
    {
        // Ambil data yang sudah di-soft delete beserta alasan hapusnya
        $pegawaiTerhapus = Pegawai::onlyTrashed()->get();
        return response()->json([
            'status' => true,
            'data'   => $pegawaiTerhapus
        ]);
    }

    // 7. Restore
    public function restore($id)
    {
        $pegawai = Pegawai::withTrashed()->find($id);

        if ($pegawai && $pegawai->trashed()) {
            // Kosongkan kembali alasan hapus saat di-restore
            $pegawai->update(['alasan_hapus' => null]);
            $pegawai->restore();
            
            return response()->json([
                'status'  => true,
                'message' => 'Data pegawai ' . $pegawai->nama . ' berhasil dikembalikan!'
            ]);
        }

        return response()->json(['status' => false, 'message' => 'Data tidak ditemukan di tong sampah'], 404);
    }
}