Your IP : 216.73.216.79


Current Path : /var/www/html/reddsis/app/Http/Controllers/Backend/
Upload File :
Current File : /var/www/html/reddsis/app/Http/Controllers/Backend/ContentDirectoryDepartmentController.php

<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use App\Http\Requests\Backend\ContentDirectoryDepartmentRequest;
use App\Models\Backend\ContentDirectoryDepartment;
use Illuminate\Http\Request;

class ContentDirectoryDepartmentController extends Controller
{
    public function index(Request $request)
    {
        $search = $request->get('search');
        $parentFilter = $request->get('parent');

        $parents = ContentDirectoryDepartment::whereNull('directory_department_parent_id')
            ->orderBy('directory_department_name')
            ->pluck('directory_department_name', 'directory_department_id');

        $filterActive = $parentFilter !== null && $parentFilter !== '';

        if ($filterActive) {
            $departments = ContentDirectoryDepartment::query()
                ->with('parent')
                ->when($search, function ($q) use ($search) {
                    $q->where(function ($sub) use ($search) {
                        $sub->where('directory_department_code', 'like', "%{$search}%")
                            ->orWhere('directory_department_name', 'like', "%{$search}%")
                            ->orWhere('directory_department_name_en', 'like', "%{$search}%");
                    });
                })
                ->when($parentFilter === 'root', fn($q) => $q->whereNull('directory_department_parent_id'))
                ->when($parentFilter !== 'root', fn($q) => $q->where('directory_department_parent_id', $parentFilter))
                ->orderBy('directory_department_sort')
                ->orderBy('directory_department_id')
                ->paginate(10)
                ->onEachSide(1)
                ->withQueryString();
        } else {
            $roots = ContentDirectoryDepartment::whereNull('directory_department_parent_id')
                ->with(['children' => function ($q) {
                    $q->with(['children' => function ($q) {
                        $q->orderBy('directory_department_sort')->orderBy('directory_department_id');
                    }])
                    ->orderBy('directory_department_sort')
                    ->orderBy('directory_department_id');
                }])
                ->when($search, function ($q) use ($search) {
                    $q->where(function ($sub) use ($search) {
                        $sub->where('directory_department_code', 'like', "%{$search}%")
                            ->orWhere('directory_department_name', 'like', "%{$search}%")
                            ->orWhere('directory_department_name_en', 'like', "%{$search}%");
                    });
                })
                ->orderBy('directory_department_sort')
                ->orderBy('directory_department_id')
                ->get();

            $departments = collect();
            $rootIndex = 0;
            foreach ($roots as $root) {
                $rootIndex++;
                $root->depth = 0;
                $root->parent_name = '—';
                $root->display_sort = $rootIndex;
                $departments->push($root);

                $childIndex = 0;
                foreach ($root->children as $child) {
                    $childIndex++;
                    $child->depth = 1;
                    $child->parent_name = $root->directory_department_name;
                    $child->display_sort = $childIndex;
                    $departments->push($child);

                    $grandchildIndex = 0;
                    foreach ($child->children as $grandchild) {
                        $grandchildIndex++;
                        $grandchild->depth = 2;
                        $grandchild->parent_name = $child->directory_department_name;
                        $grandchild->display_sort = $grandchildIndex;
                        $departments->push($grandchild);
                    }
                }
            }
        }

        return view('backend.module.contentDirectoryDepartment.index', [
            'departments' => $departments,
            'parents' => $parents,
            'search' => $search,
            'parentFilter' => $parentFilter,
            'filterActive' => $filterActive,
        ]);
    }

    public function create()
    {
        $parents = ContentDirectoryDepartment::whereNull('directory_department_parent_id')
            ->orderBy('directory_department_name')
            ->pluck('directory_department_name', 'directory_department_id');

        return view('backend.module.contentDirectoryDepartment.create', [
            'parents' => $parents,
        ]);
    }

    public function store(ContentDirectoryDepartmentRequest $request)
    {
        ContentDirectoryDepartment::create([
            'directory_department_code' => $request->directory_department_code,
            'directory_department_name' => $request->directory_department_name,
            'directory_department_name_en' => $request->directory_department_name_en,
            'directory_department_parent_id' => $request->directory_department_parent_id,
            'directory_department_sort' => $request->directory_department_sort,
            'created_by' => auth()->id(),
            'updated_by' => auth()->id(),
        ]);

        flash()->success('Department created successfully!');

        return redirect()->route('content-directory-department.index');
    }

    public function edit($id)
    {
        $department = ContentDirectoryDepartment::findOrFail($id);

        $parents = ContentDirectoryDepartment::whereNull('directory_department_parent_id')
            ->where('directory_department_id', '!=', $id)
            ->orderBy('directory_department_name')
            ->pluck('directory_department_name', 'directory_department_id');

        return view('backend.module.contentDirectoryDepartment.edit', [
            'department' => $department,
            'parents' => $parents,
        ]);
    }

    public function update(ContentDirectoryDepartmentRequest $request, $id)
    {
        $department = ContentDirectoryDepartment::findOrFail($id);

        $department->update([
            'directory_department_code' => $request->directory_department_code,
            'directory_department_name' => $request->directory_department_name,
            'directory_department_name_en' => $request->directory_department_name_en,
            'directory_department_parent_id' => $request->directory_department_parent_id,
            'directory_department_sort' => $request->directory_department_sort,
            'updated_by' => auth()->id(),
        ]);

        flash()->success('Department updated successfully!');

        return redirect()->route('content-directory-department.index');
    }

    public function destroy($id)
    {
        $department = ContentDirectoryDepartment::findOrFail($id);

        $childrenCount = ContentDirectoryDepartment::where('directory_department_parent_id', $id)->count();
        $staffCount = $department->staff()->count();

        if ($childrenCount > 0 || $staffCount > 0) {
            flash()->error('Cannot delete department because it has ' . $childrenCount . ' sub-department(s) and ' . $staffCount . ' staff(s) attached. Please reassign them first.');

            return redirect()->route('content-directory-department.index');
        }

        $department->delete();

        flash()->success('Department deleted successfully.');

        return redirect()->route('content-directory-department.index');
    }

    public function reorder(Request $request)
    {
        $ids = $request->input('ids', []);
        $parentId = $request->input('parent_id');
        $page = (int) $request->input('page', 1);
        $perPage = 10;
        $offset = ($page - 1) * $perPage;

        if (empty($ids)) {
            return response()->json(['success' => false], 422);
        }

        $sortIndex = 0;
        foreach ($ids as $id) {
            $sortValue = $offset + $sortIndex + 1;

            $query = ContentDirectoryDepartment::where('directory_department_id', $id);
            if ($parentId === 'root') {
                $query->whereNull('directory_department_parent_id');
            } elseif ($parentId) {
                $query->where('directory_department_parent_id', $parentId);
            }
            $query->update(['directory_department_sort' => $sortValue]);
            $sortIndex++;
        }

        return response()->json(['success' => true]);
    }
}