<?php

namespace App\Services;

use App\Core\Database;
use App\Models\Deposit;
use App\Models\Transaction;
use App\Constants\Status; // Ensure this exists
use Exception;

class DepositService
{
    public function addFund($requestData)
    {
        $amount = $requestData['amount'];
        $gateway = 'uddoktapay'; // Defaulting

        $deposit = Deposit::create([
            'user_id' => user_id(),
            'amount' => $amount,
            'track_id' => strRandom(),
            'status' => Status::UNPAID, // 0
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
        ]);

        $gatewayNamespace = "App\\Services\\Gateway\\" . ucfirst($gateway) . "\\Payment";
        if (!class_exists($gatewayNamespace)) {
            throw new Exception("Gateway Class not found");
        }

        $data = $gatewayNamespace::prepareDepositData($deposit, $gateway);

        if (isset($data['error'])) {
            throw new Exception($data['message']);
        }

        return $data;
    }

    public function completeDeposit(Deposit $deposit, string $paymentMethod, string $transactionId)
    {
        if (Transaction::where('transaction_id', $transactionId)->first()) {
            throw new Exception("Transaction ID already exists.");
        }

        $db = Database::getInstance();
        $db->beginTransaction();

        try {
            if ($deposit->status == Status::UNPAID) {
                $deposit->status = Status::PAID;
                $deposit->save();

                $user = $deposit->user();
                $user->balance += $deposit->amount;
                $user->save();

                Transaction::create([
                    'user_id' => $deposit->user_id,
                    'deposit_id' => $deposit->id,
                    'trx_type' => Status::CREDIT, // Adding money = Credit
                    'amount' => $deposit->amount,
                    'payment_method' => $paymentMethod,
                    'remarks' => "Deposit via $paymentMethod",
                    'transaction_id' => $transactionId,
                    'created_at' => date('Y-m-d H:i:s')
                ]);
            }
            $db->commit();
        } catch (Exception $e) {
            $db->rollBack();
            throw $e;
        }
    }
}
