<?php

namespace App\Http\Controllers\Dashboard\Admin;

use App\Enum\TransactionDirection;
use App\Enum\TransactionMethod;
use App\Enum\TransactionStatus;
use App\Enum\TransactionType;
use App\Http\Controllers\Controller;
use App\Models\Plan;
use App\Models\Transaction;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class UserProfitBalanceController extends Controller
{
    public function index($uuid)
    {
        $breadcrumbs = [
            ['label' => config('app.name'), 'url' => '/'],
            ['label' => 'Dashboard', 'url' => route('admin.dashboard')],
            ['label' => 'Users', 'url' => route('admin.user.index')],
            ['label' => 'User Details', 'url' => route('admin.user.show', $uuid)],
            ['label' => 'Profit Balance', 'active' => true],
        ];

        $user = User::where('uuid', $uuid)->firstOrFail();

        $userPlans = $user->userPlans()->with(['plan'])->get();

        $data = [
            'title' => 'Profit Balance',
            'user' => $user,
            'breadcrumbs' => $breadcrumbs,
            'userPlans' => $userPlans,
        ];

        return view('dashboard.admin.user.profit_balance.index', $data);
    }

    public function store(Request $request, $uuid)
    {
        // Validate the request
        $request->validate([
            'amount' => 'required|numeric|min:0.01',
            'plan_id' => 'required|exists:plans,id',
        ]);

        try {
            // Get the user
            $user = User::where('uuid', $uuid)->firstOrFail();

            // Get the plan
            $plan = Plan::where('id', $request->plan_id)->firstOrFail();

            DB::transaction(function () use ($user, $plan, $request) {
                // Add the amount to the user's profit balance
                $user->profit_balance += $request->amount;
                $user->save();

                Transaction::create([
                    'user_id' => $user->id,
                    'type' => TransactionType::PROFIT,
                    'direction' => TransactionDirection::CREDIT,
                    'description' => 'Daily profit from plan ' . $plan->name,
                    'amount' => $request->amount,
                    'method' => TransactionMethod::TRADE,
                    'transaction_at' => now(),
                    'reference_id' => generateReferenceId(),
                    'other_reference_id' => $user->id,
                    'status' => TransactionStatus::COMPLETED,
                ]);
            });

            return redirect()->back()->with('success', 'Profit balance updated successfully.');
        } catch (\Exception $e) {
            Log::error('Error updating profit balance: ' . $e->getMessage());
            return redirect()->back()->with('error', 'Error updating profit balance.');
        }
    }
}
