<?php

declare(strict_types=1);

namespace App\Http\Controllers\Market;

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

class UserInfoController
{
    public function getUserInfo(Request $request, string $hashkey)
    {
        $targetUser = User::where('hashkey', $hashkey)->first();
        if (!$targetUser) {
            return ResponseHelper::returnError('User not found', 404);
        }

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

        // Check permission: can view self or has ViewUserInfo permission for others
        if ($currentUser->id !== $targetUser->id && !UserPermissions::isActionPermitted($currentUser->acct_type, UserActions::ViewUserInfo)) {
            return ResponseHelper::returnUnauthorized();
        }

        $userInfo = $targetUser->userInfo;
        if (!$userInfo) {
            // Lazy create if it doesn't exist (should have been backfilled but just in case)
             $userInfo = UserInfo::create([
                'user_id' => $targetUser->id,
                'fullname' => $targetUser->fullname ?? $targetUser->name,
                'email' => $targetUser->email,
                'mobile' => $targetUser->mobile_number,
                'is_active' => true,
            ]);
        }

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

    public function updateUserInfo(Request $request, string $hashkey)
    {
        $targetUser = User::where('hashkey', $hashkey)->first();
        if (!$targetUser) {
            return ResponseHelper::returnError('User not found', 404);
        }

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

        // Check permission: can manage self or has ManageUserInfo permission for others
        if ($currentUser->id !== $targetUser->id && !UserPermissions::isActionPermitted($currentUser->acct_type, UserActions::ManageUserInfo)) {
            return ResponseHelper::returnUnauthorized();
        }

        $userInfo = $targetUser->userInfo;
        if (!$userInfo) {
            $userInfo = new UserInfo(['user_id' => $targetUser->id]);
        }

        $validated = $request->validate([
            'firstname' => 'nullable|string|max:255',
            'middlename' => 'nullable|string|max:255',
            'lastname' => 'nullable|string|max:255',
            'suffix' => 'nullable|string|max:50',
            'gender' => 'nullable|string|max:50',
            'dob' => 'nullable|date',
            'priority_sector' => 'nullable|string|max:255',
            'messenger_id' => 'nullable|string|max:255',
            'viber_number' => 'nullable|string|max:255',
            'tiktok_username' => 'nullable|string|max:255',
            'region' => 'nullable|string|max:255',
            'province' => 'nullable|string|max:255',
            'city' => 'nullable|string|max:255',
            'barangay' => 'nullable|string|max:255',
            'civil_status' => 'nullable|string|max:100',
            'children_count' => 'nullable|integer',
            'dependent_count' => 'nullable|integer',
            'education_level' => 'nullable|string|max:255',
            'course' => 'nullable|string|max:255',
            'school' => 'nullable|string|max:255',
            'year_last_attended' => 'nullable|string|max:50',
            'livelihood_source' => 'nullable|string|max:255',
            'last_company' => 'nullable|string|max:255',
            'employer_name' => 'nullable|string|max:255',
            'last_position' => 'nullable|string|max:255',
            'occupation' => 'nullable|string|max:255',
            'last_employment_year' => 'nullable|string|max:50',
            'monthly_income' => 'nullable|numeric',
            'tin' => 'nullable|string|max:100',
            'philhealth_id' => 'nullable|string|max:100',
            'gov_id' => 'nullable|string|max:100',
            'id_type' => 'nullable|string|max:100',
            'id_number' => 'nullable|string|max:100',
            'beneficiary_type' => 'nullable|string|max:100',
            'emergency_contact_name' => 'nullable|string|max:255',
            'emergency_contact_address' => 'nullable|string|max:255',
            'emergency_contact_phone' => 'nullable|string|max:50',
            'emergency_contact_relation' => 'nullable|string|max:100',
            'emergency_contact_user_id' => 'nullable|integer',
            'fullname' => 'nullable|string|max:255',
            'landline' => 'nullable|string|max:20',
            'mobile' => 'nullable|string|max:20',
            'email' => 'nullable|email|max:255',
            'alt_email' => 'nullable|email|max:255',
            'alt_landline' => 'nullable|string|max:20',
            'alt_mobile' => 'nullable|string|max:20',
            'facebook_url' => 'nullable|url|max:255',
            'bank_details' => 'nullable|array',
            'bank_account_no' => 'nullable|string|max:100',
            'addresses' => 'nullable|array',
            'other_details' => 'nullable|array',
        ]);

        // Logic to automatically populate emergency_contact_user_id if phone matches a registered user
        if (!empty($validated['emergency_contact_phone'])) {
            $matchedUser = User::where('mobile_number', $validated['emergency_contact_phone'])->first();
            if ($matchedUser) {
                $validated['emergency_contact_user_id'] = $matchedUser->id;
            }
        }

        $userInfo->fill($validated);
        
        if ($userInfo->save()) {
             // Also update core user fields if they match
             if (isset($validated['fullname'])) $targetUser->fullname = $validated['fullname'];
             if (isset($validated['email'])) $targetUser->email = $validated['email'];
             if (isset($validated['mobile'])) $targetUser->mobile_number = $validated['mobile'];
             $targetUser->save();

            return ResponseHelper::returnSuccessResponse($userInfo, $userInfo->hashkey, 'User info updated');
        }

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

    public function searchEmergencyContact(Request $request)
    {
        $query = $request->input('q');
        if (empty($query)) {
            return response()->json(['success' => true, 'data' => []]);
        }

        $users = User::where('name', 'like', "%$query%")
            ->orWhere('fullname', 'like', "%$query%")
            ->orWhere('mobile_number', 'like', "%$query%")
            ->limit(10)
            ->get(['id', 'name', 'fullname', 'mobile_number', 'hashkey']);

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