<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\BalanceLog;
use App\Models\BalanceTransaction;
use App\Models\IncomeHistory;
use App\Models\User;
// use App\Models\BalanceTransaction; // যদি মডেল ব্যবহার করতে চান
use App\Services\VoucherTransactionService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class BalanceController extends Controller
{
    public function showUpdateForm()
    {
        $recentTransactions = collect();

        if (Schema::hasTable('balance_transactions')) {
            $recentTransactions = BalanceTransaction::query()
                ->leftJoin('users', 'balance_transactions.user_id', '=', 'users.id')
                ->leftJoin('admins', 'balance_transactions.admin_id', '=', 'admins.id')
                ->select([
                    'balance_transactions.*',
                    'users.name as user_name',
                    'users.referral_code as user_referral_code',
                    'admins.name as admin_name',
                ])
                ->orderByDesc('balance_transactions.created_at')
                ->limit(20)
                ->get();
        }

        return view('admin.balance_update', compact('recentTransactions'));
    }
    
    
    
    // app/Http/Controllers/Admin/BalanceController.php

public function fetchUser(Request $request)
{
    $id = trim($request->get('id'));
    if (!$id) return response()->json(['found' => false]);

    $user = $this->applyHiddenUserScope(\App\Models\User::query())
        ->where(function ($query) use ($id) {
            $query->where('email', $id)
                ->orWhere('mobile', $id)
                ->orWhere('referral_code', $id)
                ->orWhere('id', $id);
        })
        ->select('id','name','profile_photo','referral_code','balance','voucher_balance')
        ->first();

    if (!$user) {
        return response()->json(['found' => false]);
    }

    // --- Robust profile photo URL resolver ---
    $photoDb = (string)($user->profile_photo ?? '');

    $photoUrl = null;

    if ($photoDb) {
        // 1) already absolute (http/https)
        if (preg_match('~^https?://~i', $photoDb)) {
            $photoUrl = $photoDb;
        }
        // 2) has a slash -> treat as relative path under public
        elseif (strpos($photoDb, '/') !== false) {
            // remove leading slash then asset()
            $photoUrl = asset(ltrim($photoDb, '/'));
        }
        // 3) only filename -> assume stored in /images/profile/
        else {
            $photoUrl = asset('images/profile/' . $photoDb);
        }
    }

    // fallback default avatar if empty/invalid
    if (!$photoUrl) {
        $photoUrl = asset('images/profile.png'); // আপনার ডিফল্ট ইমেজ
    }

    return response()->json([
        'found'            => true,
        'name'             => $user->name,
        'photo'            => $photoUrl,
        'referral_code'    => $user->referral_code,
        'balance'          => $user->balance,
        'voucher_balance'  => $user->voucher_balance,
    ]);
}

    public function update(Request $request)
    {
        // ভ্যালিডেশন
        $data = $request->validate([
            'identifier' => ['required','string','max:255'],       // email | mobile | referral_code | user_id
            'id_type'    => ['required','in:auto,email,mobile,referral_code,user_id'],
            'wallet'     => ['required','in:balance,voucher_balance'],
            'action'     => ['required','in:increment,decrement'],
            'amount'     => ['required','numeric','min:0.01'],
            'reason'     => ['nullable','string','max:255'],
            'pin'        => ['required','string','max:50'],
        ]);

        // PIN চেক
        $pin = (string) config('admin_security.balance_update_pin');
        if (!$pin || $data['pin'] !== $pin) {
            return back()->withInput()->with('error','পিন সঠিক নয়!');
        }

        // ইউজার ফাইন্ড করার লজিক
        $userQuery = $this->applyHiddenUserScope(User::query());
        $identifier = trim($data['identifier']);

        if ($data['id_type'] === 'email') {
            $user = (clone $userQuery)->where('email', $identifier)->first();
        } elseif ($data['id_type'] === 'mobile') {
            $user = (clone $userQuery)->where('mobile', $identifier)->first();
        } elseif ($data['id_type'] === 'referral_code') {
            $user = (clone $userQuery)->where('referral_code', $identifier)->first();
        } elseif ($data['id_type'] === 'user_id') {
            $user = (clone $userQuery)->where('id', (int)$identifier)->first();
        } else {
            // auto: প্রাধান্য—email > mobile > referral_code > id
            $user = (clone $userQuery)->where('email', $identifier)->first();
            if (!$user) $user = (clone $userQuery)->where('mobile', $identifier)->first();
            if (!$user) $user = (clone $userQuery)->where('referral_code', $identifier)->first();
            if (!$user && ctype_digit($identifier)) $user = (clone $userQuery)->where('id', (int)$identifier)->first();
        }

        if (!$user) {
            return back()->withInput()->with('error','কোনো ইউজার পাওয়া যায়নি!');
        }

        $wallet = $data['wallet']; // balance | voucher_balance
        $amount = round((float)$data['amount'], 2);
        $action = $data['action'];

        // ট্রানজ্যাকশন + রো-লক
        try {
            DB::transaction(function () use ($user, $wallet, $amount, $action, $data) {

                // for update lock
                $locked = User::where('id', $user->id)->lockForUpdate()->first();

                $before = (float)$locked->{$wallet};

                if ($action === 'increment') {
                    $after = $before + $amount;
                } else {
                    // decrement: নেগেটিভ হতে দেব না
                    if ($before < $amount) {
                        abort(422, 'পর্যাপ্ত ব্যালেন্স নেই—ডিক্রিমেন্ট করা যাবে না!');
                    }
                    $after = $before - $amount;
                }

                // আপডেট
                $locked->{$wallet} = $after;
                $locked->save();

                // অডিট লগ (DB::table সরাসরি; চাইলে মডেল ইউজ করুন)
                DB::table('balance_transactions')->insert([
                    'user_id'       => $locked->id,
                    'admin_id'      => Auth::guard('admin')->id() ?? 0,
                    'wallet'        => $wallet,
                    'action'        => $action,
                    'amount'        => $amount,
                    'before_amount' => $before,
                    'after_amount'  => $after,
                    'reason'        => $data['reason'] ?? null,
                    'created_at'    => now(),
                ]);

                // Income cards read from balance_logs + signed balance_transactions.
                // Keep this log for main wallet increment support.
                if ($wallet === 'balance' && $action === 'increment' && $amount > 0) {
                    BalanceLog::create([
                        'user_id' => $locked->id,
                        'amount' => $amount,
                    ]);
                }

                if ($wallet === 'balance') {
                    $reason = trim((string) ($data['reason'] ?? ''));
                    $signedAmount = $action === 'increment' ? $amount : -1 * $amount;
                    $baseDescription = $action === 'increment'
                        ?  $amount . '৳ এড করা হয়েছে।'
                        :  $amount . '৳ মাইনাস করা হয়েছে।';

                    IncomeHistory::create([
                        'user_id' => $locked->id,
                        'source' => 'admin_manual_adjustment',
                        'amount' => $signedAmount,
                        'description' => $reason !== ''
                            ? $baseDescription . ' কারণ: ' . $reason
                            : $baseDescription . ' কারণ: অ্যাডমিন ম্যানুয়াল সমন্বয়।',
                    ]);
                }

                if ($wallet === 'voucher_balance') {
                    $reason = trim((string) ($data['reason'] ?? ''));
                    $description = $action === 'increment'
                        ? 'অ্যাডমিন ভাউচার ব্যালেন্সে টাকা যোগ করেছেন।'
                        : 'অ্যাডমিন ভাউচার ব্যালেন্স থেকে টাকা মাইনাস করেছেন।';

                    if ($reason !== '') {
                        $description .= ' কারণ: ' . $reason;
                    }

                    VoucherTransactionService::record(
                        userId: (int) $locked->id,
                        direction: $action === 'increment' ? 'credit' : 'debit',
                        amount: $amount,
                        before: $before,
                        after: $after,
                        source: 'admin_manual_adjustment',
                        description: $description,
                        referenceType: 'admin_action',
                        referenceId: (Auth::guard('admin')->id() ?? 0),
                        adminId: (int) (Auth::guard('admin')->id() ?? 0),
                        metadata: [
                            'wallet' => $wallet,
                            'action' => $action,
                        ]
                    );
                }
            });
        } catch (\Throwable $e) {
            // abort(422, ...) ধরা পড়লে
            if ($e->getCode() === 0 && str_contains($e->getMessage(), 'পর্যাপ্ত ব্যালেন্স')) {
                return back()->withInput()->with('error', $e->getMessage());
            }
            return back()->withInput()->with('error', 'আপডেট ব্যর্থ: '.$e->getMessage());
        }

        return back()->with('success', 'ব্যালেন্স সফলভাবে আপডেট হয়েছে!');
    }

    private function canSeeHiddenUsers(): bool
    {
        $admin = Auth::guard('admin')->user();
        if (!$admin || !method_exists($admin, 'isSuperAdmin')) {
            return false;
        }

        return (bool) $admin->isSuperAdmin();
    }

    private function applyHiddenUserScope($query)
    {
        if (!$this->canSeeHiddenUsers() && Schema::hasColumn('users', 'is_hidden')) {
            $query->where(function ($inner) {
                $inner->whereNull('is_hidden')->orWhere('is_hidden', 0);
            });
        }

        return $query;
    }
}
