<?php

declare(strict_types=1);

namespace App\Http\Controllers\UserManagement;

use App\Http\Controllers\Helpers\ResponseHelper;
use App\Http\Controllers\Helpers\Permissions\UserPermissions;
use App\Enums\UserActions;
use App\Models\User;
use App\Models\Market\Organization;
use Hypervel\Http\Request;
use Hypervel\Support\Facades\Auth;
use Hypervel\Support\Str;

class UserAdditionalDetailsController
{
    public function getDetails(Request $request)
    {
        $user = Auth::user();
        if (!$user) {
            return ResponseHelper::returnUnauthorized();
        }

        return response()->json([
            'success' => true,
            'data' => [
                'settings' => $user->settings,
                'details' => $user->details,
            ]
        ]);
    }

    public function updateCooperatives(Request $request)
    {
        $user = Auth::user();
        if (!$user) {
            return ResponseHelper::returnUnauthorized();
        }

        $cooperativeHash = $request->input('cooperative_hash');
        $action = $request->input('action', 'add'); // 'add' or 'remove'

        if (!$cooperativeHash) {
            return ResponseHelper::returnIncorrectDetails();
        }

        $settings = $user->settings ?? [];
        $cooperatives = $settings['cooperatives'] ?? [];

        if ($action === 'add') {
            if (!in_array($cooperativeHash, $cooperatives)) {
                $cooperatives[] = $cooperativeHash;
            }
        } else {
            $cooperatives = array_values(array_filter($cooperatives, fn($h) => $h !== $cooperativeHash));
        }

        $settings['cooperatives'] = $cooperatives;
        $user->settings = $settings;

        if ($user->save()) {
            return response()->json([
                'success' => true,
                'message' => 'Cooperatives updated successfully',
                'data' => $cooperatives
            ]);
        }

        return ResponseHelper::returnError('Failed to update cooperatives');
    }

    public function getUserCooperatives(Request $request)
    {
        $userHash = $request->input('user_hash');
        
        if ($userHash) {
            $targetUser = User::where('hashkey', $userHash)->first();
            if (!$targetUser) {
                return ResponseHelper::returnError('User not found', 404);
            }
            
            // Authorization check
            if (!UserPermissions::isActionPermitted($targetUser->acct_type, UserActions::ViewUserInfo)) {
                return ResponseHelper::returnUnauthorized();
            }
            
            $user = $targetUser;
        } else {
            $user = Auth::user();
        }

        if (!$user) {
            return ResponseHelper::returnUnauthorized();
        }

        $cooperativeHashes = $user->settings['cooperatives'] ?? [];
        if (empty($cooperativeHashes)) {
            return response()->json(['success' => true, 'data' => []]);
        }

        $cooperatives = Organization::whereIn('hashkey', $cooperativeHashes)->get();

        return response()->json([
            'success' => true,
            'data' => $cooperatives
        ]);
    }

    public function searchUsersByCooperative(Request $request)
    {
        if (!UserPermissions::isActionPermitted(Auth::user()->acct_type, UserActions::ViewUserInfo)) {
            return ResponseHelper::returnUnauthorized();
        }

        $cooperativeHash = $request->input('cooperative_hash');
        if (!$cooperativeHash) {
            return ResponseHelper::returnIncorrectDetails();
        }

        // Search in the JSON field 'settings' for cooperatives array containing the hash
        $users = User::where('settings->cooperatives', 'like', '%' . $cooperativeHash . '%')->get();

        return response()->json([
            'success' => true,
            'data' => $users
        ]);
    }
}
