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

class Products extends CI_Controller
{
	function __construct()
	{
		parent::__construct();

		$this->load->model('common');
		$this->load->helper(array('form', 'url', 'string'));
		$this->load->library('form_validation');
		$this->load->library('session');
	}

	/**
	 * List all products with filters
	 */
	public function index()
	{
		// Get filter parameters
		$filterCategory = $this->input->get('filter_category');
		$filterVendor = $this->input->get('filter_vendor');
		$filterStatus = $this->input->get('filter_status');
		$searchTerm = $this->input->get('search');
		
		// Get all products
		$allProducts = $this->common->readdatafromcollectionwhereclause("Products");
		
		// Get categories and vendors for filters
		$data['categories'] = $this->common->readdatafromcollectionwhereclause("Categories");
		$allVendors = $this->common->readdatafromcollectionwhereclause("Users");
		$data['vendors'] = array();
		foreach ($allVendors as $vendorId => $vendor) {
			if (isset($vendor['userRole']) && $vendor['userRole'] == 'vendor') {
				$data['vendors'][$vendorId] = $vendor;
			}
		}
		
		// Apply filters
		$filteredProducts = array();
		foreach ($allProducts as $productId => $product) {
			// Filter by category
			if ($filterCategory && (!isset($product['categoryId']) || $product['categoryId'] != $filterCategory)) {
				continue;
			}
			
			// Filter by vendor
			if ($filterVendor && (!isset($product['userId']) || $product['userId'] != $filterVendor)) {
				continue;
			}
			
			// Filter by status
			if ($filterStatus && $filterStatus != 'all') {
				$isVerified = isset($product['isVerified']) ? $product['isVerified'] : false;
				if ($filterStatus == 'approved' && !$isVerified) {
					continue;
				}
				if ($filterStatus == 'pending' && $isVerified) {
					continue;
				}
			}
			
			// Search filter
			if ($searchTerm) {
				$searchLower = strtolower($searchTerm);
				$productName = isset($product['productName']) ? strtolower($product['productName']) : '';
				if (strpos($productName, $searchLower) === false) {
					continue;
				}
			}
			
			$filteredProducts[$productId] = $product;
		}
		
		// Enhance product data
		$data['products'] = $this->enhanceProductData($filteredProducts, $data['categories'], $data['vendors']);
		$data['filterCategory'] = $filterCategory;
		$data['filterVendor'] = $filterVendor;
		$data['filterStatus'] = $filterStatus;
		$data['searchTerm'] = $searchTerm;
		
		$this->template->template_render('products_management', $data);
	}
	
	/**
	 * Enhance product data with category and vendor names
	 */
	private function enhanceProductData($products, $categories, $vendors)
	{
		foreach ($products as $productId => &$product) {
			// Add category name
			if (isset($product['categoryId']) && isset($categories[$product['categoryId']])) {
				$product['categoryName'] = isset($categories[$product['categoryId']]['categoryName']) ? 
					$categories[$product['categoryId']]['categoryName'] : 'Unknown';
			} else {
				$product['categoryName'] = 'Unknown';
			}
			
			// Add vendor name
			if (isset($product['userId']) && isset($vendors[$product['userId']])) {
				$vendor = $vendors[$product['userId']];
				$product['vendorName'] = isset($vendor['shopName']) ? $vendor['shopName'] : 
					(isset($vendor['firstName']) ? $vendor['firstName'] . ' ' . (isset($vendor['lastName']) ? $vendor['lastName'] : '') : 'Unknown');
			} else {
				$product['vendorName'] = 'Unknown';
			}
		}
		
		return $products;
	}

	/**
	 * Add new product form
	 */
	public function addproduct()
	{
		$data['categories'] = $this->common->readdatafromcollectionwhereclause("Categories");
		$data['subcategories'] = $this->common->readdatafromcollectionwhereclause("Subcategories");
		$allUsers = $this->common->readdatafromcollectionwhereclause("Users");
		$data['vendors'] = array();
		foreach ($allUsers as $userId => $user) {
			if (isset($user['userRole']) && $user['userRole'] == 'vendor') {
				$data['vendors'][$userId] = $user;
			}
		}

		$this->template->template_render('addproduct', $data);
	}

