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

class Pmg extends CI_Controller {

	public function __construct()
	{
		parent::__construct();
		$this->load->library('encrypt');
		$this->load->helper('az_auth');
		$this->load->helper('az_config');
		$this->load->helper('az_crud');
		$this->load->helper('az_core');
		$this->load->helper('az_surya');
		$this->load->helper('az_telegram');
		// webhook dipanggil oleh server Telegram (tanpa login) → lewati cek login
		$method = $this->router->fetch_method();
		if ($method != 'webhook') { az_check_auth('dashboard'); }
	}

	private function _guard_admin()
	{
		if ($this->session->userdata('role_name') != 'administrator') { show_404(); }
	}

	private function _guard_barber()
	{
		$idrole = $this->session->userdata('idrole');
		$this->db->where('idrole', $idrole);
		$this->db->where('menu_name', 'history_bill_production');
		$this->db->where('access', 1);
		$this->db->where('status', 1);
		if ($this->db->count_all_results('user_role') <= 0) { show_404(); }
	}

	// ==========================================================
	// TAHAP 2: SETTING TELEGRAM
	// ==========================================================
	public function telegram_setting()
	{
		$this->_guard_admin();
		$this->load->library('AZApp');
		$app = $this->azapp;

		$set = az_tg_get_setting();

		$data = array();
		$data['bot_token']   = (string)$set->bot_token;
		$data['chat_id']     = (string)$set->chat_id;
		$data['webhook_url'] = (string)$set->webhook_url;
		$data['save_url'] = app_url() . 'pmg/telegram_save';
		$data['test_url'] = app_url() . 'pmg/telegram_test';
		$data['back_url'] = app_url();

		$view = $this->load->view('pmg/v_telegram_setting', $data, true);
		$app->add_content($view);

		$data_header = array();
		$data_header['title'] = 'Setting Telegram PMG';
		$data_header['breadcrumb'] = array('dashboard');
		$app->set_data_header($data_header);
		echo $app->render();
	}

	public function telegram_save()
	{
		$this->_guard_admin();
		$token = trim((string)$this->input->post('bot_token'));
		$chat  = trim((string)$this->input->post('chat_id'));

		$upd = array(
			'bot_token' => $token,
			'chat_id'   => $chat,
			'updated'   => date('Y-m-d H:i:s'),
			'updatedby' => $this->session->userdata('username'),
		);

		$this->db->where('id', 1);
		if ($this->db->count_all_results('telegram_setting') > 0)
		{
			$this->db->where('id', 1);
			$this->db->update('telegram_setting', $upd);
		}
		else
		{
			$upd['id'] = 1;
			$this->db->insert('telegram_setting', $upd);
		}

		// Daftarkan webhook supaya tombol di Telegram berfungsi
		$wh_msg = '';
		if (strlen($token) > 0)
		{
			$secret = md5($token . '::pmg::');
			$webhook_url = app_url() . 'pmg/webhook/' . $secret;
			$r = az_tg_api('setWebhook', array('url' => $webhook_url));
			if ($r && isset($r->ok) && $r->ok)
			{
				$this->db->where('id', 1);
				$this->db->update('telegram_setting', array('webhook_url' => $webhook_url));
				$wh_msg = ' Webhook AKTIF — tombol Setuju/Tolak di Telegram sudah bisa dipakai.';
			}
			else
			{
				$this->db->where('id', 1);
				$this->db->update('telegram_setting', array('webhook_url' => ''));
				$desc = isset($r->description) ? $r->description : 'penyebab tidak diketahui';
				$wh_msg = ' PERHATIAN: webhook gagal (' . $desc . '). Persetujuan tetap bisa lewat menu PMG admin.';
			}
		}

		$this->session->set_flashdata('tg_msg', 'Setting Telegram tersimpan.' . $wh_msg);
		redirect('pmg/telegram_setting');
	}

	public function telegram_test()
	{
		$this->_guard_admin();
		$set = az_tg_get_setting();
		if (strlen((string)$set->bot_token) == 0 || strlen((string)$set->chat_id) == 0)
		{
			$this->session->set_flashdata('tg_err', 'Isi dulu token & chat id, lalu simpan.');
			redirect('pmg/telegram_setting');
			return;
		}

		$r = az_tg_send("✅ TES KONEKSI PMG BERHASIL\nWaktu: " . date('d/m/Y H:i'));
		if ($r && isset($r->ok) && $r->ok)
		{
			$this->session->set_flashdata('tg_msg', '✅ Berhasil! Pesan tes sudah masuk ke Telegram Anda.');
		}
		else
		{
			$desc = isset($r->description) ? $r->description : 'Gagal menghubungi Telegram. Periksa token / koneksi internet server.';
			$this->session->set_flashdata('tg_err', '❌ ' . $desc);
		}
		redirect('pmg/telegram_setting');
	}

