<?php
namespace App\Http\Actions;

use App\Models\Order;
use App\Models\Transaction;

class CompleteTransaction{

        /**
     * Completes transaction after successful paystack payment
     *
     */
    public function execute($payment)
    {
        if(!$payment){
            return;
        }
        $amt = $payment['amount'];
        $amount = $amt / 100;
        $this->updateTransaction($payment, $amount);
    }

    private function updateTransaction($payment, $amount){
        $transaction = Transaction::where("reference", $payment['reference'])->first();
        if($transaction){
            //update transaction
            $orderId = $transaction->order_id;
            //order
            Order::where("order_id", $orderId)->update(["payment_status" => "success", "sale_status" => "pending"]);
            //transaction
            Transaction::where("order_id", $orderId)->update(
                [
                    "status" => $payment['status'],
                    "payment_id" => $payment['id'],
                    "fee" => $payment['fees'],
                    "paid_at" => $payment['paid_at'],
                ]
            );
        }
    }
}
?>
