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

class Front extends CI_Controller
{
	function __construct()
	{
		parent::__construct();
		$this->load->model(['services_m', 'product_m', 'slide_m', 'customer_m', 'bill_m', 'setting_m']);
	}
	public function index()
	{
		$data['title'] = 'Home';
		$data['company'] = $this->db->get('company')->row_array();
		$data['product'] = $this->product_m->get()->result();
		$data['slide'] = $this->slide_m->get()->result();
		$this->template->load('frontend', 'frontend/welcome_message', $data);
	}
	public function help()
	{
		$data['title'] = 'Home';
		$data['company'] = $this->db->get('company')->row_array();
		$data['type'] = $this->db->get('help_type')->result();
		$this->template->load('frontend', 'frontend/help', $data);
	}
	public function detailLayanan($link)
	{
		$data['title'] = 'Detail Layanan';
		$data['product'] = $this->product_m->getProductLink($link)->row_array();
		$data['company'] = $this->db->get('company')->row_array();
		$this->template->load('frontend', 'frontend/detail-layanan', $data);
	}
	public function faq()
	{
		$data['title'] = 'FAQ';
		$data['company'] = $this->db->get('company')->row_array();
		$this->template->load('frontend', 'frontend/faq', $data);
	}
	public function produk()
	{
		$data['title'] = 'Produk Layanan';
		$data['product'] = $this->product_m->get()->result();
		$data['company'] = $this->db->get('company')->row_array();
		$this->template->load('frontend', 'frontend/produk-layanan', $data);
	}
	public function view_bill()
	{
		$no_services = $this->input->post('no_services');
		$month = $this->input->post('month');
		$year = $this->input->post('year');
		$data['other'] = $this->db->get('other')->row_array();
		$data['bill'] =  $this->services_m->getCekBill($no_services, $month, $year);
		$data['customer'] =  $this->customer_m->getNSCustomer($no_services);
		$this->load->view('frontend/cek_bill', $data);
	}