	// ==========================================================
	// TAHAP 3: PENGAJUAN PMG (produksi)
	// ==========================================================
	private function _pmg_items($id)
	{
		$this->db->select('tr.idtransaction, pr.product_name');
		$this->db->from('transaction tr');
		$this->db->join('item it', 'it.iditem = tr.iditem', 'left');
		$this->db->join('product pr', 'pr.idproduct = it.idproduct', 'left');
		$this->db->where('tr.idtransaction_group', $id);
		$this->db->where('tr.status', 1);
		$this->db->order_by('tr.idtransaction ASC');
		return $this->db->get()->result();
	}

	private function _pmg_blocked($id)
	{
		$this->db->select('pd.idtransaction');
		$this->db->from('pmg_detail pd');
		$this->db->join('pmg p', 'p.idpmg = pd.idpmg');
		$this->db->where('p.idtransaction_group', $id);
		$this->db->group_start();
			$this->db->where('p.status', 0);
			$this->db->or_group_start();
				$this->db->where('p.status', 1);
				$this->db->where('p.printed', 0);
			$this->db->group_end();
		$this->db->group_end();
		$map = array();
		foreach ($this->db->get()->result() as $r) { $map[(int)$r->idtransaction] = 1; }
		return $map;
	}

	public function apply_data()
	{
		$this->_guard_barber();
		$id = (int)$this->input->post('id');
		if ($id <= 0) { echo json_encode(array('err_code' => 1, 'err_message' => 'ID tidak valid')); return; }

		$this->db->select('tg.code, c.customer_name');
		$this->db->from('transaction_group tg');
		$this->db->join('customer c', 'c.idcustomer = tg.idcustomer', 'left');
		$this->db->where('tg.idtransaction_group', $id);
		$tg = $this->db->get()->row();
		if (!$tg) { echo json_encode(array('err_code' => 1, 'err_message' => 'Bill tidak ditemukan')); return; }

		$rows = $this->_pmg_items($id);
		$blocked = $this->_pmg_blocked($id);
		$items = array(); $n = 0; $tot = count($rows);
		foreach ($rows as $r)
		{
			$n++;
			$items[] = array(
				'idtransaction' => (int)$r->idtransaction,
				'n' => $n, 'tot' => $tot,
				'product_name' => (string)$r->product_name,
				'blocked' => isset($blocked[(int)$r->idtransaction]) ? 1 : 0,
			);
		}
		echo json_encode(array('err_code' => 0, 'code' => $tg->code, 'customer' => $tg->customer_name, 'items' => $items));
	}

