<?php


namespace Mehrab\Payment\Repositories;

use Mehrab\Payment\Models\Settlement;
use Mehrab\RolePermission\Models\Permission;

class SettlementRepo
{
    public $query;

    public function __construct()
    {
        $this->query = Settlement::query();
    }

    public function list($request,$with = []){

        $user = auth()->user();
        $query = $this->query->with($with);

        if ($user->hasPermissionTo(Permission::PERMISSION_SUPER_ADMIN) || $user->hasPermissionTo(Permission::PERMISSION_MANAGE_PAYMENT)) {

        }
        if ($user->hasPermissionTo(Permission::PERMISSION_EXPERT)){
            $query->where('user_id',$user->id);
        }

        return $query->orderBy('created_at','desc')->paginate();
    }



    public function update($request,$settlement)
    {
//        $report = $settlement->report;
        if ($request->report){
            $report[time()] = $request->report;
        }
        return $settlement->update([
            'to' => [
                'cart' => $request->cart,
                'name' => $request->name,
                'shaba' => $request->shaba
            ],
            'from' =>[
                'name' => $request->from_name,
            ],
            'reports' => $report ?? '',
            'status' => $request->status,
            'transaction_id' => $request->transaction_id,
        ]);

    }

    public function find($settlementID)
    {
        return $this->query->findOrFail($settlementID);
    }

    public function getLatestPendingSettlement(){
        return Settlement::query()
            ->where('user_id',auth()->id())
            ->where('status',Settlement::STATUS_PENDING)
            ->latest()
            ->first();
    }

    public function getLatestSettlement($userID){
        return Settlement::query()
            ->where('user_id',$userID)
            ->latest()
            ->first();
    }
}
