<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\Position;
use Spatie\Permission\Models\Role;

class PositionController extends Controller
{
    /**
     * Tampilkan semua daftar jabatan
     */
    public function index()
    {
        try {
            $positions = Position::orderBy('name', 'asc')->get();
            return response()->json(['success' => true, 'data' => $positions]);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    /**
     * Simpan Jabatan Baru
     */
    public function store(Request $request)
    {
        $request->validate([
            'code'              => 'required|string|max:20|unique:positions,code',
            'name'              => 'required|string|max:100',
            'expense_group'     => 'required|in:opex,hpp',
            'has_system_access' => 'required|boolean',
            'system_role'       => 'nullable|string|max:50'
        ]);

        DB::beginTransaction();
        try {
            Position::create([
                'code'              => $request->code,
                'name'              => $request->name,
                'expense_group'     => $request->expense_group,
                'has_system_access' => $request->has_system_access,
                'system_role'       => $request->has_system_access ? $request->system_role : null,
                'is_active'         => true,
            ]);

            DB::commit();
            return response()->json(['success' => true, 'message' => 'Master Jabatan berhasil ditambahkan.']);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    /**
     * Update Jabatan
     */
    public function update(Request $request, $id)
    {
        $request->validate([
            'code'              => 'required|string|max:20|unique:positions,code,' . $id,
            'name'              => 'required|string|max:100',
            'expense_group'     => 'required|in:opex,hpp',
            'has_system_access' => 'required|boolean',
            'system_role'       => 'nullable|string|max:50',
            'is_active'         => 'required|boolean'
        ]);

        DB::beginTransaction();
        try {
            $position = Position::findOrFail($id);
            $position->update([
                'code'              => $request->code,
                'name'              => $request->name,
                'expense_group'     => $request->expense_group,
                'has_system_access' => $request->has_system_access,
                'system_role'       => $request->has_system_access ? $request->system_role : null,
                'is_active'         => $request->is_active,
            ]);

            DB::commit();
            return response()->json(['success' => true, 'message' => 'Master Jabatan berhasil diperbarui.']);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    /**
     * Hapus Jabatan
     */
    public function destroy($id)
    {
        try {
            $position = Position::findOrFail($id);
            // Proteksi: Jangan hapus jika sudah dipakai di tabel employees
            if ($position->employees()->count() > 0) {
                return response()->json(['success' => false, 'message' => 'Gagal: Jabatan ini sedang digunakan oleh karyawan dan tidak dapat dihapus.'], 400);
            }
            $position->delete();
            return response()->json(['success' => true, 'message' => 'Master Jabatan berhasil dihapus.']);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    public function getSystemRoles()
    {
        try {
            // Mengambil semua role yang ada di database Spatie
            $roles = Role::orderBy('name', 'asc')->get(['id', 'name']);
            return response()->json(['success' => true, 'data' => $roles]);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }
}