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

class Order_pulsa extends MY_Controller
{
	public function __construct()
	{
		parent::__construct();
		check_cookie_admin(get_cookie('admin_login'));
		if (admin() == false) exit(redirect(base_url('admin/auth/logout')));
	}
	public function report()
	{
		if ($this->input->get('start') and $this->input->get('end')) {
			$start = $this->input->get('start');
			$end = $this->input->get('end');
		} else {
			$start = date('Y-m-01');
			$end = date('Y-m-t');
		}
		$widget = [
			'gross' => $this->order_pulsa_model->get_rows(['select' => 'SUM(price) AS rupiah, COUNT(price) AS total', 'where' => [['target <>' => 'bot_fake_order', 'DATE(created_at) >=' => $start, 'DATE(created_at) <=' => $end]]]),
			'net' => $this->order_pulsa_model->get_rows(['select' => 'SUM(profit) AS rupiah, COUNT(profit) AS total', 'where' => [['target <>' => 'bot_fake_order', 'DATE(created_at) >=' => $start, 'DATE(created_at) <=' => $end]]]),
			'gross_success' => $this->order_pulsa_model->get_rows(['select' => 'SUM(price) AS rupiah, COUNT(price) AS total', 'where' => [['status' => 'Success', 'target <>' => 'bot_fake_order', 'DATE(created_at) >=' => $start, 'DATE(created_at) <=' => $end]]]),
			'net_success' => $this->order_pulsa_model->get_rows(['select' => 'SUM(profit) AS rupiah, COUNT(profit) AS total', 'where' => [['status' => 'Success', 'target <>' => 'bot_fake_order', 'DATE(created_at) >=' => $start, 'DATE(created_at) <=' => $end]]]),
			'gross_error' => $this->order_pulsa_model->get_rows(['select' => 'SUM(price) AS rupiah, COUNT(price) AS total', 'where' => [['status' => 'Error', 'target <>' => 'bot_fake_order', 'DATE(created_at) >=' => $start, 'DATE(created_at) <=' => $end]]]),
			'net_error' => $this->order_pulsa_model->get_rows(['select' => 'SUM(profit) AS rupiah, COUNT(profit) AS total', 'where' => [['status' => 'Error', 'target <>' => 'bot_fake_order', 'DATE(created_at) >=' => $start, 'DATE(created_at) <=' => $end]]]),
		];
		$chart_item = $this->lib->list_date_range($start, $end);
		$chart = [];
		foreach ($chart_item as $key => $value) {
			$a = array_push($chart, [
				'date' => $value,
				'all' => $this->order_pulsa_model->get_count(['where' => [['target <>' => 'bot_fake_order', 'DATE(created_at)' => $value]]]),
				'pending' => $this->order_pulsa_model->get_count(['where' => [['target <>' => 'bot_fake_order', 'status' => 'Pending', 'DATE(created_at)' => $value]]]),
				'in progress' => $this->order_pulsa_model->get_count(['where' => [['target <>' => 'bot_fake_order', 'status' => 'in progress', 'DATE(created_at)' => $value]]]),
				'processing' => $this->order_pulsa_model->get_count(['where' => [['target <>' => 'bot_fake_order', 'status' => 'Processing', 'DATE(created_at)' => $value]]]),
				'success' => $this->order_pulsa_model->get_count(['where' => [['target <>' => 'bot_fake_order', 'status' => 'Success', 'DATE(created_at)' => $value]]]),
				'error' => $this->order_pulsa_model->get_count(['where' => [['target <>' => 'bot_fake_order', 'status' => 'Error', 'DATE(created_at)' => $value]]]),
				'partial' => $this->order_pulsa_model->get_count(['where' => [['target <>' => 'bot_fake_order', 'status' => 'Partial', 'DATE(created_at)' => $value]]]),
			]);
		}
		$this->render_admin('admin/' . $this->uri->segment(2) . '/report', ['widget' => $widget, 'chart' => $chart, 'start' => $start, 'end' => $end]);
	}
	public function tes($huruf)
	{
		echo $this->lib->format_datetime(date('Y-m-d H:i:s'));
		echo $huruf;
	}
	public function index()
	{
		// FORM INPUT //
		$field = [
			'order_pulsa_list.id' => 'ID',
			'order_pulsa_list.api_order_id' => 'SID',
			'order_pulsa_list.created_at' => 'TANGGAL/WAKTU',
			'user.username' => 'PENGGUNA',
			'service.name' => 'LAYANAN',
			'order_pulsa_list.target' => 'TARGET',
			'order_pulsa_list.price' => 'HARGA',
			'order_pulsa_list.status' => 'STATUS',
		];
		$operator = [
			'equal' => 'WHERE =',
			'not_equal' => 'WHERE <>',
			'less_than' => 'WHERE <=',
			'more_than' => 'WHERE >=',
			'like' => 'LIKE %value%'
		];
		$status = [
			'Pending' => ['name' => 'Pending', 'color' => 'warning'],
			'Processing' => ['name' => 'Processing', 'color' => 'info'],
			'Success' => ['name' => 'Success', 'color' => 'success'],
			'Partial' => ['name' => 'Partial', 'color' => 'danger'],
			'Error' => ['name' => 'Error', 'color' => 'danger'],
			'Unpaid' => ['name' => 'Unpaid', 'color' => 'primary'],
		];
		// END FORM INPUT //
		// SETTINGS //
		$data_query = [
			'select' => 'order_pulsa_list.*, user.username, service.name AS service_name',
			'join' => [
				[
					'table' => 'user',
					'on' => 'user.id = order_pulsa_list.user_id',
					'param' => 'LEFT'
				],
				[
					'table' => 'service',
					'on' => 'service.id = order_pulsa_list.service_id',
					'param' => 'LEFT'
				]
			],
			'where' => [['order_pulsa_list.target <>' => 'bot_fake_order'], ($this->input->get('status')) ? ['order_pulsa_list.status' => $this->input->get('status')] : ['order_pulsa_list.status <>' => 'MVHIRDPY']],
			'order_by' => 'order_pulsa_list.id DESC',
			'limit' => '30',
			'offset' => ($this->uri->segment(4)) ? $this->uri->segment(4) : 0
		];
		// END SETTINGS //
		// SORT & SEARCH
		if ($this->input->get('sort_field') <> '' and $this->input->get('sort_type') <> '') {
			if (array_key_exists($this->input->get('sort_field'), $field) == false) exit(redirect(base_url('admin/' . $this->uri->segment(2) . '/index')));
			if (in_array($this->input->get('sort_type'), array('asc', 'desc')) == false) exit(redirect(base_url('admin/' . $this->uri->segment(2) . '/index')));
			$data_query['order_by'] = $this->input->get('sort_field') . ' ' . $this->input->get('sort_type');
		}
		if ($this->input->get('field') <> '' and $this->input->get('operator') <> '' and $this->input->get('value') <> '') {
			if (array_key_exists($this->input->get('field'), $field) == false) exit(redirect(base_url('admin/' . $this->uri->segment(2) . '/index')));
			if (array_key_exists($this->input->get('operator'), $operator) == false) exit(redirect(base_url('admin/' . $this->uri->segment(2) . '/index')));
			if ($this->input->get('operator') == 'equal') {
				$data_query['where'][] = [$this->input->get('field') => $this->input->get('value')];
			} elseif ($this->input->get('operator') == 'not_equal') {
				$data_query['where'][] = [$this->input->get('field') . ' <>' => $this->input->get('value')];
			} elseif ($this->input->get('operator') == 'less_than') {
				$data_query['where'][] = [$this->input->get('field') . ' <=' => $this->input->get('value')];
			} elseif ($this->input->get('operator') == 'more_than') {
				$data_query['where'][] = [$this->input->get('field') . ' >=' => $this->input->get('value')];
			} else {
				$data_query['where'][] = $this->input->get('field') . " LIKE '%" . $this->input->get('value') . "%'";
			}
		}
		// END SORT & SEARCH
		// SESSION FILTER //
		if ($this->session->userdata('filter_order_pulsa_user') <> '') {
			$data_query['where'][]['order_pulsa_list.user_id'] = $this->session->userdata('filter_order_pulsa_user');
		}
		if ($this->session->userdata('filter_order_pulsa_status') <> '') {
			$data_query['where'][]['order_pulsa_list.status'] = $this->session->userdata('filter_order_pulsa_status');
		}
		if ($this->session->userdata('filter_order_pulsa_service') <> '') {
			$data_query['where'][]['order_pulsa_list.service_id'] = $this->session->userdata('filter_order_pulsa_service');
		}
		if ($this->session->userdata('filter_order_pulsa_api') <> '') {
			$data_query['where'][]['order_pulsa_list.api_id'] = $this->session->userdata('filter_order_pulsa_api');
		}
		// END SESSION FILTER //
		// PAGINATION //
		if ($this->uri->segment(4) <> '' and is_numeric($this->uri->segment(4)) == false) exit('No direct script access allowed');
		$config['base_url'] = base_url('admin/' . $this->uri->segment(2) . '/index');
		$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_admin('admin/' . $this->uri->segment(2) . '/index', ['table' => $this->order_pulsa_model->get_rows($data_query), 'total_data' => $config['total_rows'], 'field' => $field, 'operator' => $operator, 'status' => $status, 'user' => $this->user_model->get_rows(), 'service' => $this->service_model->get_rows(), 'api' => $this->api_model->get_rows()]);
	}

