<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\IncomeHistory;
use App\Models\User;

class IncomeHistoryController extends Controller
{
    public function index(Request $request)
    {
        $ref = trim((string) $request->get('referral_code', ''));

        $historiesQuery = IncomeHistory::query();
        $searchedUser = null;
        $isRelatedMemberSearch = false;
        $searchNotFound = false;

        if ($ref !== '') {
            $searchedUser = User::query()
                ->whereRaw('LOWER(referral_code) = ?', [strtolower($ref)])
                ->first();

            if ($searchedUser) {
                $isRelatedMemberSearch = true;
                $escapedReferralCode = $this->escapeLike(trim((string) $searchedUser->referral_code));

                $historiesQuery->where(function ($query) use ($searchedUser, $escapedReferralCode) {
                    $query->where('user_id', $searchedUser->id)
                        ->orWhere(function ($descriptionQuery) use ($escapedReferralCode) {
                            $descriptionQuery->whereNotNull('description')
                                ->where('description', 'like', '%(' . $escapedReferralCode . ')%');
                        });
                });
            } else {
                $historiesQuery->whereRaw('1=0');
                $searchNotFound = true;
            }
        } else {
            $historiesQuery->where('user_id', auth()->id());
        }

        $histories = $historiesQuery
            ->latest()
            ->paginate(10)
            ->withQueryString();

        return view('user.income-history', compact(
            'histories',
            'ref',
            'searchedUser',
            'isRelatedMemberSearch',
            'searchNotFound'
        ));
    }

    private function escapeLike(string $value): string
    {
        return str_replace(['\\', '%', '_'], ['\\\\', '\%', '\_'], $value);
    }
}
