<?php

namespace App\Http\Controllers;

use App\Models\Tenants\Department;
use App\Models\Tenants\Tenant;
use App\Services\DepartmentPermissionService;
use Illuminate\Http\Request;

class DepartmentPermissionController extends Controller
{
    protected DepartmentPermissionService $departmentPermissionService;

    public function __construct(DepartmentPermissionService $departmentPermissionService)
    {
        $this->departmentPermissionService = $departmentPermissionService;
    }

    /**
     * 부서 권한 관리 메인 페이지
     */
    public function index(Request $request)
    {
        $tenantId = session('selected_tenant_id');

        // 부서 목록 조회
        $departmentsQuery = Department::query()->orderBy('tenant_id')->orderBy('sort_order')->orderBy('name');

        if ($tenantId && $tenantId !== 'all') {
            // 특정 테넌트 선택 시
            $departments = $departmentsQuery->where('tenant_id', $tenantId)->get();
            $departmentsByTenant = null;
        } else {
            // 전체 선택 시 테넌트별 그룹핑
            $departments = $departmentsQuery->get();
            $departmentsByTenant = $departments->groupBy('tenant_id');

            // 테넌트 정보 로드
            $tenantIds = $departmentsByTenant->keys()->filter()->toArray();
            $tenants = Tenant::whereIn('id', $tenantIds)->pluck('company_name', 'id');
        }

        return view('department-permissions.index', [
            'departments' => $departments,
            'departmentsByTenant' => $departmentsByTenant ?? null,
            'tenants' => $tenants ?? collect(),
            'selectedTenantId' => $tenantId,
        ]);
    }
}
