<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;

class Sale extends BaseModel
{
    use HasFactory;

    protected $fillable = ['order_id','cc_number','status','auth_code','transaction_id','ip','user_id','recurring_id','created_at'];

    public function createSale($inputData){
        return self::create($inputData);
    }
    public function updateByOrderId($order_id,$data){
        return $this->where('order_id',$order_id)->update($data);
    }

    public function getDataByTransactionId($transaction_id){
        return $this->where('transaction_id',$transaction_id)->first();
    }
    public function  getLatestSalesByUserId($user_id)
    {
        $user_sale_obj=[];
        $user_sale_obj=self::where(['user_id' => $user_id, 'status' => 1])->latest('id')->first();
        return $user_sale_obj;
    }
    public function getSalesList($inputData)
    {
        $fromDate=$inputData['fdate'];
        $toDate=$inputData['tdate'];
        $clientName=$inputData['clientName'];
        $payStatus=$inputData['payStatus'];

        $result = [];
        $salesResult=self::join('users', 'sales.user_id', '=', 'users.id')
            ->select('sales.*','users.first_name',
                'users.last_name','users.email',
                'users.street_no','users.street_name',
                'users.city','users.state',
                'users.phone','users.zip_code',
                'users.ssn')
            ->getQuery();

        if(!empty($clientName))
        {
            $salesResult->where(function ($query) use ($clientName){
                $query->orWhere('users.first_name', 'like', "%$clientName%")
                    ->orWhere('users.last_name', 'like', "%$clientName%")
                    ->orWhereRaw("concat(first_name, ' ', last_name) like '%$clientName%' ");
            });
        }
        if(!empty($fromDate) && !empty($toDate))
        {
            $salesResult->whereBetween('sales.created_at',[$fromDate.' 00:00:00', $toDate.' 23:59:59']);
        }
        if(is_numeric($payStatus))
        {
            $salesResult->where('sales.status',$payStatus);
        }

//        dd($salesResult->toSql());
        $result= $salesResult->latest('id')->paginate($inputData['pageLimit']);

        return $result;

    }

}