	public function mass_form()
	{
		$service_keys = $this->input->post('id');
		$status = $this->input->post('status');
		$sn = $this->input->post('sn');
		for ($i = 0; $i < count($service_keys); $i++) {
			$this->db->trans_start();
			$this->order_pulsa_model->update([
				'status' => $status[$i],
				'sn' => $sn[$i],
			], ['id' => $service_keys[$i]]);
			$this->db->trans_complete();
		}
		$this->session->set_flashdata('result', array('alert' => 'success', 'title' => 'Perubahan data berhasil!', 'msg' => 'Data berhasil diperbaharui.'));
		exit(redirect(base_url('admin/' . $this->uri->segment(2))));
	}

	public function mass_edit()
	{
		$status = [
			'Pending' => ['name' => 'Pending', 'color' => 'warning'],
			'Processing' => ['name' => 'Processing', 'color' => 'info'],
			'Success' => ['name' => 'Success', 'color' => 'success'],
			'Partial' => ['name' => 'Partial', 'color' => 'danger'],
			'Error' => ['name' => 'Error', 'color' => 'danger'],
		];

		$data = explode(",", $this->input->post('list_id'));
		$this->db->select('*');
		$this->db->from('order_pulsa_list');
		$this->db->where_in('id', $data);
		$query = $this->db->get();
		$data_order = $query->result_array();
		$this->render_admin('admin/' . $this->uri->segment(2) . '/mass_edit', ['target' => $data_order, 'status' => $status]);
	}

