<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Services\UserService;
use App\Http\Requests\StaffStoreRequest;
use App\Http\Requests\StaffUpdateRequest;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class StaffController extends Controller
{
    protected $service;

    public function __construct(UserService $service)
    {
        $this->service = $service;
    }

    public function index(Request $request)
    {
        $organization = $request->attributes->get('current_organization');
        $this->authorize('manageStaff', [User::class, $organization]);

        return view('pages.staff', [
            'page_title' => 'Quản Lý Nhân Viên',
        ]);
    }

    public function data(Request $request): JsonResponse
    {
        $organization = $request->attributes->get('current_organization');
        $this->authorize('manageStaff', [User::class, $organization]);

        $filters = [
            'keyword' => $request->get('keyword'),
        ];
        $perPage = (int)$request->get('per_page', 10);

        $pageData = $this->service->getListForTable($this->getOrgHex(), $filters, $perPage);
        $actor = $request->user();

        $rows = $pageData->getCollection()->map(function ($user) use ($actor) {
            return [
                'id' => $user->hex_id,
                'name' => $user->name,
                'display_name' => $user->display_name,
                'email' => $user->email,
                'role' => $user->role ? $user->role->name : 'staff',
                'created_at' => optional($user->created_at)->toIso8601String(),
                'can_update' => $actor ? $actor->can('updateStaff', $user) : false,
                'can_delete' => $actor ? $actor->can('deleteStaff', $user) : false,
            ];
        })->values();

        return response()->json([
            'data' => $rows,
            'pagination' => [
                'current_page' => $pageData->currentPage(),
                'per_page' => $pageData->perPage(),
                'total' => $pageData->total(),
                'last_page' => $pageData->lastPage(),
            ],
        ]);
    }

    public function store(StaffStoreRequest $request): JsonResponse
    {
        $staff = $this->service->createStaff($request->validated(), $this->getOrgHex());

        return response()->json([
            'success' => true,
            'message' => 'Thêm nhân viên thành công',
            'data' => [
                'id' => $staff->hex_id,
                'name' => $staff->name,
            ],
        ]);
    }

    public function update(StaffUpdateRequest $request, string $id): JsonResponse
    {
        $target = $this->service->getStaffById($id, $this->getOrgHex());

        if (!$target) {
            return response()->json([
                'success' => false,
                'message' => 'Không tìm thấy nhân viên trong organization hiện tại',
            ], 404);
        }

        $this->authorize('updateStaff', $target);

        $payload = $request->validated();

        $updated = $this->service->updateStaff($id, $payload, $this->getOrgHex(), $request->user());

        if (!$updated) {
            return response()->json([
                'success' => false,
                'message' => 'Không thể cập nhật nhân viên',
            ], 500);
        }

        return response()->json([
            'success' => true,
            'message' => 'Cập nhật nhân viên thành công',
        ]);
    }

    public function destroy(Request $request, string $id): JsonResponse
    {
        $organization = $request->attributes->get('current_organization');
        $this->authorize('manageStaff', [User::class, $organization]);

        $target = $this->service->getStaffById($id, $this->getOrgHex());

        if (!$target) {
            return response()->json([
                'success' => false,
                'message' => 'Không tìm thấy nhân viên trong organization hiện tại',
            ], 404);
        }

        $this->authorize('deleteStaff', $target);

        $this->service->deleteStaff($id, $this->getOrgHex());

        return response()->json([
            'success' => true,
            'message' => 'Xóa nhân viên thành công',
        ]);
    }
}
