<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use AfricasTalking\SDK\AfricasTalking;


class Message extends Model
{
    use HasFactory;
    use SoftDeletes;

    protected $dates = ['deleted_at'];

    protected $fillable = [
        'username',
        'phone',
        'status',
        'email',
        'message',
        'type'
    ];


    public function sendSms($phone,$message)
    {
    	$sm =Setting::where('status',1)->first();

    	$username =  $sm->sms_username;
		$apiKey   = $sm->sms_apikey;
		//$sms_shortcode  = $sm->sms_shortcode;

		$AT = new AfricasTalking($username, $apiKey);


		$sms = $AT->sms();
		$result   = $sms->send([
		    'to'      => $phone,
		    'message' => $message,
            'from' => $sm->sms_shortcode
		]);


        if($result){

             // $u = User::where('phone', $phone)->first();
             $store = Message::create([
                'phone' => $phone,
                'message' => $message,
                'status' => 1
            ]);
        }
        // if($result['data']['SMSMessageData']['Recipients'][0]['statusCode']){
        //      $store = Message::create([
        //         'phone' => $phone,
        //         'message' => $message,
        //         'status' => 0
        //     ]);

        //     return 0;
        // }


		return $result;

    }
    public function sendSmsTest($phone,$message)
    {
        $sm =Setting::where('status',1)->first();
        $username =  $sm->sms_username;
        $apiKey   =  $sm->sms_apikey;
        //$from  = 'SwiftKenya';

        $AT       = new AfricasTalking($username, $apiKey);


        $sms = $AT->sms();
        $result   = $sms->send([
            'to'      => $phone,
            'message' => $message,
             'from' => $sm->sms_shortcode
        ]);

        return $result;

    }
}
