<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Kurir_model extends CI_Model {
    private function set_cost($kurir) {
        $curl       = curl_init();
        $key        = '05c00701d16e450b810bd7cbc9da95f1';       

        $query = [
            'originType'      => 'city',
            'destinationType' => 'subdistrict',
            'origin'          => 243,
            'destination'     => 241,
            'weight'          => 1000,
            'courier'         => $kurir
        ];

        curl_setopt_array($curl, array(
            CURLOPT_URL             => "https://pro.rajaongkir.com/api/cost",
            CURLOPT_RETURNTRANSFER  => true,
            CURLOPT_ENCODING        => "",
            CURLOPT_MAXREDIRS       => 10,
            CURLOPT_TIMEOUT         => 30,
            CURLOPT_HTTP_VERSION    => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST   => "POST",
            CURLOPT_POSTFIELDS      => http_build_query($query),
            CURLOPT_HTTPHEADER      => array(
                "content-type: application/x-www-form-urlencoded",
                "key: {$key}"
            ),
        ));
          
        $response   = curl_exec($curl);            
        $err        = curl_error($curl);
        
        curl_close($curl);

        return json_decode($response);
    }

    public function cost() {
        $data  = [];
        $kurir = ['pos', 'tiki', 'jne', 'wahana', 'jnt', 'anteraja'];

        foreach($kurir as $item) {
            $get = $this -> set_cost($item);
            if($get) {
                $list = $get -> rajaongkir -> results;
                foreach($list[0] -> costs as $row) {
                    $service = str_replace('Pos', '', $row -> service);
                    $name    = strtoupper($list[0] -> code . ' ' . ltrim($service));
                    $etd     = str_replace('HARI', '', $row -> cost[0] -> etd);
                    $cost    = $row -> cost[0] -> value;
                    $img     = base_url('upload/ekspedisi/'.$item.'.png');
                    $data[]  = (object) [
                        'name' => $name,
                        'etd'  => $etd ? trim($etd) . ' Hari' : '-',
                        'cost' => $cost,
                        'img'  => $img
                    ];
                }
            }
        }

        return $data;
    }
}

// Kurir Model
// Kode ini dibuat oleh codelingker