<?php
namespace App\Models\Master;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Models\Master\Plans;
use Auth;
use DB;

class PaymentHistory extends Model
{
    use SoftDeletes;
    protected $connection = 'mysql';
    protected $dates = ['deleted_at'];
    protected $table = 'payment_history';
    protected $rules = array(
        
    );
    protected $injectUniqueIdentifier = true;
    protected $fillable = [];

    public function scopeTextSearch($query, $search)
    {
        return $query->where(function ($query) use ($search) {
            $query->where('seller_name', 'LIKE', '%'.$search.'%');
        });
    }
    /**
     save payment history
        HR - 2019
    */
    public static function SavePaymentHistory($subscriptions,$plan_id_primary)
    {    
        $plan_id = $subscriptions['plan_id'];;
        $plans = Plans::where('id',$plan_id_primary)->first();

        $PaymentHistory = new PaymentHistory;
        $PaymentHistory->seller_id =$subscriptions['seller_id'];
        $PaymentHistory->seller_plan_id =$subscriptions['SellerPlan_id'];
        $PaymentHistory->amount =(isset($subscriptions['plan']['amount']))?$subscriptions['plan']['amount']/100:$subscriptions['amount']/100;
        if($subscriptions['gateway'] == 'stripe'){
            $PaymentHistory->gateway ='stripe';
            $checkstrip = \App\Http\Controllers\Controller::fetchStripeCredential($subscriptions['seller_id']);
            $PaymentHistory->test  =(strpos(env('STRIPE_SECRET'), 'test'))?'Y':'N';
        }

        $PaymentHistory->payment_status  ='Success';
        if($subscriptions['gateway'] == 'stripe'){
            $PaymentHistory->subscription_id  =  (isset($subscriptions['id'])) ? $subscriptions['id'] : '' ;
        }else if($subscriptions['gateway'] == 'razorpay'){
            $PaymentHistory->payment_id  = $subscriptions['payment_id'];
            $PaymentHistory->subscription_id  = $subscriptions['subscription_id'];
        }
        if($plans->trial_days < 1){
          $PaymentHistory->transaction_type  ='Credit';
        }
        $PaymentHistory->save();
        return $PaymentHistory;
    }
    
    public static function DeletePayment($seller_id)
    {
      $date = date('Y-m-d');
      $deleted = PaymentHistory::where('seller_id', $seller_id)->update(['seller_id'=>'1']);
      return true;
    } 

    public static function getTotalOrderCredit($seller_id){

        $creditTotal = PaymentHistory::select(DB::raw('COALESCE(((SELECT SUM(order_credit_limit) FROM payment_history WHERE transaction_type = "Credit") - (SELECT SUM(order_credit_limit) FROM payment_history WHERE transaction_type = "Debit")), 0) as db_credit_limit'))->where('seller_id',$seller_id)->first();
        return $creditTotal['db_credit_limit']; 
    }
}
