<?php

declare(strict_types=1);

namespace App\Http\Controllers\Pages;

use Hypervel\Http\Request;
use Hypervel\Support\Facades\Auth;
use App\Models\User;
use App\Enums\UserTypes;
use App\Http\Controllers\Helpers\Permissions\UserPermissions;

class TransferMyCreditPageController
{
    use PageResponses_TransferMyCredit;

    public static function TransferMyCredit(string $hashkey, float $amount)
    {
        $currentuser = Auth::id();
        $currentuser = User::findOrFail($currentuser);
        if ($amount <= 0) {
            throw new \Exception('Invalid amount');
        }

        try {
            $target_user = User::where('hashkey', $hashkey)->first();
            $currentUserBalance = $currentuser->total_balance;

            if ($currentuser->acct_type !== UserTypes::ULTIMATE && $currentUserBalance < $amount) {
                throw new \Exception('Insufficient balance');
            }

            if (!$target_user) {
                throw new \Exception('User not found');
            }

            if ($target_user->id === $currentuser->id) {
                throw new \Exception('You cannot transfer points to yourself');
            }

            if (!UserPermissions::isDirectCreditTransfertoUserAllowed($hashkey)) {
                throw new \Exception('Permission Denied');
            }


            //Add function to subtract from current user
            if ($currentuser->acct_type !== UserTypes::ULTIMATE) {
                $currentuser->total_balance -= $amount;
                $currentuser->save();
            }

            $target_user->total_balance += $amount;
            $target_user->save();

            return true;

        } catch (\Throwable $th) {
             throw new \Exception( $th->getMessage());
        }
    }
}

trait PageResponses_TransferMyCredit
{
    public function Response_TransferMyCredit(Request $request)
    {
        $target_user = $request->input('target_user');
        $amount = $request->input('amount');
        if (!$target_user || !is_string($target_user) || !$amount || !is_numeric($amount)) {
            return Response::json(false, 404);
        }
        try {
            $success = self::TransferMyCredit($target_user, (float) $amount);
        } catch (\Throwable $th) {
            return response()->json($th->getMessage(), 500);
        }

        if (!$success) {
            return response()->json('User not found or transfer failed', 400);
        }

        return response()->json(true, 200);
    }
}
