<?php

namespace App\Http\Controllers;

use App\Enums\Status;
use App\Models\Department;
use Illuminate\Http\Request;
use Yajra\DataTables\Facades\DataTables;

class DepartmentsController extends Controller
{
    /**
     * Display the departments listing page.
     */
    public function index()
    {
        return view('departments.index');
    }

    /**
     * Get departments data for DataTable.
     */
    public function datatable(Request $request)
    {
        $query = Department::with('parentDepartment:id,name');

        return DataTables::of($query)
            ->addColumn('parent_name', function ($department) {
                return $department->parentDepartment?->name;
            })
            ->addColumn('status', function ($department) {
                return $department->status->value;
            })
            ->make(true);
    }

    /**
     * Store a new department.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'code' => 'required|string|max:50|unique:departments,code',
            'parent_id' => 'nullable|exists:departments,id',
            'notes' => 'nullable|string',
        ]);

        $department = Department::create([
            'name' => $validated['name'],
            'code' => $validated['code'],
            'parent_id' => $validated['parent_id'] ?? null,
            'notes' => $validated['notes'] ?? null,
            'status' => Status::ACTIVE,
        ]);

        return response()->json([
            'success' => true,
            'message' => __('Department created successfully.'),
            'data' => $department,
        ]);
    }

    /**
     * Get a single department.
     */
    public function show(Department $department)
    {
        return response()->json([
            'success' => true,
            'data' => $department,
        ]);
    }

    /**
     * Update a department.
     */
    public function update(Request $request, Department $department)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'code' => 'required|string|max:50|unique:departments,code,'.$department->id,
            'parent_id' => 'nullable|exists:departments,id',
            'notes' => 'nullable|string',
        ]);

        // Prevent setting self as parent
        if ($validated['parent_id'] == $department->id) {
            return response()->json([
                'success' => false,
                'message' => __('A department cannot be its own parent.'),
            ], 422);
        }

        $department->update([
            'name' => $validated['name'],
            'code' => $validated['code'],
            'parent_id' => $validated['parent_id'] ?? null,
            'notes' => $validated['notes'] ?? null,
        ]);

        return response()->json([
            'success' => true,
            'message' => __('Department updated successfully.'),
            'data' => $department,
        ]);
    }

    /**
     * Delete a department.
     */
    public function destroy(Department $department)
    {
        $department->delete();

        return response()->json([
            'success' => true,
            'message' => __('Department deleted successfully.'),
        ]);
    }

    /**
     * Toggle department status.
     */
    public function toggleStatus(Department $department)
    {
        $department->status = $department->status === Status::ACTIVE ? Status::INACTIVE : Status::ACTIVE;
        $department->save();

        return response()->json([
            'success' => true,
            'message' => __('Department status updated successfully.'),
        ]);
    }

    /**
     * Get parent departments for dropdown.
     */
    public function parentDepartments()
    {
        $departments = Department::where('status', Status::ACTIVE)
            ->get(['id', 'name', 'code']);

        return response()->json([
            'success' => true,
            'data' => $departments,
        ]);
    }
}
