<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Mandate extends Model
{

    protected $table = 'mandate';

    protected $fillable = ['consumer_application_id','mandate_id','umrn','status','mode', 'action','collection','frequency','monthly_frequency','mandate_amount','rejection_message','mandate_cancel_response','applicant_id','expiry_date','until_cancelled','date_first_collection','applicant_type'];

    public function application(){
        return $this->hasOne('App\ConsumerApplication','id','consumer_application_id');
    }

    public static function cancel($id, $mandate_id){
        $payload = json_encode(array('cancel_reason'=>'C001')); //The cancellation reason. Either C001 (cancellation on customer request) or C002 (cancellation on merchant request).
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => _env('LOTUSPAYBASEURL').'/mandates/'.$mandate_id.'/cancel',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
            CURLOPT_USERPWD => _env('LOTUSPAYSECRETKEY'),
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => $payload,
            CURLOPT_HTTPHEADER => array(
                "Content-Type: application/json",
            ),
        ));

        $response = curl_exec($curl);
        $err = curl_error($curl);

        curl_close($curl);

        if($err){
            static::where('id',$id)->update(['mandate_cancel_response' => $err]);
            return $err;
        }
        static::where('id',$id)->update(['mandate_cancel_response' => $response]);
        $response = json_decode($response);
        if(isset($response->id)){
            static::where('id',$id)->update(['status' => 'cancelled']);
        }
        return $response;

    }
}
