<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use App\Models\Deposit;
use App\Models\Transaction;
use App\Models\RewardSetting; // ⬅️ added
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class AddMoneyManager extends Controller
{
    public function __construct()
    {
        // $this->middleware(['auth']);
        // $this->middleware('can:manage-deposits');
    }

    /**
     * GET /admin/deposits
     * Filters: status=[pending|approved|rejected], q=search
     */
    public function index(Request $request)
    {
        $request->validate([
            'status' => ['nullable','in:pending,approved,rejected'],
            'q'      => ['nullable','string','max:100'],
        ]);

        $query = Deposit::with(['user','method'])->latest();

        if ($request->filled('status')) {
            $query->where('status', $request->string('status')->toString());
        }

        if ($q = $request->string('q')->toString()) {
            $query->where(function($qq) use ($q) {
                $qq->where('reference','like',"%$q%")
                   ->orWhere('payer_phone','like',"%$q%")
                   ->orWhereHas('user', fn($uq) => $uq->where('name','like',"%$q%"));
            });
        }

        $deposits = $query->paginate(30)->withQueryString();

        return view('admin.deposits.index', compact('deposits'));
    }

    /**
     * POST /admin/deposits/{deposit}/approve
     * Body: note (nullable string)
     */
    public function approve(Deposit $deposit, Request $request)
    {
        $data = $request->validate([
            'note' => ['nullable','string','max:500'],
        ]);

        DB::transaction(function () use ($deposit, $data) {
            // Lock the deposit row, re-check status inside TX
            $dep = Deposit::whereKey($deposit->id)->lockForUpdate()->first();

            if (!$dep || $dep->status !== 'pending') {
                abort(400, 'Already processed.');
            }

            // Lock user row
            $user = $dep->user()->lockForUpdate()->first();

            // Fetch active reward setting (latest)
            $activeSetting = RewardSetting::where('is_active', true)->latest('id')->first();
            $percent = $activeSetting ? (float) $activeSetting->add_money_comm : 0.0;

            // Flip status first to block concurrent approvals
            $dep->update([
                'status'      => 'approved',
                'approved_at' => now(),
                'admin_note'  => $data['note'] ?? null,
            ]);

            // Credit wallet
            $user->balance = $user->balance + $dep->amount;

            // Calculate reward points from percent (integer, floor)
            // points = floor(amount * percent/100)
            $pointsToAdd = (int) floor(($dep->amount * $percent) / 100);

            // Increase reward points
            if ($pointsToAdd > 0) {
                $user->reward_points = $user->reward_points + $pointsToAdd;
            }

            $user->save();

            // Transaction log (money)
            Transaction::create([
                'user_id'       => $user->id,
                'type'          => 'credit',
                'amount'        => $dep->amount,
                'balance_after' => $user->balance,
                'related_type'  => Deposit::class,
                'related_id'    => $dep->id,
                'meta'          => [
                    'reference'     => $dep->reference,
                    'reward_percent'=> $percent,
                    'reward_points' => $pointsToAdd,
                ],
            ]);
        });

        return back()->with('ok', 'Deposit approved & reward points updated.');
    }

    /**
     * POST /admin/deposits/{deposit}/reject
     * Body: note (required string)
     */
    public function reject(Deposit $deposit, Request $request)
    {
        $data = $request->validate([
            'note' => ['required','string','max:500'],
        ]);

        DB::transaction(function () use ($deposit, $data) {
            $dep = Deposit::whereKey($deposit->id)->lockForUpdate()->first();

            if (!$dep || $dep->status !== 'pending') {
                abort(400, 'Already processed.');
            }

            $dep->update([
                'status'     => 'rejected',
                'admin_note' => $data['note'],
            ]);
        });

        return back()->with('ok', 'Deposit rejected.');
    }
}