	public function apply_save()
	{
		$this->_guard_barber();
		$id = (int)$this->input->post('id');
		$reason = (string)$this->input->post('reason');
		$tids = array_filter(explode(',', (string)$this->input->post('tids')));

		if ($id <= 0) { echo json_encode(array('err_code' => 1, 'err_message' => 'Bill tidak valid')); return; }
		if (!in_array($reason, array('HILANG', 'TIDAK_TAMPAK'))) { echo json_encode(array('err_code' => 1, 'err_message' => 'Pilih alasan terlebih dahulu.')); return; }
		if (count($tids) == 0) { echo json_encode(array('err_code' => 1, 'err_message' => 'Centang minimal 1 num.')); return; }

		$photos = isset($_FILES['photos']) ? $_FILES['photos'] : null;
		$n_photo = 0;
		if ($photos && is_array($photos['name']))
		{
			foreach ($photos['name'] as $nm) { if (strlen((string)$nm) > 0) $n_photo++; }
		}
		if ($n_photo > 3) { echo json_encode(array('err_code' => 1, 'err_message' => 'Foto maksimal 3.')); return; }

		$blocked = $this->_pmg_blocked($id);
		foreach ($tids as $t)
		{
			if (isset($blocked[(int)$t])) { echo json_encode(array('err_code' => 1, 'err_message' => 'Ada num yang sudah punya PMG aktif. Muat ulang halaman.')); return; }
		}

		$this->db->where('idtransaction_group', $id);
		$tg = $this->db->get('transaction_group')->row();
		if (!$tg) { echo json_encode(array('err_code' => 1, 'err_message' => 'Bill tidak ditemukan')); return; }

		$rows = $this->_pmg_items($id);
		$nummap = array(); $n = 0; $tot = count($rows);
		foreach ($rows as $r) { $n++; $nummap[(int)$r->idtransaction] = array('n' => $n, 'tot' => $tot); }

		$this->db->insert('pmg', array(
			'pmg_code' => '',
			'idtransaction_group' => $id,
			'idoutlet' => $tg->idoutlet,
			'reason' => $reason,
			'status' => 0,
			'printed' => 0,
			'idproduction' => $this->session->userdata('iduser'),
			'created' => date('Y-m-d H:i:s'),
			'createdby' => $this->session->userdata('username'),
		));
		$idpmg = $this->db->insert_id();
		$pmg_code = 'PRC' . str_pad($idpmg, 2, '0', STR_PAD_LEFT);
		$this->db->where('idpmg', $idpmg);
		$this->db->update('pmg', array('pmg_code' => $pmg_code));

		$seq = 0; $labels = array();
		foreach ($tids as $t)
		{
			$tid = (int)$t;
			if (!isset($nummap[$tid])) continue;
			$seq++;
			$labels[] = $nummap[$tid]['n'] . '/' . $nummap[$tid]['tot'];
			$this->db->insert('pmg_detail', array(
				'idpmg' => $idpmg,
				'idtransaction' => $tid,
				'num' => $nummap[$tid]['n'],
				'num_total' => $nummap[$tid]['tot'],
				'marker_seq' => $seq,
			));
		}

		if ($n_photo > 0)
		{
			$dir = APPPATH . 'assets/pmg/';
			if (!is_dir($dir)) @mkdir($dir, 0777, true);
			$this->load->library('upload');
			for ($i = 0; $i < count($photos['name']); $i++)
			{
				if (strlen((string)$photos['name'][$i]) == 0) continue;
				$_FILES['pmg_one'] = array(
					'name' => $photos['name'][$i],
					'type' => $photos['type'][$i],
					'tmp_name' => $photos['tmp_name'][$i],
					'error' => $photos['error'][$i],
					'size' => $photos['size'][$i],
				);
				$this->upload->initialize(array(
					'upload_path' => $dir,
					'allowed_types' => 'jpg|png|jpeg',
					'max_size' => '3000',
					'encrypt_name' => true,
				));
				if ($this->upload->do_upload('pmg_one'))
				{
					$this->db->insert('pmg_photo', array(
						'idpmg' => $idpmg,
						'photo' => $this->upload->data('file_name'),
						'created' => date('Y-m-d H:i:s'),
					));
				}
			}
		}

		// Notifikasi Telegram + TOMBOL Setuju/Tolak
		$reason_label = ($reason == 'HILANG') ? 'Marker lepas saat pencucian & hilang' : 'Tulisan marker tidak tampak 95%';
		$msg = "🟠 PENGAJUAN MARKER PENGGANTI (PMG)\n"
			. "🧾 Bill: " . $tg->code . "\n"
			. "👤 Diajukan: " . $this->session->userdata('name') . " (" . $this->session->userdata('username') . ")\n"
			. "❗ Alasan: " . $reason_label . "\n"
			. "🔢 Num: " . implode(', ', $labels) . "\n"
			. "📷 Foto: " . $n_photo . " (lihat di menu PMG admin)\n"
			. "🔑 Kode: " . $pmg_code . "\n"
			. "⏰ " . date('d/m/Y H:i');
		$kb = array(array(
			array('text' => '✅ SETUJUI ' . $pmg_code, 'callback_data' => 'pmga_' . $idpmg),
			array('text' => '❌ TOLAK', 'callback_data' => 'pmgr_' . $idpmg),
		));
		az_tg_send($msg, $kb);

		echo json_encode(array('err_code' => 0, 'pmg_code' => $pmg_code));
	}

