<?php

namespace App\Modules\HR\Core\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\HR\Core\Models\Department;
use App\Modules\PLATFORM\Settings\Models\Branch;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Yajra\DataTables\Facades\DataTables;

class DepartmentController extends Controller
{
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $query = Department::with(['branch', 'parent']);

            return DataTables::of($query)
                ->addIndexColumn()
                ->addColumn('branch', fn ($row) => $row->branch?->name ?? '-')
                ->addColumn('parent', fn ($row) => $row->parent?->name ?? '-')
                ->editColumn('status', function ($row) {
                    return $row->status
                        ? '<span class="badge bg-success">Active</span>'
                        : '<span class="badge bg-danger">Inactive</span>';
                })
                ->addColumn('action', function ($row) {
                    return view('core::departments/partials/actions', compact('row'))->render();
                })
                ->rawColumns(['status', 'action'])
                ->make(true);
        }

        return view('core::departments/index');
    }

    public function create()
    {
        return view('core::departments/create', [
            'branches'    => Branch::where('status', true)->orderBy('name')->get(),
            'departments' => Department::whereNull('parent_id')
                                ->where('status', true)
                                ->orderBy('name')
                                ->get(),
        ]);
    }

    public function store(Request $request)
    {
        $request->validate([
            'code'      => 'required|string|max:50',
            'name'      => 'required|string|max:150',
            'branch_id' => 'nullable|exists:branches,id',
            'parent_id' => 'nullable|exists:departments,id',
        ], [
            'code.required' => 'Department code is required.',
            'code.max' => 'Department code must not exceed 50 characters.',
            'name.required' => 'Department name is required.',
            'name.max' => 'Department name must not exceed 150 characters.',
            'branch_id.exists' => 'The selected branch is invalid.',
            'parent_id.exists' => 'The selected parent department is invalid.',
        ]);

        Department::create([
            'branch_id' => $request->branch_id,
            'code'      => $request->code,
            'name'      => $request->name,
            'parent_id' => $request->parent_id,
            'status'    => $request->boolean('status'),
        ]);

        return response()->json([
            'status'  => true,
            'message' => 'Department created successfully',
        ]);
    }

    public function edit(Department $department)
    {
        return view('core::departments/edit', [
            'department' => $department,
            'branches'   => Branch::where('status', true)->orderBy('name')->get(),
            'departments'=> Department::where('id', '!=', $department->id)
                                ->whereNull('parent_id')
                                ->where('status', true)
                                ->orderBy('name')
                                ->get(),
        ]);
    }

    public function update(Request $request, Department $department)
    {
        $request->validate([
            'code'      => 'required|string|max:50',
            'name'      => 'required|string|max:150',
            'branch_id' => 'nullable|exists:branches,id',
            'parent_id' => 'nullable|exists:departments,id',
        ], [
            'code.required' => 'Department code is required.',
            'code.max' => 'Department code must not exceed 50 characters.',
            'name.required' => 'Department name is required.',
            'name.max' => 'Department name must not exceed 150 characters.',
            'branch_id.exists' => 'The selected branch is invalid.',
            'parent_id.exists' => 'The selected parent department is invalid.',
        ]);

        $department->update([
            'branch_id' => $request->branch_id,
            'code'      => $request->code,
            'name'      => $request->name,
            'parent_id' => $request->parent_id,
            'status'    => $request->boolean('status'),
        ]);

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

    public function destroy(Department $department)
    {
        // Check if department is being used by employees
        $employeeCount = DB::table('employees')
            ->where('department_id', $department->id)
            ->count();

        if ($employeeCount > 0) {
            return response()->json([
                'status' => false,
                'message' => 'Cannot delete this department. It is currently being used by ' . $employeeCount . ' employee(s).',
            ], 422);
        }

        // Check if department has child departments
        $childCount = DB::table('departments')
            ->where('parent_id', $department->id)
            ->count();

        if ($childCount > 0) {
            return response()->json([
                'status' => false,
                'message' => 'Cannot delete this department. It has ' . $childCount . ' child department(s).',
            ], 422);
        }

        $department->delete();

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

    public function status(Department $department)
    {
        $department->update([
            'status' => ! $department->status,
        ]);

        return response()->json([
            'status'  => true,
            'message' => 'Status updated successfully',
        ]);
    }
}
