<?php
ini_set('memory_limit', '7000M');
ini_set('max_execution_time', 300); //300 seconds = 5 minutes
defined('BASEPATH') or exit('No direct script access allowed');

class Order_pulsa extends MY_Controller
{
	public function __construct()
	{
		parent::__construct();
		if (website_config('mt_web') == 1) {
			exit(redirect(base_url('maintenance')));
		}
		check_cookie(get_cookie('smm_login'));
		if (user() == false) exit(redirect(base_url('auth/logout')));
	}
	public function form($i = '')
	{
		$i = $this->db->escape_str($i);
		if (in_array($i, ['Pulsa', 'PaketInternet', 'PaketSMS', 'VoucherGame', 'Emoney', 'TokenListrik', 'Games', 'Other']) == false) show_404();
		$data = $this->service_category_model->get_row(['type' => $i]);
		$category = $this->service_category_model->get_rows([
			'where' => [['type' => $i]],
			'order_by' => 'id ASC'
		]);
		$this->render('public/order_pulsa/form', ['page_type' => 'Transaksi', 'type' => $data, 'category' => $category]);
	}
	public function submit()
	{
		// filter input = 1
		if ($this->input->post()) {
			$this->form_validation->set_rules('service', 'Layanan', 'required|numeric');
			$this->form_validation->set_rules('target', 'Target', 'required');
			if ($this->form_validation->run() == true) {

				// CHECK SERVICE //
				$service = $this->service_pulsa_model->get_row(['id' => $this->input->post('service'), 'status' => '1']);
				if ($service == false) {
					$this->session->set_flashdata('result', array('alert' => 'danger', 'title' => 'Gagal!', 'msg' => 'Layanan tidak tersedia.'));
					exit(redirect(base_url()));
				}


				$data_input = [
					'user_id' => user(),
					'service_id' => $this->db->escape_str($this->input->post('service')),
					'target' =>  htmlentities($this->db->escape_str(strip_tags($this->input->post('target')))),
					'price' => 0, // reset
					'profit' => 0, // reset
					'status' => 'Pending',
					'is_api' => 0,
					'is_refund' => 0,
					'api_id' => 0, // reset
					'api_order_id' => 0, // reset
					'api_log_order' => null, // reset
					'ip_address' => $this->input->ip_address(),
					'custom_link' => $this->input->post('no_meter'),
					'created_at' => date('Y-m-d H:i:s'),
					'updated_at' => date('Y-m-d H:i:s'),
					'uplink' => user('uplink'),
				];
				//				print_r($data_input); die;
				// LIMIT THE SAME ORDER TARGET //
				if (website_config('limit_order') > 0) {
					if ($this->order_pulsa_model->get_count(['where' => [['user_id' => user(), 'target' => $data_input['target']], "status IN ('Pending', 'Processing')"]]) >= website_config('limit_order')) {
						$this->session->set_flashdata('result', array('alert' => 'danger', 'title' => 'Gagal!', 'msg' => 'Mohon menunggu sampai pesanan sebelumnya dengan target yang sama selesai diproses.'));
						exit(redirect(base_url()));
					}
				}
				// END LIMIT THE SAME ORDER TARGET //
				$data_input['service'] = $service->name;
				// SET PRICE & PROFIT //
				$data_input['price'] = $service->price;
				$data_input['profit'] = $service->profit;
				$custom_price = $this->custom_price_model->get_row(['service_id' => $data_input['service_id'], 'user_id' => user()]);
				if ($custom_price == true) {
					$data_input['price'] = $custom_price->price;
					$data_input['profit'] = $custom_price->profit;
				}
				// END SET PRICE & PROFIT //

				// CHECK USER BALANCE //
				if (user('balance') < $data_input['price']) {
					$this->session->set_flashdata('result', array('alert' => 'danger', 'title' => 'Gagal!', 'msg' => 'Sisa saldo Anda tidak cukup untuk membuat pesanan ini.'));
					exit(redirect(base_url()));
				}
				// END CHECK USER BALANCE //

				// CHECK API //
				$api = $this->api_model->get_by_id($service->api_id);
				if ($api == false) {
					$this->session->set_flashdata('result', array('alert' => 'danger', 'title' => 'Gagal!', 'msg' => 'Layanan tidak tersedia 1.'));
					exit(redirect(base_url()));
				}
				$data_input['api_id'] = $api->id;
				// END CHECK API //
				$provider_order_id = false;
				if ($api->is_manual == '1') {
					$provider_order_id = true;
				} else { // OPER DIGIFLAZZ
					$trx_id = $this->lib->random_strings(10);
					$username = 'hepihogxm09o';
					$data = array(
						'username' => 'hepihogxm09o', // konstan
						'buyer_sku_code' => $service->api_service_id,
						'customer_no' => $data_input['target'],
						'ref_id' => $trx_id,
						'sign' => md5("hepihogxm09o" . "0b9d2dbe-1727-5bb9-95a1-cb3902bdbf93" . "$trx_id")
					);

					$header = array(
						'Content-Type: application/json',
					);
					$curl = $this->lib->curl('https://api.digiflazz.com/v1/transaction', json_encode($data), $header);
					$result = json_decode($curl, true);
					//$this->lib->print_data($result);
					if (isset($result['data']['rc']) and $result['data']['rc'] == 03 or $result['data']['rc'] == 00) {
						$provider_order_id = $result['data']['ref_id'];
						$data_input['api_order_id'] = $provider_order_id;
						$data_input['api_log_order'] = $this->db->escape($curl);
					}
				}
				if ($provider_order_id != null) {
					$this->db->trans_start();
					$this->user_model->update(['balance' => user('balance') - $data_input['price']], ['id' => user()]);
					$insert_order = $this->order_pulsa_model->insert($data_input);
					$this->log_balance_usage_model->insert([
						'user_id' => user(),
						'type' => 'minus',
						'category' => 'place order',
						'amount' => $data_input['price'],
						'description' => 'Membuat pesanan <b>Pulsa & PPOB</b> #' . $insert_order . '.',
						'created_at' => date('Y-m-d H:i:s')
					]);
					$this->db->trans_complete();
					if ($this->db->trans_status() == true) {
						$this->session->set_flashdata('result', array('alert' => 'success', 'title' => 'Pesanan berhasil dibuat!', 'msg' => 'ID Pesanan: ' . $insert_order . '<br />Layanan: ' . $service->name . '<br />Target: ' . $data_input['target'] . ''));
						exit(redirect(base_url()));
					} else {
						log_message('error', $data_input);
						$this->session->set_flashdata('result', array('alert' => 'danger', 'title' => 'Gagal!!!', 'msg' => 'Terjadi kesalahan tidak terduga.'));
						exit(redirect(base_url()));
					}
					exit(redirect(base_url()));
				} else {
					$this->service_pulsa_model->update(['status' => 0], ['id' => $service->id]);
					$this->session->set_flashdata('result', array('alert' => 'danger', 'title' => 'Gagal!', 'msg' => 'Layanan sedang mengalami gangguan 2'));
					exit(redirect(base_url()));
				}
			} else {
				$this->session->set_flashdata('result', array('alert' => 'danger', 'title' => 'Gagal!', 'msg' => '<br />' . validation_errors()));
				exit(redirect(base_url()));
			}
		}
	}

