<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;

class UserController extends Controller
{
    public function index(Request $request)
    {
        $user = $request->user();
        $query = User::with(['company', 'roles']);

        if (!$user->isSuperAdmin()) {
            $query->where('company_id', $user->company_id);
        } elseif ($request->has('company_id')) {
            $query->where('company_id', $request->company_id);
        }

        return response()->json(['data' => $query->latest()->get()]);
    }

    public function store(Request $request)
    {
        $user = $request->user();
        $isSuperAdmin = $user->isSuperAdmin();

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email',
            'password' => 'required|string|min:6',
            'status' => 'nullable|in:active,inactive',
            'company_id' => $isSuperAdmin ? 'nullable|exists:companies,id' : 'prohibited',
            'roles' => 'nullable|array',
            'roles.*' => 'string|exists:roles,name',
        ]);

        // Super Admin no longer needs to be assigned to a holding company
        $companyId = $isSuperAdmin ? ($validated['company_id'] ?? null) : $user->company_id;

        $newUser = User::create([
            'name' => $validated['name'],
            'email' => $validated['email'],
            'password' => Hash::make($validated['password']),
            'company_id' => $companyId,
            'status' => $validated['status'] ?? 'active',
        ]);

        if (!empty($validated['roles'])) {
            $newUser->syncRoles($validated['roles']);
        } else {
            $newUser->assignRole('Company User');
        }

        return response()->json(['data' => $newUser->load(['company', 'roles']), 'message' => 'User created'], 201);
    }

    public function show(Request $request, $id)
    {
        $user = $request->user();
        $target = User::with(['company', 'roles'])->findOrFail($id);

        if (!$user->isSuperAdmin() && $user->company_id !== $target->company_id) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }

        return response()->json(['data' => $target]);
    }

    public function update(Request $request, $id)
    {
        $user = $request->user();
        $target = User::findOrFail($id);

        if (!$user->isSuperAdmin() && $user->company_id !== $target->company_id) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }

        $isSuperAdmin = $user->isSuperAdmin();

        $validated = $request->validate([
            'name' => 'sometimes|string|max:255',
            'email' => ['sometimes', 'email', Rule::unique('users')->ignore($target->id)],
            'password' => 'nullable|string|min:6',
            'status' => 'sometimes|in:active,inactive',
            'company_id' => $isSuperAdmin ? 'sometimes|exists:companies,id' : 'prohibited',
            'roles' => 'nullable|array',
            'roles.*' => 'string|exists:roles,name',
        ]);

        if (isset($validated['name'])) $target->name = $validated['name'];
        if (isset($validated['email'])) $target->email = $validated['email'];
        if (!empty($validated['password'])) $target->password = Hash::make($validated['password']);
        if (isset($validated['status'])) $target->status = $validated['status'];
        
        // Super Admin no longer needs to be assigned to a holding company
        if ($isSuperAdmin && isset($validated['company_id'])) {
            $target->company_id = $validated['company_id'];
        }

        $target->save();

        if (!empty($validated['roles'])) {
            $target->syncRoles($validated['roles']);
        }

        return response()->json(['data' => $target->load(['company', 'roles']), 'message' => 'User updated']);
    }

    public function destroy(Request $request, $id)
    {
        $user = $request->user();
        $target = User::findOrFail($id);

        if (!$user->isSuperAdmin() && $user->company_id !== $target->company_id) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }

        if ($target->id === $user->id) {
            return response()->json(['message' => 'Cannot delete yourself'], 403);
        }

        $target->delete();
        return response()->json(['message' => 'User deleted']);
    }
}