	/**
	 * Insert new product
	 */
	public function insertproduct()
	{
		$post = $this->input->post();
		$isAjax = $this->input->is_ajax_request();
		
		// Validation
		if (empty($post['productName']) || empty($post['productPrice'])) {
			if ($isAjax) {
				echo json_encode(array('success' => false, 'message' => 'Product Name and Price are required.'));
				return;
			} else {
				$this->session->set_flashdata('warningmessage', 'Product Name and Price are required.');
				redirect(base_url('products/addproduct'));
				return;
			}
		}
		
		// Prepare product data
		$productData = array(
			'productName' => trim($post['productName']),
			'productPrice' => floatval($post['productPrice']),
			'displayPrice' => isset($post['displayPrice']) ? floatval($post['displayPrice']) : floatval($post['productPrice']),
			'productDetail' => isset($post['productDetail']) ? trim($post['productDetail']) : '',
			'productUnit' => isset($post['productUnit']) ? trim($post['productUnit']) : '',
			'categoryId' => isset($post['categoryId']) ? trim($post['categoryId']) : '',
			'subcategoryId' => isset($post['subcategoryId']) && !empty($post['subcategoryId']) ? trim($post['subcategoryId']) : '',
			'userId' => isset($post['userId']) ? trim($post['userId']) : '',
			'potencyLevel' => isset($post['potencyLevel']) ? intval($post['potencyLevel']) : 0,
			'nicotineLevel' => isset($post['nicotineLevel']) ? intval($post['nicotineLevel']) : 0,
			'isVerified' => isset($post['isVerified']) ? (bool)$post['isVerified'] : false,
			'date' => time() * 1000 // Current timestamp in milliseconds
		);
		
		// Handle image upload
		if (isset($_FILES['productImage']['tmp_name']) && !empty($_FILES['productImage']['tmp_name'])) {
			$firebase = $this->firebase->init();
			$storage = $firebase->createStorage();
			$defaultBucket = $storage->getBucket();
			
			$uploadedFile = $defaultBucket->upload(
				file_get_contents($_FILES['productImage']['tmp_name']),
				['name' => "productImage" . rand() . time() . $_FILES['productImage']['name']]
			);
			
			$productData['productUrl'] = $uploadedFile->info()['mediaLink'];
		} else {
			if ($isAjax) {
				echo json_encode(array('success' => false, 'message' => 'Product image is required.'));
				return;
			} else {
				$this->session->set_flashdata('warningmessage', 'Product image is required.');
				redirect(base_url('products/addproduct'));
				return;
			}
		}
		
		// Create product in Firestore
		$productId = time();
		$response = $this->common->adddatamodel('Products', $productId, $productData);
		
		if ($response) {
			if ($isAjax) {
				echo json_encode(array('success' => true, 'message' => 'Product added successfully!'));
				return;
			} else {
				$this->session->set_flashdata('successmessage', 'Product added successfully.');
			}
		} else {
			if ($isAjax) {
				echo json_encode(array('success' => false, 'message' => 'Something went wrong. Please try again.'));
				return;
			} else {
				$this->session->set_flashdata('warningmessage', 'Something went wrong. Please try again.');
			}
		}
		
		if (!$isAjax) {
			redirect(base_url('products'));
		}
	}

	/**
	 * Edit product form
	 */
	public function editproduct($id)
	{
		$data['product'] = $this->common->readdatadocument("Products", $id);
		if (empty($data['product'])) {
			$this->session->set_flashdata('warningmessage', 'Product not found');
			redirect(base_url('products'));
			return;
		}
		
		$data['categories'] = $this->common->readdatafromcollectionwhereclause("Categories");
		$data['subcategories'] = $this->common->readdatafromcollectionwhereclause("Subcategories");
		$allUsers = $this->common->readdatafromcollectionwhereclause("Users");
		$data['vendors'] = array();
		foreach ($allUsers as $userId => $user) {
			if (isset($user['userRole']) && $user['userRole'] == 'vendor') {
				$data['vendors'][$userId] = $user;
			}
		}
		$data['productId'] = $id;
		
		$this->template->template_render('editproduct', $data);
	}