	public function history()
	{
		// filter input = 1
		// FORM INPUT //
		$rows = [
			'10' => '10',
			'25' => '25',
			'50' => '50',
			'100' => '100',
		];
		$status = [
			'Pending' => 'Pending',
			'Processing' => 'Processing',
			'Success' => 'Success',
			'Error' => 'Error',
			'Partial' => 'Partial',
		];
		// END FORM INPUT //
		// SETTINGS //
		$data_query = [
			'select' => 'order_pulsa_list.*, service_pulsa.name AS service_name',
			'join' => [
				[
					'table' => 'service_pulsa',
					'on' => 'service_pulsa.id = order_pulsa_list.service_id',
					'param' => 'LEFT'
				]
			],
			'where' => [['order_pulsa_list.user_id' => user()]],
			'order_by' => 'order_pulsa_list.id DESC',
			'limit' => '10',
			'offset' => ($this->uri->segment(3)) ? $this->uri->segment(3) : 0
		];
		// END SETTINGS //
		// SORT & SEARCH
		if ($this->input->get('rows')) {
			if (array_key_exists($this->input->get('rows'), $rows) == false) exit(redirect(base_url('order_pulsa/history')));
			$data_query['limit'] = $this->input->get('rows');
		}

		if ($this->input->get('status') <> '') {
			if (array_key_exists($this->input->get('status'), $status) == false) exit(redirect(base_url('order_pulsa/history')));
			$data_query['where'][]['order_pulsa_list.status'] = $this->input->get('status');
		}
		if ($this->input->get('search') <> '') {
			$data_query['where'][]['order_pulsa_list.id'] = $this->input->get('search');
		}
		// PAGINATION //
		if ($this->uri->segment(3) <> '' and is_numeric($this->uri->segment(3)) == false) exit('shafou.com');
		$config['base_url'] = base_url('order_pulsa/history');
		$config['total_rows'] = $this->order_pulsa_model->get_count($data_query);
		$config['per_page'] = $data_query['limit'];
		$this->pagination->initialize($config);
		// END PAGINATION //
		$this->render('public/order_pulsa/history', ['page_type' => 'Riwayat Pesanan', 'table' => $this->order_pulsa_model->get_rows($data_query), 'total_data' => $config['total_rows'], 'rows' => $rows, 'status' => $status]);
	}
	public function detail($i = '', $csrf = '')
	{
		// filter input = 1
		if ($csrf <> $this->security->get_csrf_hash()) exit(show_404());
		$i = $this->db->escape_str($i);
		$target = $this->order_pulsa_model->get_row(['user_id' => user(), 'id' => $i]);
		if ($target == false) show_404();
		$this->render('public/order_pulsa/detail', ['page_type' => 'Detail Pesanan', 'target' => $target, 'service' => $this->service_pulsa_model->get_by_id($target->service_id)]);
	}
	public function graph()
	{
		$chart_item = $this->lib->list_date_range(date('Y-m-01'), date('Y-m-t'));
		$chart = [];
		foreach ($chart_item as $key => $value) {
			array_push($chart, [
				'date' => $value,
				'count' => $this->order_pulsa_model->get_count(['where' => [['user_id' => user(), 'DATE(created_at)' => $value]]])
			]);
		}
		$this->render('public/order_pulsa/graph', ['page_type' => 'Grafik Pesanan', 'chart' => $chart]);
	}
}
