<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\StoreStaffRequest;
use App\Http\Requests\UpdateStaffRequest;
use App\Http\Resources\UserResource;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Mail;
use App\Mail\StaffCredentials;

class StaffController extends Controller
{
    public function index(Request $request): AnonymousResourceCollection
    {
        $query = User::with(['role', 'branch', 'company'])
            ->where('company_id', $request->user()->company_id);

        if ($request->has('search')) {
            $search = $request->input('search');
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhere('email', 'like', "%{$search}%")
                  ->orWhere('phone', 'like', "%{$search}%");
            });
        }

        if ($request->has('branch_id')) {
            $query->where('branch_id', $request->input('branch_id'));
        }

        if ($request->has('role_id')) {
            $query->where('role_id', $request->input('role_id'));
        }

        return UserResource::collection(
            $query->orderBy('name')->paginate($request->integer('per_page', 15))
        );
    }

    public function store(StoreStaffRequest $request): UserResource
    {
        $data = $request->validated();
        $data['company_id'] = $request->user()->company_id;

        $user = User::create($data);

        // Send credentials email
        Mail::to($user->email)->queue(new StaffCredentials(
            $user,
            $data['password'] ?? null,
            $data['pin'] ?? null
        ));

        return new UserResource($user->load(['role', 'branch']));
    }

    public function show(Request $request, User $staff): UserResource
    {
        if ($staff->company_id !== $request->user()->company_id) {
            abort(404);
        }

        return new UserResource($staff->load(['role', 'branch']));
    }

    public function update(UpdateStaffRequest $request, User $staff): UserResource
    {
        if ($staff->company_id !== $request->user()->company_id) {
            abort(404);
        }

        $data = $request->validated();

        if (empty($data['pin'])) {
            unset($data['pin']);
        }

        if (empty($data['password'])) {
            unset($data['password']);
        }

        $staff->update($data);

        return new UserResource($staff->load(['role', 'branch']));
    }

    public function destroy(Request $request, User $staff): Response
    {
        if ($staff->company_id !== $request->user()->company_id) {
            abort(404);
        }

        // Prevent self-deletion
        if ($staff->id === $request->user()->id) {
            return response()->noContent(403);
        }

        $staff->delete();

        return response()->noContent();
    }
}
