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

require APPPATH . '/libraries/REST_Controller.php';
require APPPATH . '/libraries/Format.php';

use Restserver\Libraries\REST_Controller;

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");

class Api_digiflazz_harga extends CI_Controller
{

	public function __construct()
	{
		parent::__construct();
		$this->load->helper(['jwt', 'authorization']);
	}


	public function index()
	{
		date_default_timezone_set("Asia/Jakarta");

		//PANGGIL DATA
		$pulsa = $this->db->query("SELECT * FROM tbl_mst_pulsa");
		if ($pulsa->num_rows() > 0) {
			foreach ($pulsa->result() as $row) {
				$url = "https://api.digiflazz.com/v1/price-list";

				$header = array(
					'Content-Type: text/plain',
				);

				$data = array(
					'cmd' => 'prepaid',
					'username' => $this->config->item('digiflazz_api_username'),
					'sign' => md5($this->config->item('digiflazz_api_username') . $this->config->item('digiflazz_api_key') . 'pricelist')
				);

				$json = json_encode($data);
				$ch = curl_init();
				curl_setopt($ch, CURLOPT_URL, $url);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
				curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
				curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
				curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
				curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
				$result = curl_exec($ch);
				curl_close($ch);
				$response = json_decode($result, true)['data'];

				foreach ($response as $data) {
					//DIGIFLAZZ
					$buyer_sku_code = $data['buyer_sku_code'];
					$price = $data['price'];
					$seller_product_status = $data['seller_product_status'];

					//CEK JIKA PRODUK SAMA
					if ($buyer_sku_code == $row->mst_pulsa_kode) {
						//JIKA PRODUK AKTIF
						if ($seller_product_status === true) {
							//UPDATE tbl_mst_pulsa
							$this->db->query("UPDATE tbl_mst_pulsa set 
											mst_pulsa_harga='$price',
											mst_pulsa_status='0'
											where
											mst_pulsa_kode='$row->mst_pulsa_kode'");
						} else {
							//JIKA PRODUK TIDAK AKTIF
							//UPDATE tbl_mst_pulsa
							$this->db->query("UPDATE tbl_mst_pulsa set 
										mst_pulsa_harga='$price',
										mst_pulsa_status='1'
										where
										mst_pulsa_kode='$row->mst_pulsa_kode'");
						}
					}
				}
			}

			echo json_encode($response);
		}
	}
}
