<?php

namespace App\Repositories;

use App\Models\AccountTransaction;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Mail\Mailer;
use Illuminate\Support\Facades\Schema;

class AccountTransactionRepository
{
    public function __construct(AccountTransaction $accountTransaction, Filesystem $filesystem, Mailer $mailer)
    {
        $this->model = $accountTransaction;
        $this->file = $filesystem;
        $this->mailer = $mailer;
    }

    public function listByUserAndStore($userId, $storeId, $limit = 20)
    {
		if($storeId){
			return $this->model
				->where('user_id', '=', (int) $userId)
				//->where('store_id', '=', (int) $storeId)
				->orderBy('id', 'desc')
				->paginate($limit);
		}else{
			return $this->model
            ->where('user_id', '=', (int) $userId)
            ->orderBy('id', 'desc')
            ->paginate($limit);
		}		
    }

    public function add($userId, $storeId, $amount, $trType, $type = null, $typeId = null, array $meta = [])
    {
        $tx = $this->model->newInstance();
        $tx->user_id = (int) $userId;
        $tx->store_id = (int) $storeId;
        $tx->amount = round((float) $amount, 2);
        $tx->tr_type = (string) $trType;
        $tx->type = $type;
        $tx->type_id = $typeId;

        foreach ($meta as $key => $value) {
            try {
                if (Schema::hasColumn($tx->getTable(), $key)) {
                    $tx->{$key} = $value;
                }
            } catch (\Throwable $e) {
                // If schema lookup fails for any reason, skip setting unknown meta.
            }
        }

        $tx->save();

        return $tx;
    }
}
