<?php

namespace App\Http\Controllers\Api\V1\Admin;

use App\Http\Controllers\Controller;
use App\Models\Portal;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class PortalController extends Controller
{
    /**
     * Display a listing of the portals.
     */
    public function index()
    {
        $portals = Portal::orderBy('order')->orderBy('name')->get();
        return response()->json([
            'data' => $portals
        ]);
    }

    /**
     * Store a newly created portal in storage.
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'key' => 'required|string|max:255|unique:portals,key',
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'url' => 'nullable|url|max:500',
            'icon' => 'nullable|string|max:100',
            'enabled' => 'boolean',
            'show_in_user_dashboard' => 'boolean',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'message' => 'Validation failed',
                'errors' => $validator->errors()
            ], 422);
        }

        $portal = Portal::create([
            'key' => $request->key,
            'name' => $request->name,
            'description' => $request->description,
            'url' => $request->url,
            'icon' => $request->icon,
            'enabled' => $request->enabled ?? true,
            'show_in_user_dashboard' => $request->show_in_user_dashboard ?? true,
        ]);

        return response()->json($portal, 201);
    }

    /**
     * Display the specified portal.
     */
    public function show(Portal $portal)
    {
        return response()->json($portal);
    }

    /**
     * Update the specified portal in storage.
     */
    public function update(Request $request, Portal $portal)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'url' => 'nullable|url|max:500',
            'icon' => 'nullable|string|max:100',
            'enabled' => 'boolean',
            'show_in_user_dashboard' => 'boolean',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'message' => 'Validation failed',
                'errors' => $validator->errors()
            ], 422);
        }

        // Log request data for debugging
        \Log::info('Portal update request', [
            'portal_id' => $portal->id,
            'request_data' => $request->all(),
            'show_in_user_dashboard_value' => $request->show_in_user_dashboard,
            'has_show_in_user_dashboard' => $request->has('show_in_user_dashboard'),
        ]);

        $updateData = [
            'name' => $request->name,
            'description' => $request->description,
            'url' => $request->url,
            'icon' => $request->icon,
        ];

        // Handle boolean fields properly - use has() to check existence
        if ($request->has('enabled')) {
            $updateData['enabled'] = $request->enabled;
        }

        if ($request->has('show_in_user_dashboard')) {
            $updateData['show_in_user_dashboard'] = $request->show_in_user_dashboard;
        }

        $portal->update($updateData);

        \Log::info('Portal updated', [
            'portal_id' => $portal->id,
            'enabled' => $portal->enabled,
            'show_in_user_dashboard' => $portal->show_in_user_dashboard,
        ]);

        return response()->json($portal);
    }

    /**
     * Remove the specified portal from storage.
     */
    public function destroy(Portal $portal)
    {
        // Check if portal has assigned users
        $userCount = $portal->users()->count();
        
        if ($userCount > 0) {
            return response()->json([
                'message' => "Cannot delete portal. It has {$userCount} assigned user(s)."
            ], 422);
        }

        $portal->delete();

        return response()->json([
            'message' => 'Portal deleted successfully'
        ]);
    }

    /**
     * Assign a user to the portal.
     */
    public function assignUser(Request $request, Portal $portal)
    {
        $validator = Validator::make($request->all(), [
            'user_id' => 'required|exists:users,id',
            'role_scope' => 'required|in:portal_admin,user',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'message' => 'Validation failed',
                'errors' => $validator->errors()
            ], 422);
        }

        $portal->users()->syncWithoutDetaching([
            $request->user_id => ['role_scope' => $request->role_scope]
        ]);

        return response()->json([
            'message' => 'User assigned to portal successfully'
        ]);
    }

    /**
     * Remove a user from the portal.
     */
    public function removeUser(Portal $portal, $userId)
    {
        $portal->users()->detach($userId);

        return response()->json([
            'message' => 'User removed from portal successfully'
        ]);
    }

    /**
     * Get all users assigned to the portal.
     */
    public function getPortalUsers(Portal $portal)
    {
        $users = $portal->users()
            ->withPivot('role_scope')
            ->get();

        return response()->json($users);
    }

    /**
     * Reorder portals.
     */
    public function reorder(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'portals' => 'required|array',
            'portals.*.id' => 'required|exists:portals,id',
            'portals.*.order' => 'required|integer',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'message' => 'Validation failed',
                'errors' => $validator->errors()
            ], 422);
        }

        try {
            foreach ($request->portals as $portalData) {
                Portal::where('id', $portalData['id'])
                    ->update(['order' => $portalData['order']]);
            }

            return response()->json([
                'message' => 'Portals reordered successfully'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'message' => 'Failed to reorder portals',
                'error' => $e->getMessage()
            ], 500);
        }
    }
}
