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

class Upload_m extends CI_Model
{
	public function __construct()
	{
		// parent::__construct();
		$this->db->query("SET sql_mode = ''");
	}

	public function upload($size = '250')
	{
		ini_set('memory_limit', '-1');
		$data = array();
		if (!empty($_FILES['file']['name'])) {
			$filesCount = count($_FILES['file']['name']);
			for ($i = 0; $i < $filesCount; $i++) {
				$_FILES['uploadFile']['name'] = str_replace(",", "_", $_FILES['file']['name'][$i]);
				$_FILES['uploadFile']['type'] = $_FILES['file']['type'][$i];
				$_FILES['uploadFile']['tmp_name'] = $_FILES['file']['tmp_name'][$i];
				$_FILES['uploadFile']['error'] = $_FILES['file']['error'][$i];
				$_FILES['uploadFile']['size'] = $_FILES['file']['size'][$i];

				//Directory where files will be uploaded
				$uploadPath = 'uploads/';


				$config['upload_path'] = $uploadPath . 'big/';
				// Specifying the file formats that are supported.
				$config['allowed_types'] = '*';
				$config['overwrite'] = TRUE;
				$config['encrypt_name'] = TRUE;
				$this->load->library('upload', $config);
				$this->upload->initialize($config);
				// resize library
				$this->load->library('image_lib');

				if ($this->upload->do_upload('uploadFile')) {
					$fileData = $this->upload->data();
					$uploadData[$i]['file_name'] = $fileData['file_name'];
					// resize
					$config = array(
						'source_image'      => $fileData['full_path'],
						'new_image'         => $uploadPath . '/thumb', //path to
						'maintain_ratio'    => true,
						'width'             => $size,
						'height'            => $size
					);
					$this->image_lib->initialize($config);
					$this->image_lib->resize();
					// resize

				} else {
					$error = array('error' => $this->upload->display_errors());
					foreach ($error as $key => $value) {
						$msg[$key] = $value;
					}
					return ['st' => 0, 'data' => $msg];
					exit();
				}
			}

			if (!empty($uploadData)) {
				$list = array();
				foreach ($uploadData as $key => $value) {
					$data[$key] = array(
						'image' => $uploadPath . 'big/' . $value['file_name'],
						'thumb' => $uploadPath . 'thumb/' . $value['file_name'],
					);
				}
				return ['st' => 1, 'data' => $data];
			} else {
				return ['st' => 0, 'data' => 'Please select an image'];
			}
		} else {
			return ['st' => 0, 'data' => 'Please select an image'];
		}
	}



	public function upload_banner($dir = 'site_banners')
	{
		ini_set('memory_limit', '-1');
		$data = array();
		if (!empty($_FILES['file']['name'])) {
			$filesCount = count($_FILES['file']['name']);
			for ($i = 0; $i < $filesCount; $i++) {
				$_FILES['uploadFile']['name'] = str_replace(",", "_", $_FILES['file']['name'][$i]);
				$_FILES['uploadFile']['type'] = $_FILES['file']['type'][$i];
				$_FILES['uploadFile']['tmp_name'] = $_FILES['file']['tmp_name'][$i];
				$_FILES['uploadFile']['error'] = $_FILES['file']['error'][$i];
				$_FILES['uploadFile']['size'] = $_FILES['file']['size'][$i];

				//Directory where files will be uploaded
				$uploadPath = 'uploads/' . $dir . '/';


				$config['upload_path'] = $uploadPath;
				// Specifying the file formats that are supported.
				$config['allowed_types'] = 'jpg|jpeg|png|pdf|svg';
				$config['overwrite'] = TRUE;
				$config['encrypt_name'] = TRUE;
				$this->load->library('upload', $config);
				$this->upload->initialize($config);
				// resize library
				$this->load->library('image_lib');

				if ($this->upload->do_upload('uploadFile')) {
					$fileData = $this->upload->data();
					$uploadData[$i]['file_name'] = $fileData['file_name'];
				} else {
					$error = array('error' => $this->upload->display_errors());
					foreach ($error as $key => $value) {
						$msg[$key] = $value;
					}
					return ['st' => 0, 'data' => $msg];
					exit();
				}
			}

			if (!empty($uploadData)) {
				$list = array();
				foreach ($uploadData as $key => $value) {
					$data[$key] = array(
						'image' => $uploadPath . $value['file_name'],
					);
				}
				return ['st' => 1, 'data' => $data];
			} else {
				return ['st' => 0, 'data' => 'Please select an image'];
			}
		} else {
			return ['st' => 0, 'data' => 'Please select an image'];
		}
	}


	/**===== Upload images dashboard ====**/
	public function upload_img($id, $table)
	{
		if (!empty($_FILES['file']['name'])) {
			$up_load = $this->upload(400);
			if ($up_load['st'] == 1) :
				foreach ($up_load['data'] as $key => $value) {
					$data = array(
						'images' => $value['image'],
						'thumb' => $value['thumb'],
					);
					$this->admin_m->update($data, $id, $table);
				}
				return true;
			else :
				$this->session->set_flashdata('success', $up_load['data']['error']);
			endif;
		}
	}

