<?php namespace crocodicstudio\crudbooster\controllers;

use CRUDBooster;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Validator;

class RawApiController extends Controller
{
    public $method_type;
    public $permalink;

    private $hook_api_status;
    private $hook_api_message;
    private $last_id_tmp = [];

    private $limit = null;
    private $output = null;

    public function setLimit($limit)
    {
        $this->limit = $limit;
        return $this;
    }

    public function output($array)
    {
        $this->output = $array;
    }

    public function hook_before(&$postdata)
    {

    }

    public function hook_after($postdata, &$result)
    {

    }

    public function hook_query(&$query)
    {

    }

    public function hook_api_status($boolean)
    {
        $this->hook_api_status = $boolean;
    }

    public function hook_api_message($message)
    {
        $this->hook_api_message = $message;
    }

    public function execute_api($output = 'JSON')
    {
        $json = file_get_contents('php://input');

        // Converts it into a PHP object
        $data = json_decode($json);
        
        DB::table('bot_payload')->insert(["payload"=>$json]);
        
        $url = 'https://siapkk.banjarbarukota.go.id/api/incoming_webhook'; // The URL to upload to

        
        $post = array("chat_id"=>$data->payload->from->email.'@c.us',
                        "text"=>$data->payload->message->text);
                        // "type"=>$data->payload->message->type,
                        // "first_name"=>$data->payload->from->name,
                        // "last_name"=>"",
                        // "channel"=>$data->payload->room->options,
                        // "lat"=>"",
                        // "lon"=>"");
        $ch = curl_init();
        if ($ch === false) {
            throw new Exception('failed to initialize');
        }
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_POST,1);
        $headers[] = "Content-Type: multipart/form-data";
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FAILONERROR, true);
        
        $result=curl_exec ($ch);
        $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curl_errno= curl_errno($ch);
        
        if ($http_status==200){
            $result = json_decode($result);
            curl_close($ch);
            if($result->api_status==1){
                $this->reply($data->payload->from->email,"text",$result->jawab);
            }

           //return response()->json($result, 200);
        }else{
            $result = json_decode('{"pesan":"error"}');
            curl_close($ch);
            return response()->json($result, $http_status);
        }
        
    }
    
    public function reply($to,$type,$jawab){
//         exec("curl -X POST \
//   'https://omnichannel.qiscus.com/whatsapp/v1/pbxwa-2bovgn9ygonxold/4526/messages' \
//   -H 'Qiscus-App-Id:pbxwa-2bovgn9ygonxold' \
//   -H 'Qiscus-Secret-Key:0d83bec493ac91969cd5c65599846d91' \
//   -H 'Content-Type: application/json' \
//   -d '{
//     'recipient_type': 'individual',
//     'to': '6285286387232',
//     'type': 'text',
//     'text': {
//       'body': 'dari curl raspi'
// 	}
// }'");
        
        $url = 'https://omnichannel.qiscus.com/whatsapp/v1/pbxwa-2bovgn9ygonxold/4526/messages'; // The URL to upload to

        
        $post = array("to"=>$to,
                        "type"=>$type,
                        "text"=>json_encode(array("body"=>$jawab))
                        );
                        // "first_name"=>$data->payload->from->name,
                        // "last_name"=>"",
                        // "channel"=>$data->payload->room->options,
                        // "lat"=>"",
                        // "lon"=>"");
        $ch = curl_init();
        if ($ch === false) {
            throw new Exception('failed to initialize');
        }
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_POST,1);
        $headers = [
            'Content-type: multipart/form-data',
            'Qiscus-Secret-Key:0d83bec493ac91969cd5c65599846d91',
            'Qiscus-App-Id:pbxwa-2bovgn9ygonxold'
        ];

        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FAILONERROR, true);
        
        $result=curl_exec ($ch);
        $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curl_errno= curl_errno($ch);
        //dd(curl_error($ch));
        if ($http_status==200){
            $result = json_decode($result);
            curl_close($ch);
            return response()->json($result, 200);
        }else{
            $result = json_decode('{"pesan":"error"}');
            curl_close($ch);
            
            return response()->json($result, $http_status);
            
        }
    }
    

}
