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

class Pwa extends CI_Controller {
	public function __construct(){
		parent::__construct();
		check_login_user();
		is_valid();
	}

	public function index()
	{
		$data = array();
		$data['page_title'] = "PWA";
		$data['page'] = "PWA";
		$data['settings'] = $this->admin_m->get_setting();
		$data['main_content'] = $this->load->view('admin/dashboard/admin_activities/pwa', $data, TRUE);
		$this->load->view('admin/index',$data);

		$file = base_url('uploads/pwa/logo.png');
		$filePath = 'assets/images/logo.jpg';
		/* Store the path of destination file */
		$destinationFilePath = 'uploads/pwa/logo.png';
		if (!file_exists($file)) {
			copy($filePath, $destinationFilePath);
		}
	}

	public function add_pwa(){
		is_test();
		if(is_allow() !=1):
			exit();
		endif;
    	$id = $this->input->post('id');
		$this->form_validation->set_rules('title', 'Title', 'trim|xss_clean|required');
		$this->form_validation->set_rules('theme_color', 'Theme Color', 'trim|xss_clean');
		$this->form_validation->set_rules('background_color', 'background Color', 'trim|xss_clean');
		if ($this->form_validation->run() == FALSE) {
			$this->session->set_flashdata('error', validation_errors());
			redirect(base_url('admin/pwa/'));
			}else{	
				$logo = $this->upload_logo();
				$is_pwa_active = $this->input->post('is_pwa_active');
				$old_img = $this->input->post('old_img');
				$pwaData = array(
					'title' => $this->input->post('title',TRUE),
					'theme_color' => substr($this->input->post('theme_color',TRUE),1),
					'background_color' => substr($this->input->post('background_color',TRUE),1),
					'is_pwa_active' => isset($is_pwa_active)?$is_pwa_active :0,
					'logo' => !empty($logo)?$logo:$old_img,
				);
				$data = array(
					'pwa_config' => json_encode($pwaData),
				);


				if($id==0){
					$insert = $this->admin_m->insert($data,'setting');
				}else{
					$insert = $this->admin_m->update($data,$id,'setting');
				}

				if($insert){
					$this->session->set_flashdata('success', !empty(lang('success_text'))?lang('success_text'):'Save Change Successful');
					redirect(base_url('admin/pwa'));
				}else{
					$this->session->set_flashdata('error', !empty(lang('error_text'))?lang('error_text'):'Somethings Were Wrong!!');
					redirect(base_url('admin/pwa'));
				}	
		}
	}


	public function upload_logo()
	{
		
		if(!empty($_FILES['images']['name'])){
			$directory = 'uploads/pwa/';
			$dir = $directory;
			$name = $_FILES['images']['name'];
			list($txt, $ext) = explode(".", $name);
			$image_name = md5(time()).".".$ext;
			$tmp = $_FILES['images']['tmp_name'];
			if(move_uploaded_file($tmp, $dir.$image_name)){
				$url = $dir.$image_name;
				$data = array('logo' => $url);
				return $url;
			}else{
				echo "image uploading failed";
			}
		}

	}

}