	// ==========================================================
	// TAHAP 4: PERSETUJUAN (admin)
	// ==========================================================
	public function admin_list()
	{
		$this->_guard_admin();
		$this->load->library('AZApp');
		$app = $this->azapp;

		$f_status = $this->input->get('status');
		if ($f_status === null || $f_status === '') $f_status = '0';

		$this->db->select('pmg.*, tg.code AS bill_code, c.customer_name, o.outlet_name');
		$this->db->from('pmg');
		$this->db->join('transaction_group tg', 'tg.idtransaction_group = pmg.idtransaction_group', 'left');
		$this->db->join('customer c', 'c.idcustomer = tg.idcustomer', 'left');
		$this->db->join('outlet o', 'o.idoutlet = pmg.idoutlet', 'left');
		if ($f_status !== 'all') $this->db->where('pmg.status', (int)$f_status);
		$this->db->order_by('pmg.idpmg', 'DESC');
		$rows = $this->db->get()->result();

		foreach ($rows as $r)
		{
			$this->db->select('num, num_total')->where('idpmg', $r->idpmg)->order_by('marker_seq ASC');
			$ds = $this->db->get('pmg_detail')->result();
			$labs = array();
			foreach ($ds as $d) { $labs[] = $d->num . '/' . $d->num_total; }
			$r->nums_label = implode(', ', $labs);
			$this->db->where('idpmg', $r->idpmg);
			$r->photos = $this->db->get('pmg_photo')->result();
		}

		$data = array();
		$data['rows'] = $rows;
		$data['base_url'] = app_url() . 'pmg/admin_list?';
		$data['approve_url'] = app_url() . 'pmg/approve';
		$data['reject_url'] = app_url() . 'pmg/reject';
		$data['photo_base'] = base_url() . AZAPP . 'assets/pmg/';
		$data['print_base'] = app_url() . 'pmg/print_page/';

		$view = $this->load->view('pmg/v_admin_list', $data, true);
		$app->add_content($view);

		$data_header = array();
		$data_header['title'] = 'PMG — Persetujuan Marker Pengganti';
		$data_header['breadcrumb'] = array('dashboard');
		$app->set_data_header($data_header);
		echo $app->render();
	}

	private function _decide($id, $status)
	{
		if ($id <= 0) return;
		$this->db->where('idpmg', $id);
		$p = $this->db->get('pmg')->row();
		if (!$p || (int)$p->status !== 0) return; // cegah dobel keputusan
		$this->db->where('idpmg', $id);
		$this->db->update('pmg', array(
			'status' => $status,
			'approved_by' => $this->session->userdata('iduser'),
			'approved_at' => date('Y-m-d H:i:s'),
			'approved_via' => 'form',
		));
	}

	public function approve()
	{
		$this->_guard_admin();
		$this->_decide((int)$this->input->post('id'), 1);
		redirect('pmg/admin_list');
	}

	public function reject()
	{
		$this->_guard_admin();
		$this->_decide((int)$this->input->post('id'), 2);
		redirect('pmg/admin_list');
	}

	// - Webhook: dipanggil Telegram saat tombol di pesan diklik (tanpa login) -
	public function webhook($hash = '')
	{
		$set = az_tg_get_setting();
		$expect = md5((string)$set->bot_token . '::pmg::');
		if (strlen((string)$set->bot_token) == 0 || $hash !== $expect)
		{
			echo 'forbidden'; return;
		}

		$up = json_decode(file_get_contents('php://input'));
		if (!$up || !isset($up->callback_query)) { echo json_encode(array('ok' => true)); return; }

		$cb = $up->callback_query;
		$data = isset($cb->data) ? $cb->data : '';
		$idpmg = 0; $act = '';
		if (preg_match('/^pmga_(\d+)$/', $data, $m)) { $act = 'approve'; $idpmg = (int)$m[1]; }
		elseif (preg_match('/^pmgr_(\d+)$/', $data, $m)) { $act = 'reject'; $idpmg = (int)$m[1]; }

		$chat_id = isset($cb->message->chat->id) ? $cb->message->chat->id : null;
		$message_id = isset($cb->message->message_id) ? $cb->message->message_id : null;
		$old_text = isset($cb->message->text) ? $cb->message->text : '';

		$result_text = '';
		if ($idpmg > 0 && $act != '')
		{
			$this->db->where('idpmg', $idpmg);
			$p = $this->db->get('pmg')->row();
			if (!$p)
			{
				$result_text = 'Data PMG tidak ditemukan.';
			}
			else if ((int)$p->status !== 0)
			{
				$result_text = 'PMG ' . $p->pmg_code . ' sudah diproses sebelumnya.';
			}
			else
			{
				$new_status = ($act == 'approve') ? 1 : 2;
				$this->db->where('idpmg', $idpmg);
				$this->db->update('pmg', array(
					'status' => $new_status,
					'approved_by' => null,
					'approved_at' => date('Y-m-d H:i:s'),
					'approved_via' => 'telegram',
				));
				$result_text = 'PMG ' . $p->pmg_code . ' → ' . ($act == 'approve' ? '✅ DISETUJUI' : '❌ DITOLAK') . ' (via Telegram) · ' . date('d/m/Y H:i');
			}
		}

		az_tg_api('answerCallbackQuery', array('callback_query_id' => $cb->id, 'text' => $result_text));
		if ($chat_id && $message_id)
		{
			az_tg_api('editMessageText', array(
				'chat_id' => $chat_id,
				'message_id' => $message_id,
				'text' => $old_text . "\n\n" . $result_text,
			));
		}
		echo json_encode(array('ok' => true));
	}
	