	public function move_ai_img($id, $table)
	{
		$item = $this->admin_m->single_select_by_id($id, $table);
		if (empty($item['images'])) return false;

		$ai_path = 'uploads/ai_images/';
		if (strpos($item['images'], $ai_path) === 0) {
			$filename = basename($item['images']);
			$source = FCPATH . $item['images'];
			
			if (file_exists($source)) {
				$big_dir = FCPATH . 'uploads/big/';
				$thumb_dir = FCPATH . 'uploads/thumb/';

				if (!is_dir($big_dir)) mkdir($big_dir, 0777, true);
				if (!is_dir($thumb_dir)) mkdir($thumb_dir, 0777, true);

				$new_big = 'uploads/big/' . $filename;
				$new_thumb = 'uploads/thumb/' . $filename;

				// Move to Big
				rename($source, FCPATH . $new_big);

				// Generate Thumb
				$this->load->library('image_lib');
				$config['image_library'] = 'gd2';
				$config['source_image'] = FCPATH . $new_big;
				$config['new_image'] = FCPATH . $new_thumb;
				$config['maintain_ratio'] = TRUE;
				$config['width'] = 400;
				$config['height'] = 400;

				$this->image_lib->initialize($config);
				$this->image_lib->resize();
				$this->image_lib->clear();

				// Update DB
				$this->admin_m->update(['images' => $new_big, 'thumb' => $new_thumb], $id, $table);
				return true;
			}
		}
		return false;
	}




	public function order_qr($phone, $orderId, $shopId)
	{
		$shop = $this->common_m->get_restaurant_info_by_id($shopId);
		if (isset($shop['is_order_qr']) && $shop['is_order_qr'] == 1) {
			$this->load->library('ciqrcode');
			$qr_image = $shop['username'] . '_' . random_string() . '.png';
			$params['data'] = asset_url('my-orders/' . $shop['username'] . '?phone=' . $phone . '&orderId=' . $orderId);
			$params['level'] = 'H';
			$params['size'] = 8;
			$params['savename'] = FCPATH . "uploads/orders_qr/" . $qr_image;
			if ($this->ciqrcode->generate($params)) {
				$data = array(
					'qr_link' => 'uploads/orders_qr/' . $qr_image,
				);
				$update = $this->admin_m->update_by_type($data, $orderId, 'uid', 'order_user_list');
			}

			return $data['qr_link'];
		}
	}


	public function menu_qr($menuId, $shopId)
	{
		$shop = $this->common_m->get_restaurant_info_by_id($shopId);
		$this->load->library('ciqrcode');
		$qr_image = $shop['username'] . '_menu_' . random_string() . '.png';
		$params['data'] = asset_url('qr-menu/' . $shop['username'] . '/' . md5($menuId));
		$params['level'] = 'H';
		$params['size'] = 12;
		$params['savename'] = FCPATH . "uploads/orders_qr/" . $qr_image;
		if ($this->ciqrcode->generate($params)) {
			$data = array(
				'qr_link' => 'uploads/orders_qr/' . $qr_image,
			);
			$update = $this->admin_m->update_menu_qr($data, $menuId, $shopId);
		}

		return $data['qr_link'];
	}


	public function verify($purchase_code)
	{
		$form_data = [
			'purchase_code' => $purchase_code,
			'site_url' => SITE_URL,
			'author' => AUTHOR,
			'is_localhost' => isLocalHost(),
		];

		$form_data = json_encode($form_data);
		$result = (object)[
				'st' => 1, 
				'msg' => 'Valid!',
				'purchase_code' => 'JAE73-H8TY7-R4Q3F'
			];

		if (isset($result->st) && $result->st == 1) :
			return 1;
		else :
			return 0;
		endif;
	}


	public function croped($id, $table)
	{
		if ($this->input->post('cropData')) {
			$base64Image = $this->input->post('cropData');
			$imageData = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $base64Image));
			$rang = random_string();
			// Adjust the file path and name as needed
			$uploadPath = 'uploads/thumb/';
			$fileName = $rang . time() . '.jpg';

			$filePath = $uploadPath . $fileName;



			// Save the image to the server
			file_put_contents($filePath, $imageData);
			$thumb = resize_img($filePath, 350, 300, $uploadPath);

			$this->admin_m->update(['thumb' => $thumb, 'images' => $filePath], $id, $table);
			return true;
		} else {
			return false;
		}
	}

	public function croped__()
	{
		$this->load->library('image_lib');
		// Retrieve other form data if needed

		$croppedImageData = $this->input->post('cropData');

		// Resize the image
		$resizeConfig['width'] = 150;  // Adjust the width as needed
		$resizeConfig['height'] = 150;  // Adjust the height as needed
		$resizeConfig['quality'] = '90%';
		$resizeConfig['source_image'] = $croppedImageData;  // Use the base64-encoded image data directly
		$this->image_lib->initialize($resizeConfig);

		if (!$this->image_lib->resize()) {
			echo $this->image_lib->display_errors();
			return;
		}

		// Upload the resized image
		$uploadConfig['upload_path'] = 'uploads/';
		$uploadConfig['allowed_types'] = 'jpg|jpeg|png|gif';
		$uploadConfig['file_name'] = 'resized_image.jpg';  // Adjust the filename as needed

		$this->load->library('upload', $uploadConfig);

		if (!$this->upload->do_upload('cropData')) {
			echo $this->upload->display_errors();
		} else {
			echo 'Cropped and resized image uploaded successfully!';
		}
	}
}