	/**
	 * Update product
	 */
	public function updateproduct($id)
	{
		$post = $this->input->post();
		$isAjax = $this->input->is_ajax_request();
		
		// Validation
		if (empty($post['productName']) || empty($post['productPrice'])) {
			if ($isAjax) {
				echo json_encode(array('success' => false, 'message' => 'Product Name and Price are required.'));
				return;
			} else {
				$this->session->set_flashdata('warningmessage', 'Product Name and Price are required.');
				redirect(base_url('products/editproduct/' . $id));
				return;
			}
		}
		
		// Prepare update data
		$updateData = array(
			'productName' => trim($post['productName']),
			'productPrice' => floatval($post['productPrice']),
			'displayPrice' => isset($post['displayPrice']) ? floatval($post['displayPrice']) : floatval($post['productPrice']),
			'productDetail' => isset($post['productDetail']) ? trim($post['productDetail']) : '',
			'productUnit' => isset($post['productUnit']) ? trim($post['productUnit']) : '',
			'categoryId' => isset($post['categoryId']) ? trim($post['categoryId']) : '',
			'subcategoryId' => isset($post['subcategoryId']) && !empty($post['subcategoryId']) ? trim($post['subcategoryId']) : '',
			'userId' => isset($post['userId']) ? trim($post['userId']) : '',
			'potencyLevel' => isset($post['potencyLevel']) ? intval($post['potencyLevel']) : 0,
			'nicotineLevel' => isset($post['nicotineLevel']) ? intval($post['nicotineLevel']) : 0,
			'isVerified' => isset($post['isVerified']) ? (bool)$post['isVerified'] : false
		);
		
		// Handle image upload
		if (isset($_FILES['productImage']['tmp_name']) && !empty($_FILES['productImage']['tmp_name'])) {
			$firebase = $this->firebase->init();
			$storage = $firebase->createStorage();
			$defaultBucket = $storage->getBucket();
			
			$uploadedFile = $defaultBucket->upload(
				file_get_contents($_FILES['productImage']['tmp_name']),
				['name' => "productImage" . rand() . time() . $_FILES['productImage']['name']]
			);
			
			$updateData['productUrl'] = $uploadedFile->info()['mediaLink'];
		}
		
		// Update product
		$response = $this->common->updatedatamodel("Products", $id, $updateData);
		
		if ($response) {
			if ($isAjax) {
				echo json_encode(array('success' => true, 'message' => 'Product updated successfully!'));
				return;
			} else {
				$this->session->set_flashdata('successmessage', 'Product updated successfully.');
			}
		} else {
			if ($isAjax) {
				echo json_encode(array('success' => false, 'message' => 'Something went wrong. Please try again.'));
				return;
			} else {
				$this->session->set_flashdata('warningmessage', 'Something went wrong. Please try again.');
			}
		}
		
		if (!$isAjax) {
			redirect(base_url('products'));
		}
	}

	/**
	 * View product details
	 */
	public function detail($id)
	{
		$data['productdetail'] = $this->common->readdatadocument("Products", $id);
		if (empty($data['productdetail'])) {
			$this->session->set_flashdata('warningmessage', 'Product not found');
			redirect(base_url('products'));
			return;
		}
		
		$data['userinfo'] = $this->common->readdatadocument("Users", $data['productdetail']['userId']);
		$data['categories'] = $this->common->readdatadocument("Categories", $data['productdetail']['categoryId']);
		if (isset($data['productdetail']['subcategoryId']) && !empty($data['productdetail']['subcategoryId'])) {
			$data['subcategories'] = $this->common->readdatadocument("Subcategories", $data['productdetail']['subcategoryId']);
		} else {
			$data['subcategories'] = array();
		}
		
		$review = $this->common->readdatacollection("Products", "Reviews", $id);
		$noofreview = 0;
		$rating = 0;
		if (count($review) > 0) {
			foreach ($review as $r => $v) {
				$noofreview = $noofreview + 1;
				$rating = $rating + $v['rating'];
			}
		}

		$data['totalreview'] = $noofreview;
		$data['totalrating'] = $noofreview > 0 ? $rating / $noofreview : 0;
		$data["id"] = $id;
		
		$this->template->template_render('productdetail', $data);
	}

	/**
	 * Delete product
	 */
	public function deleteproduct($id)
	{
		$response = $this->common->deletedatamodel("Products", $id);
		if ($response) {
			$this->session->set_flashdata('successmessage', 'Product deleted successfully');
		} else {
			$this->session->set_flashdata('warningmessage', 'Failed to delete product');
		}
		redirect('products');
	}

	/**
	 * Update product price
	 */
	public function updateprice($id)
	{
		$data['displayPrice'] = (double)$this->input->post('displayPrice');
		$flag = $this->common->updatedatamodel("Products", $id, $data);
		if ($flag) {
			$this->session->set_flashdata('successmessage', 'Price has been updated successfully.');
			redirect('products/detail/' . $id);
		} else {
			$this->session->set_flashdata('warningmessage', 'Something went wrong. Please try later');
			redirect('products/detail/' . $id);
		}
	}

	/**
	 * Update product status (approve/reject)
	 */
	public function updatestatus($id, $flag)
	{
		if ($flag == "approved") {
			$data['isVerified'] = true;
		} else {
			$data['isVerified'] = false;
		}

		$flag = $this->common->updatedatamodel("Products", $id, $data);
		if ($flag) {
			$this->session->set_flashdata('successmessage', 'Product status updated successfully.');
			redirect('products/detail/' . $id);
		} else {
			$this->session->set_flashdata('warningmessage', 'Something went wrong. Please try later');
			redirect('products/detail/' . $id);
		}
	}
}
