<?php

namespace App\Http\Controllers;

use App\Models\UserAccount;
use App\Models\UserBranch;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Hash;

class UserAccountController extends Controller
{
    public function findByPin(Request $request)
    {
        try {
            // Validate the incoming request
            $validatedData = $request->validate([
                'mobile_pin' => 'required|string'
            ]);

            $pin = $validatedData['mobile_pin'];

            // Get all users (consider limiting this in production)
            $users = UserAccount::all();

            // Flag to track if we found a user but PIN didn't match
            $userFound = false;

            // Find the user with the matching pin
            foreach ($users as $user)
            {
                // Check if the user has a mobile_pin before attempting to verify
                if ($user->mobile_pin !== null && $user->mobile_pin !== '')
                {
                    $userFound = true;
                    try
                    {
                        if (Hash::check($pin, $user->mobile_pin))
                        {
                            $userBranches = UserBranch::join('tbl_branch', 'user_branch.branch_id', '=', 'tbl_branch.branch_id')
                            ->where('user_branch.user_id', $user->employee_ID)
                            ->select('user_branch.*', 'tbl_branch.branch_name', 'tbl_branch.branch_address', 'tbl_branch.branch_tele01')
                            ->get();
                        // Create response with user and branch data
                        $response = [
                            'user' => $user,
                            'branches' => $userBranches
                        ];
                            return response()->json($response);
                        }
                    } catch (\Exception $e) {
                        // Log the hash check error
                        Log::error('Hash check error', [
                            'exception' => $e,
                            'user_id' => $user->id
                        ]);
                        // Continue checking other users
                    }
                }
            }

            // No matching pin found - clearer error message
            return response()->json([
                'message' => 'Invalid PIN provided. No matching user found.',
                'status' => 'error'
            ], 404);

        } catch (\Exception $e) {
            // Log the overall error
            Log::error('Error in findByPin method', [
                'exception' => $e,
                'request' => $request->except(['mobile_pin'])
            ]);

            return response()->json([
                'message' => 'An error occurred while processing your request.',
                'status' => 'error'
            ], 500);
        }
    }

    public function update(Request $request, $id)
    {
        $userAccount = UserAccount::find($id);

        if (!$userAccount) {
            return response()->json(['message' => 'User account not found'], 404);
        }

        $validatedData = $request->validate([
            'mobile_pin' => 'sometimes|required|string|min:5'
        ]);

        // Only hash password if it's being updated
        if (isset($validatedData['mobile_pin'])) {
            $validatedData['mobile_pin'] = Hash::make($validatedData['mobile_pin']);
        }

        try
        {
            $userAccount->update($validatedData);
            return response()->json(['message' => 'User account updated successfully']);
        } catch (\Exception $e)
        {
            Log::error("Error updating user account:", ['message' => $e->getMessage()]);
            return response()->json(['message' => 'Failed to update user account', 'error' => $e->getMessage()], 500);
        }
    }

}