	// ==========================================================
	// TAHAP 5: CETAK PMG
	// ==========================================================

	// - AJAX: daftar PMG yang boleh dicetak (disetujui & belum dicetak) -
	public function printable_list()
	{
		$this->_guard_barber();
		$this->db->select('idpmg, idtransaction_group');
		$this->db->where('status', 1);
		$this->db->where('printed', 0);
		$rows = $this->db->get('pmg')->result();
		echo json_encode(array('err_code' => 0, 'rows' => $rows));
	}

	// - Halaman cetak 5x3 cm. Membuka halaman = mengunci (menandai DICETAK). -
	public function print_page($idpmg = 0)
	{
		$this->_guard_barber();
		$idpmg = (int)$idpmg;
		$this->db->where('idpmg', $idpmg);
		$p = $this->db->get('pmg')->row();
		if (!$p) { show_404(); }

		$data = array('msg' => '', 'markers' => array());
		if ((int)$p->status !== 1)
		{
			$data['msg'] = 'PMG ini belum disetujui.';
			$this->load->view('pmg/v_print_pmg', $data); return;
		}
		if ((int)$p->printed === 1)
		{
			$data['msg'] = 'PMG ' . $p->pmg_code . ' SUDAH DICETAK sebelumnya. Untuk cetak lagi, buat pengajuan baru.';
			$this->load->view('pmg/v_print_pmg', $data); return;
		}

		// KUNCI: tandai dicetak sekarang + buat kode marker (tanggal = tanggal cetak)
		$now = date('Y-m-d H:i:s');
		$tgl_code = date('dmY');
		$this->db->where('idpmg', $idpmg);
		$this->db->update('pmg', array(
			'printed' => 1,
			'printed_by' => $this->session->userdata('iduser'),
			'printed_at' => $now,
		));

		$this->db->where('idpmg', $idpmg);
		$this->db->order_by('marker_seq ASC');
		$details = $this->db->get('pmg_detail')->result();
		foreach ($details as $d)
		{
			$code = $p->pmg_code . '-' . str_pad($d->marker_seq, 2, '0', STR_PAD_LEFT) . '-' . $tgl_code;
			$this->db->where('idpmg_detail', $d->idpmg_detail);
			$this->db->update('pmg_detail', array('pmg_marker_code' => $code));
			$d->pmg_marker_code = $code;
		}

		// data bill
		$this->db->select('tg.code, c.customer_name, o.outlet_name, tg.duedate');
		$this->db->from('transaction_group tg');
		$this->db->join('customer c', 'c.idcustomer = tg.idcustomer', 'left');
		$this->db->join('outlet o', 'o.idoutlet = tg.idoutlet', 'left');
		$this->db->where('tg.idtransaction_group', $p->idtransaction_group);
		$bill = $this->db->get()->row();

		$markers = array();
		foreach ($details as $d)
		{
			$this->db->select('tr.idtransaction, pr.product_name, tr.trx_note, it.idcolour, it.idhue, tr.idspot');
			$this->db->from('transaction tr');
			$this->db->join('item it', 'it.iditem = tr.iditem', 'left');
			$this->db->join('product pr', 'pr.idproduct = it.idproduct', 'left');
			$this->db->where('tr.idtransaction', $d->idtransaction);
			$r = $this->db->get()->row();

			$notes = array();
			if ($r)
			{
				$col  = function_exists('az_convert_colour') ? az_convert_colour($r->idcolour) : '';
				$hue  = function_exists('az_convert_hue') ? az_convert_hue($r->idhue) : '';
				$spot = function_exists('az_convert_spot') ? az_convert_spot($r->idspot) : '';
				if (strlen((string)$col) > 0) $notes[] = $col;
				if (strlen((string)$hue) > 0) $notes[] = $hue;
				if (strlen((string)$spot) > 0) $notes[] = $spot;
				if (strlen((string)$r->trx_note) > 0) $notes[] = $r->trx_note;
			}

			$markers[] = array(
				'customer' => $bill ? (string)$bill->customer_name : '',
				'code5' => $bill ? substr((string)$bill->code, -5) : '',
				'outlet' => $bill ? strtoupper((string)$bill->outlet_name) : '',
				'num' => (int)$d->num,
				'tot' => (int)$d->num_total,
				'product' => $r ? (string)$r->product_name : '',
				'duedate' => ($bill && strlen((string)$bill->duedate) > 0 && $bill->duedate != '0000-00-00 00:00:00') ? date('d M H:i', strtotime($bill->duedate)) : '',
				'notes' => implode(', ', $notes),
				'pmg_marker_code' => (string)$d->pmg_marker_code,
			);
		}

		$data['markers'] = $markers;
		$this->load->view('pmg/v_print_pmg', $data);
	}	
	
