<?php

namespace App\Http\Controllers\Admin\Machine;

use App\Http\Controllers\Admin\AdminController;
use App\Models\System\Company;
use App\Models\Machine\Machine;
use App\Models\System\User;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;

class MachinePermissionController extends AdminController
{
    /**
     * 顯示機台權限管理列表
     */
    public function index(Request $request): View
    {
        $per_page = $request->input('per_page', 10);
        $search = $request->input('search');
        $company_id = $request->input('company_id');

        $currentUser = auth()->user();

        // 僅列出租戶中具有「is_admin」標記的角色帳號以供分配
        $userQuery = User::query()
            ->with(['machines' => function($query) {
                $query->withoutGlobalScope('machine_access')
                      ->select('machines.id', 'machines.name', 'machines.serial_no');
            }])
            ->whereNotNull('company_id');

        // 非系統管理員僅能看到同公司的帳號 (因 User Model 排除 TenantScoped 全域過濾，需手動注入)
        if (!$currentUser->isSystemAdmin()) {
            $userQuery->where('company_id', $currentUser->company_id);
        } elseif ($company_id) {
            // 系統管理員的篩選邏輯
            $userQuery->where('company_id', $company_id);
        }

        if ($search) {
            $userQuery->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhere('username', 'like', "%{$search}%")
                  ->orWhere('email', 'like', "%{$search}%");
            });
        }

        $users_list = $userQuery->latest()->paginate($per_page)->withQueryString();
        $companies = $currentUser->isSystemAdmin() ? Company::all() : collect();

        return view('admin.machines.permissions', compact('users_list', 'companies'));
    }

    /**
     * AJAX: 取得特定帳號的機台分配狀態
     */
    public function getAccountMachines(User $user): JsonResponse
    {
        $currentUser = auth()->user();

        // 安全檢查：只能操作自己公司的帳號（除非是系統管理員）
        if (!$currentUser->isSystemAdmin() && $user->company_id !== $currentUser->company_id) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }

        // 取得該使用者所屬公司之所有機台 (忽略個別帳號的 machine_access 限制，以公司為單位顯示)
        $machines = Machine::withoutGlobalScope('machine_access')
            ->where('company_id', $user->company_id)
            ->get(['id', 'name', 'serial_no']);
            
        $assignedIds = $user->machines()->pluck('machines.id')->toArray();

        return response()->json([
            'user' => $user,
            'machines' => $machines,
            'assigned_ids' => $assignedIds
        ]);
    }

    /**
     * AJAX: 儲存特定帳號的機台分配
     */
    public function syncAccountMachines(Request $request, User $user): JsonResponse
    {
        $currentUser = auth()->user();

        // 安全檢查
        if (!$currentUser->isSystemAdmin() && $user->company_id !== $currentUser->company_id) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }

        $request->validate([
            'machine_ids' => 'nullable|array',
            'machine_ids.*' => 'exists:machines,id'
        ]);

        // 加固驗證：確保所有機台 ID 都屬於該使用者的公司 (使用 withoutGlobalScope 避免管理員自身權限影響驗證邏輯)
        if ($request->has('machine_ids')) {
            $machineIds = array_unique($request->machine_ids);
            $validCount = Machine::withoutGlobalScope('machine_access')
                ->where('company_id', $user->company_id)
                ->whereIn('id', $machineIds)
                ->count();
            
            if ($validCount !== count($machineIds)) {
                return response()->json(['error' => 'Invalid machine IDs provided.'], 422);
            }
        }

        $user->machines()->sync($request->machine_ids ?? []);

        return response()->json([
            'success' => true, 
            'message' => __('Permissions updated successfully'),
            'assigned_machines' => $user->machines()->select('machines.id', 'machines.name', 'machines.serial_no')->get()
        ]);
    }
}
