<?php

namespace App\Http\Controllers;

use App\Models\Karyawan;
use App\Models\Jabatan;
use App\Models\Departemen;
use App\Models\AtrKaryawan;
use App\Http\Requests\StoreKaryawanRequest;
use App\Http\Requests\UpdateKaryawanRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Log;
use Carbon\Carbon;
use Intervention\Image\ImageManager;
use Intervention\Image\Drivers\Gd\Driver;
use Intervention\Image\Encoders\JpegEncoder;

class KaryawanController extends Controller
{
    private function uploadFoto($file, $folder = 'karyawans')
    {
        $manager = new ImageManager(Driver::class);

        $image = $manager->decode($file);

        $image = $image->scale(width: 600);

        do {
            $filename = $folder . '/' .
                now()->format('YmdHis') . '_' .
                Str::random(10) . '.jpg';
        } while (Storage::disk('public')->exists($filename));

        $encoded = $image->encode(
            new JpegEncoder(quality: 75)
        );

        Storage::disk('public')->put(
            $filename,
            (string) $encoded
        );

        return $filename;
    }

    public function getData(Request $request)
    {
        $perPage = (int) $request->get('perPage', 10);
        $search = $request->get('search');

        $query = Karyawan::query()->with(['atr', 'jabatan', 'departemen']);

        if ($search) {
            $query->where(function ($q) use ($search) {
                $q->where('nama', 'like', "%{$search}%")
                    ->orWhere('nrp', 'like', "%{$search}%")
                    ->orWhereHas('jabatan', function ($jabatan) use ($search) {
                        $jabatan->where('jabatan', 'like', "%{$search}%");
                    })
                    ->orWhereHas('departemen', function ($departemen) use ($search) {
                        $departemen->where('departemen', 'like', "%{$search}%");
                    });
            });
        }

        $data = $query
            ->oldest()
            ->paginate($perPage);

        return response()->json($data);
    }

    public function index()
    {

        return view('menu.karyawan.index');
    }
 
    public function create()
    {
        $atasans = Karyawan::select('id', 'nama')->get();
        $jabatans = Jabatan::get();
        $departemens = Departemen::get();

        return view('menu.karyawan.create', compact('atasans', 'jabatans', 'departemens'));
    }
 
    public function store(StoreKaryawanRequest $request)
    {
        $validated = $request->validated();

        $validated['foto'] = 'karyawans/default-150x150.png';

        if ($request->hasFile('foto')) {
            $validated['foto'] = $this->uploadFoto(
                $request->file('foto'),
                'karyawans'
            );
        }

        do {
            $slug = Str::slug($request->nama) . '-' . rand(1000, 9999);
        } while (Karyawan::where('slug', $slug)->exists());

        $validated['slug'] = $slug;
        $validated['atasan_id'] = $validated['atasan_id'] ?? null;

        Karyawan::create($validated);

        return redirect('/karyawan')
            ->with('success', 'Data Karyawan berhasil ditambahkan.');
    }

    public function storeAtr(Request $request, $id)
    {
        try {
            $request->validate([
                'atr' => 'required|numeric|min:0|max:100',
            ]);

            $newAtr = new AtrKaryawan();
            $newAtr->karyawan_id = $id;
            $newAtr->nilai_atr   = $request->input('atr');
            $newAtr->tanggal     = Carbon::now()->format('Y-m-d');
            $newAtr->save();

            return response()->json([
                'success' => true,
                'message' => 'Data ATR berhasil disimpan!',
                'data'    => $newAtr
            ], 200);
        } catch (\Exception $e) {
            Log::error('Gagal Simpan ATR: ' . $e->getMessage());

            return response()->json([
                'success' => false,
                'message' => 'Gagal menyimpan: ' . $e->getMessage()
            ], 500);
        }
    }
 
    public function show(Karyawan $karyawan)
    {
        return view('menu.karyawan.show', compact('karyawan'));
    }
 
    public function edit(Karyawan $karyawan)
    {
        $atasans = Karyawan::where('id', '!=', $karyawan->id)->get();
        $jabatans = Jabatan::get();
        $departemens = Departemen::get();

        return view('menu.karyawan.edit', compact('karyawan', 'atasans', 'jabatans', 'departemens'));
    }
 
    public function update(UpdateKaryawanRequest $request, Karyawan $karyawan)
    {
        $validated = $request->validated();

        if ($request->hasFile('foto')) {
            $validated['foto'] = $this->uploadFoto(
                $request->file('foto'),
                'karyawans'
            );
        }

        $karyawan->update($validated);

        return redirect('/karyawan')
            ->with('success', 'Data Karyawan berhasil diperbarui.');
    }
 
    public function destroy(Karyawan $karyawan)
    {
        if ($karyawan->bawahan()->count() > 0) {
            return back()->with('error', 'Tidak bisa hapus, masih punya bawahan.');
        }

        if ($karyawan->laporanGL()->exists() || $karyawan->laporanManpower()->exists()) {
            return back()->with('error', 'Tidak bisa hapus, sudah digunakan di laporan.');
        }

        if (
            $karyawan->foto &&
            $karyawan->foto !== 'karyawans/default-150x150.png'
        ) {
            Storage::disk('public')->delete($karyawan->foto);
        }

        $karyawan->delete();

        return redirect('/karyawan')->with('success', 'Data berhasil dihapus.');
    }

    public function editProfile()
    {
        $karyawan = Auth::user()->karyawan;
        $jabatans = Jabatan::get();
        $departemens = Departemen::get();

        $atasans = Karyawan::where('id', '!=', $karyawan->id)->get();

        return view('menu.setting.profile', compact('karyawan', 'atasans', 'jabatans', 'departemens'));
    }

    public function updateProfile(UpdateKaryawanRequest $request)
    {
        $karyawan = Auth::user()->karyawan;

        $validated = $request->validated();

        if ($request->hasFile('foto')) {
            $validated['foto'] = $this->uploadFoto(
                $request->file('foto'),
                'karyawans'
            );
        }

        $karyawan->update($validated);

        return redirect('/')
            ->with('success', 'Profile berhasil diperbarui.');
    }
}