		// ==========================================================
	// TAHAP 6: LAPORAN PMG (KHUSUS ADMIN)
	// ==========================================================
	public function report()
	{
		$this->_guard_admin();
		$date_1 = $this->input->get('date_1');
		$date_2 = $this->input->get('date_2');
		$idoutlet = trim((string)$this->input->get('idoutlet'));
		$q1 = (strlen($date_1) > 0) ? date('Y-m-d', strtotime($date_1)) : date('Y-m-d', strtotime('-30 day'));
		$q2 = (strlen($date_2) > 0) ? date('Y-m-d', strtotime($date_2)) : date('Y-m-d');

		$this->db->select('pmg.*, tg.code AS bill_code, c.customer_name, o.outlet_name');
		$this->db->from('pmg');
		$this->db->join('transaction_group tg', 'tg.idtransaction_group = pmg.idtransaction_group', 'left');
		$this->db->join('customer c', 'c.idcustomer = tg.idcustomer', 'left');
		$this->db->join('outlet o', 'o.idoutlet = pmg.idoutlet', 'left');
		$this->db->where('DATE(pmg.created) >=', $q1);
		$this->db->where('DATE(pmg.created) <=', $q2);
		if (strlen($idoutlet) > 0) { $this->db->where('pmg.idoutlet', $idoutlet); }
		$this->db->order_by('pmg.idpmg DESC');
		$rows = $this->db->get()->result();

		foreach ($rows as $r)
		{
			$this->db->where('idpmg', $r->idpmg);
			$this->db->order_by('marker_seq ASC');
			$r->details = $this->db->get('pmg_detail')->result();
			$this->db->where('idpmg', $r->idpmg);
			$r->photos = $this->db->get('pmg_photo')->result();
		}

		$g = array('total' => count($rows), 'menunggu' => 0, 'disetujui' => 0, 'ditolak' => 0, 'dicetak' => 0, 'num' => 0, 'hilang' => 0, 'tidak_tampak' => 0);
		$by_out = array();
		foreach ($rows as $r)
		{
			if ((int)$r->status === 0) $g['menunggu']++;
			elseif ((int)$r->status === 1) $g['disetujui']++;
			else $g['ditolak']++;
			if ((int)$r->printed === 1) $g['dicetak']++;
			if ($r->reason == 'HILANG') $g['hilang']++; else $g['tidak_tampak']++;
			$nnum = count($r->details);
			$g['num'] += $nnum;
			$on = strlen((string)$r->outlet_name) ? $r->outlet_name : '(tanpa outlet)';
			if (!isset($by_out[$on])) $by_out[$on] = array('n' => 0, 'num' => 0);
			$by_out[$on]['n']++; $by_out[$on]['num'] += $nnum;
		}
		arsort($by_out);

		$this->load->view('pmg/v_report', array(
			'rows' => $rows, 'g' => $g, 'by_out' => $by_out,
			'q1' => $q1, 'q2' => $q2, 'idoutlet' => $idoutlet,
			'outlets' => $this->db->where('status', 1)->order_by('outlet_name')->get('outlet')->result(),
			'photo_base' => base_url() . AZAPP . 'assets/pmg/',
			'tanggal_cetak' => date('d F Y'),
		));
	}
	
}