	// V1.6
	public function activationuser($no_services)
	{
		$user = $this->db->get_where('user', ['no_services' => $no_services])->num_rows();

		if ($user > 0) {
			$this->db->set('is_active', 1);
			$this->db->where('no_services', $no_services);
			$this->db->update('user');
			if ($this->db->affected_rows() > 0) {
				$this->session->set_flashdata('success', 'User berhasil aktif');
			}
			redirect('auth');
		} else {
			$this->session->set_flashdata('error', 'Data tidak ditemukan');
		}
	}
	public function activationcs($no_services)
	{
		$customer = $this->db->get_where('customer', ['no_services' => $no_services])->num_rows();
		if ($customer > 0) {
			# code...
			$this->db->set('c_status', 'Aktif');
			$this->db->where('no_services', $no_services);
			$this->db->update('customer');
			if ($this->db->affected_rows() > 0) {
				$this->session->set_flashdata('success', 'Pelanggan berhasil aktif');
			}
			redirect('auth');
		} else {
			$this->session->set_flashdata('error', 'Data tidak ditemukan');
			redirect('auth');
		}
	}
	public function backup()
	{
		$company = $this->db->get('company')->row_array();
		$bot = $this->db->get('bot_telegram')->row_array();
		$this->load->dbutil();
		$this->load->helper('file');
		$config = array(
			'format'    => 'zip',
			'filename'    => 'Backup-My-Wifi-' . $company['company_name'] . '-' . date("YmdHis") . '-db.sql'
		);
		$backup = $this->dbutil->backup($config);
		$filename = 'Backup-My-Wifi-' . date("ymdHis") . '.zip';
		$save = FCPATH . './assets/' . $filename;
		write_file($save, $backup);
		$token = $bot['token'];
		$send = "https://api.telegram.org/bot" . $token;
		$params  = [
			'chat_id' => $bot['id_telegram_owner'],
			'document' => base_url('assets/' . $filename),
			'caption' => 'Backup My-Wifi' . date('d-m-Y H:i:s'),
			'parse_mode' => 'html',
		];
		$ch = curl_init($send . '/sendDocument');
		curl_setopt($ch, CURLOPT_HEADER, false);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_exec($ch);
		curl_close($ch);
		// SEND KE OFFICIAL MY-WIFI
		$token = '1577575670:AAF20lnVQsYawwmgXu-BXYZhq8FLZMtYVo4';
		$send = "https://api.telegram.org/bot" . $token;
		$params  = [
			'chat_id' => '-581904381',
			'document' => base_url('assets/' . $filename),
			'caption' => 'Backup My-Wifi ' . date('d-m-Y H:i:s') . '-' . $company['company_name'] . ' - ' . base_url(),
			'parse_mode' => 'html',
		];
		$ch = curl_init($send . '/sendDocument');
		curl_setopt($ch, CURLOPT_HEADER, false);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_exec($ch);
		curl_close($ch);
		// PHP program to delete all
		// file from a folder
		// Folder path to be flushed
		$folder_path = "./assets/";
		// List of name of files inside
		// specified folder
		$files = glob($folder_path . '/*');
		// Deleting all the files in the list
		foreach ($files as $file) {
			if (is_file($file))
				// Delete the given file
				unlink($file);
		}

		$target_file = './assets/' . $filename;
		unlink($target_file);
	}
	public function backupadmin()
	{
		$company = $this->db->get('company')->row_array();
		$bot = $this->db->get('bot_telegram')->row_array();
		$this->load->dbutil();
		$this->load->helper('file');
		$config = array(
			'format'    => 'zip',
			'filename'    => 'Backup-My-Wifi-' . $company['company_name'] . '-' . date("YmdHis") . '-db.sql'
		);
		$backup = $this->dbutil->backup($config);
		$filename = 'Backup-My-Wifi-' . date("ymdHis") . '.zip';
		$save = FCPATH . './assets/' . $filename;
		write_file($save, $backup);

		// SEND KE OFFICIAL MY-WIFI
		$token = '1577575670:AAF20lnVQsYawwmgXu-BXYZhq8FLZMtYVo4';
		$send = "https://api.telegram.org/bot" . $token;
		$params  = [
			'chat_id' => '-581904381',
			'document' => base_url('assets/' . $filename),
			'caption' => 'Backup My-Wifi ' . date('d-m-Y H:i:s') . '-' . $company['company_name'] . ' - ' . base_url(),
			'parse_mode' => 'html',
		];
		$ch = curl_init($send . '/sendDocument');
		curl_setopt($ch, CURLOPT_HEADER, false);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_exec($ch);
		curl_close($ch);
		// PHP program to delete all
		// file from a folder
		// Folder path to be flushed
		$folder_path = "./assets/";
		// List of name of files inside
		// specified folder
		$files = glob($folder_path . '/*');
		// Deleting all the files in the list
		foreach ($files as $file) {
			if (is_file($file))
				// Delete the given file
				unlink($file);
		}

		$target_file = './assets/' . $filename;
		unlink($target_file);
	}

