<?php

namespace App\Http\Controllers\Admin;

use App\Enums\RecordStatus;
use App\Http\Controllers\Controller;
use App\Models\Deposit;
use App\Services\TransactionLogger;
use Illuminate\Http\Request;

class DepositController extends Controller
{
    public function index(Request $request)
    {
        $deposits = Deposit::with('user')
            ->latest()
            ->paginate(20)
            ->withQueryString();

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

    public function approve(Request $request, Deposit $deposit)
    {
        if ($deposit->status !== RecordStatus::Pending) {
            return back()->with('error', 'Deposit is not pending.');
        }

        $deposit->update([
            'status' => RecordStatus::Approved,
            'processed_by' => $request->user()->id,
            'processed_at' => now(),
        ]);

        $deposit->user->increment('balance', $deposit->amount);
        TransactionLogger::syncStatus($deposit);

        return back()->with('success', 'Deposit approved.');
    }

    public function reject(Request $request, Deposit $deposit)
    {
        if ($deposit->status !== RecordStatus::Pending) {
            return back()->with('error', 'Deposit is not pending.');
        }

        $deposit->update([
            'status' => RecordStatus::Rejected,
            'processed_by' => $request->user()->id,
            'processed_at' => now(),
            'admin_note' => $request->input('admin_note'),
        ]);

        TransactionLogger::syncStatus($deposit);

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