	public function form($i = '')
	{
		$target = $this->order_pulsa_model->get_by_id($i);
		if ($target == false) {
			show_404();
		} else { // edit
			$status = [
				'Pending' => ['name' => 'Pending', 'color' => 'warning'],
				'Processing' => ['name' => 'Processing', 'color' => 'info'],
				'Success' => ['name' => 'Success', 'color' => 'success'],
				'Partial' => ['name' => 'Partial', 'color' => 'danger'],
				'Error' => ['name' => 'Error', 'color' => 'danger'],
			];

			if ($this->input->post()) {
				$this->form_validation->set_rules('start_count', 'Jumlah Awal', 'required|numeric');
				$this->form_validation->set_rules('remains', 'Jumlah Kurang', 'required|numeric');
				$this->form_validation->set_rules('status', 'Status', 'required');
				if ($this->form_validation->run() == true) {
					$data_input = [
						'start_count' => $this->db->escape_str($this->input->post('start_count')),
						'remains' => $this->db->escape_str($this->input->post('remains')),
						'status' => $this->db->escape_str($this->input->post('status')),
						'api_order_id' => ($this->input->post('mass_status') == null ? $this->db->escape_str($this->input->post('api_order_id')) : $this->input->post('mass_status')),
						'updated_at' => date('Y-m-d H:i:s')
					];
					$update_target = $this->order_pulsa_model->update($data_input, ['id' => $i]);
					if ($update_target) {
						$this->session->set_flashdata('result', array('alert' => 'success', 'title' => 'Perubahan data berhasil!', 'msg' => 'Data <b>#' . $i . '</b> berhasil diperbaharui.'));
					} else {
						$this->session->set_flashdata('result', array('alert' => 'danger', 'title' => 'Gagal!', 'msg' => 'Kesalahan tidak terduga.'));
					}
				} else {
					$this->session->set_flashdata('result', array('alert' => 'danger', 'title' => 'Gagal!', 'msg' => '<br />' . validation_errors()));
				}
				exit(redirect(base_url('admin/' . $this->uri->segment(2))));
			}
			$this->load->view('admin/' . $this->uri->segment(2) . '/edit', ['target' => $target, 'status' => $status]);
		}
	}
	public function delete($i = '')
	{
		$target = $this->order_pulsa_model->get_by_id($i);
		if ($target == false) show_404();
		$delete_target = $this->order_pulsa_model->delete(['id' => $i]);
		if ($delete_target) {
			$this->session->set_flashdata('result', array('alert' => 'success', 'title' => 'Hapus data berhasil!', 'msg' => 'Data <b>#' . $i . '</b> berhasil dihapus.'));
		} else {
			$this->session->set_flashdata('result', array('alert' => 'danger', 'title' => 'Gagal!', 'msg' => 'Kesalahan tidak terduga.'));
		}
		redirect(base_url('admin/' . $this->uri->segment(2)));
	}
	public function order($i = '')
	{
		$target = $this->order_pulsa_model->get_rows(['status' => $i]);
		$this->load->view('admin/' . $this->uri->segment(2) . '/detail', ['target' => $target, 'user' => $this->user_model->get_by_id($target->user_id), 'service' => $this->service_model->get_by_id($target->service_id), 'api' => $this->api_model->get_by_id($target->api_id)]);
	}
	public function detail($i = '')
	{
		$target = $this->order_pulsa_model->get_by_id($i);
		if ($target == false) show_404();
		$this->load->view('admin/' . $this->uri->segment(2) . '/detail', ['target' => $target, 'user' => $this->user_model->get_by_id($target->user_id), 'service' => $this->service_model->get_by_id($target->service_id), 'api' => $this->api_model->get_by_id($target->api_id)]);
	}
	public function status($i = '', $status = '')
	{
		$target = $this->order_pulsa_model->get_by_id($i);
		$status = str_replace('%20', ' ', $status);
		if ($target == false) show_404();
		if (in_array($status, ['Pending', 'In progress', 'Processing', 'Success', 'Error', 'Partial',]) == false) show_404();
		$update_target = $this->order_pulsa_model->update(['status' => $status], ['id' => $i]);
		if ($update_target) {
			$this->session->set_flashdata('result', array('alert' => 'success', 'title' => 'Perubahan status berhasil!', 'msg' => 'Data <b>#' . $i . '</b> berhasil diubah.'));
		} else {
			$this->session->set_flashdata('result', array('alert' => 'danger', 'title' => 'Gagal!', 'msg' => 'Kesalahan tidak terduga.'));
		}
		redirect(base_url('admin/' . $this->uri->segment(2)));
	}
	public function filter()
	{
		$api = $this->api_model->get_by_id($this->input->post('api'));
		if ($api) {
			$this->session->set_userdata('filter_order_pulsa_api', $this->input->post('api'));
		} else {
			$this->session->unset_userdata('filter_order_pulsa_api');
		}
		$service = $this->service_model->get_by_id($this->input->post('service'));
		if ($service) {
			$this->session->set_userdata('filter_order_pulsa_service', $this->input->post('service'));
		} else {
			$this->session->unset_userdata('filter_order_pulsa_service');
		}
		$status = $this->order_pulsa_model->get_rows(['status' => $this->input->post('status')]);
		if ($status) {
			$this->session->set_userdata('filter_order_pulsa_status', $this->input->post('status'));
		} else {
			$this->session->unset_userdata('filter_order_pulsa_status');
		}
		$user = $this->user_model->get_by_id($this->input->post('user'));
		if ($user) {
			$this->session->set_userdata('filter_order_pulsa_user', $this->input->post('user'));
		} else {
			$this->session->unset_userdata('filter_order_pulsa_user');
		}
		redirect(base_url('admin/' . $this->uri->segment(2)));
	}
	public function monitoring()
	{
		if ($this->session->userdata('login') == false) exit(redirect(base_url()));
		// SETTINGS //
		$data_query = [
			'select' => 'order_pulsa_list.*, service.name AS service_name',
			'join' => [
				[
					'table' => 'service',
					'on' => 'service.id = order_pulsa_list.service_id',
					'param' => 'LEFT'
				]
			],
			'order_by' => 'order_pulsa_list.id DESC',
			'where' => [['order_pulsa_list.status' => 'Completed']],
			'limit' => '100',
		];
		$data_query['where'][] = ['user_id <>' => '1'];
		// END PAGINATION //
		$this->render_admin('admin/' . $this->uri->segment(2) . '/monitoring', ['table' => $this->order_pulsa_model->get_rows($data_query)]);
	}
}