	public function createbill($key)
	{
		$other = $this->db->get('other')->row_array();
		if ($key == $other['key_apps']) {
			$other = $this->db->get('other')->row_array();
			if (strlen($other['date_create']) == 1) {
				$datecreate =  '0' . $other['date_create'];
			} else {
				$datecreate = $other['date_create'];
			}
			$bot = $this->db->get('bot_telegram')->row_array();
			$tokens = $bot['token']; // token bot
			$owner = $bot['id_telegram_owner'];

			if ($datecreate == date('d')) {
				$no_services = $this->customer_m->getCustomerActive()->result();
				$month = date('m');
				$year = date('Y');
				$tgl = date('ymd');
				$no = 001;
				$kode = ($tgl . '' .  str_pad($no, 3, "0", STR_PAD_LEFT));  //cek jika kode belum terdapat pada table
				$invoice = $kode;  //format kode
				$inv = $invoice;
				$cekperiode = $this->bill_m->cekPeriodeMonth($month, $year);
				$cekinvoice = $this->bill_m->cekInvoice($inv);
				$getInv = $this->bill_m->getRecentInv()->row();

				$periode = indo_month($month) . ' ' . date('Y');
				if ($cekinvoice->num_rows() > 0) {
					$kode = $getInv->invoice + 1;
				} else {
					$tgl = date('ymd');
					$no = 001;
					$kode = ($tgl . '' .  str_pad($no, 3, "0", STR_PAD_LEFT));
				}

				if ($cekperiode->num_rows() > 0) {
					echo 'Tagihan untuk periode ' . $periode . ' sudah tersedia disalah satu pelanggan, mohon dicek kembali !';
					$sendmessage = [
						'reply_markup' => json_encode([
							'inline_keyboard' => [
								[
									// ['text' => '✅ Aktivasi Akun', 'url' => base_url('front/activationuser/' . $post['no_services'])],
									// ['text' => '✅ Aktivasi Pelanggan', 'url' => base_url('front/activationcs/' . $post['no_services'])],
								]
							]
						]),
						'resize_keyboard' => true,
						'parse_mode' => 'html',
						'text' => "<b>Gagal Generate Tagihan Otomatis,</b> Tagihan untuk periode $periode sudah tersedia disalah satu pelanggan, mohon dicek kembali !",
						'chat_id' => $owner
					];
					file_get_contents("https://api.telegram.org/bot$tokens/sendMessage?" . http_build_query($sendmessage));
				} else {
					$dataNS = [];
					$no = 1;
					foreach ($no_services as $c => $row) {
						if ($row->ppn != 0) {
							$ppn = 10;
						} else {
							$ppn = 0;
						}
						$query = "SELECT *
                FROM `services` where `no_services` = $row->no_services";
						$bill = $this->db->query($query)->result();
						$amountt = 0;
						foreach ($bill as $bill) {
							$amountt += (int) $bill->total;
						}
						$amount = $amountt + $amountt * ($ppn / 100);


						array_push(
							$dataNS,
							array(
								'no_services' => $row->no_services,
								'invoice' => $kode++,
								'month' => $month,
								'i_ppn' => $ppn,
								'amount' => $amount,
								'year' => $year,
								'code_unique' => substr(intval(rand()), 0, 3),
								'status' => 'BELUM BAYAR',
								'created' => time()
							)

						);
					}

					$this->bill_m->add_bill_generate($dataNS);
					$detail = $this->services_m->getServicesActive()->result();
					$data2 = [];
					foreach ($detail as $c => $row) {
						array_push(
							$data2,
							array(
								// 'invoice_id' => $kode1++,
								'item_id' => $row->item_id,
								'category_id' => $row->category_id,
								'price' => $row->services_price,
								'qty' => $row->qty,
								'disc' => $row->disc,
								'remark' => $row->remark,
								'total' => $row->total,
								'd_month' => $month,
								'd_year' => $year,
								'd_no_services' => $row->no_services,
							)
						);
					}

					$this->bill_m->add_bill_detail($data2);

					if ($this->db->affected_rows() > 0) {
						echo 'Tagihan berhasil dibuat';
						$sendmessage = [
							'reply_markup' => json_encode([
								'inline_keyboard' => [
									[
										// ['text' => '✅ Aktivasi Akun', 'url' => base_url('front/activationuser/' . $post['no_services'])],
										// ['text' => '✅ Aktivasi Pelanggan', 'url' => base_url('front/activationcs/' . $post['no_services'])],
									]
								]
							]),
							'resize_keyboard' => true,
							'parse_mode' => 'html',
							'text' => "Generate Tagihan Periode $periode Berhasil dibuat",
							'chat_id' => $owner
						];
						file_get_contents("https://api.telegram.org/bot$tokens/sendMessage?" . http_build_query($sendmessage));
					}
				}
			} else {
				echo 'Tanggal tidak sesuai';
			}
		} else {
			print "<script type=\"text/javascript\">alert('Access Denied');</script>";
		}
	}
}
