<?php
require "global.ajax.php";
require "../controllers/cloudinary-api.php";

$posShowMenuUsdAmount = $posInfo['pos_show_menu_usd_amount'];

switch ($_GET["op"]) {

	case 'ajaxSaveUpdate':

		// POST VARIABLES
		$pro_id = isset($_POST["pro_id"]) ? funCheckInput($_POST["pro_id"]) : "";
		$pro_ent_id = isset($_POST["pro_ent_id"]) ? funCheckInput($_POST["pro_ent_id"]) : "";
		$pro_pos_id = isset($_POST["pro_pos_id"]) ? funCheckInput($_POST["pro_pos_id"]) : "";
		$pro_description = isset($_POST["pro_description"]) ? funCheckInput($_POST["pro_description"]) : "";
		$pro_code = isset($_POST["pro_code"]) ? funCheckInput($_POST["pro_code"]) : "";
		$pro_cat_id = isset($_POST["pro_cat_id"]) ? funCheckInput($_POST["pro_cat_id"]) : "";
		$pro_type = isset($_POST["pro_type"]) ? funCheckInput($_POST["pro_type"]) : "";
		$pro_sale_measure = isset($_POST["pro_sale_measure"]) ? funCheckInput($_POST["pro_sale_measure"]) : "";
		$pro_cost = isset($_POST["pro_cost"]) ? funCheckInput($_POST["pro_cost"]) : "";
		$pro_price = isset($_POST["pro_price"]) ? funCheckInput($_POST["pro_price"]) : "";
		$pro_price_party = isset($_POST["pro_price_party"]) ? funCheckInput($_POST["pro_price_party"]) : "";
		$pro_discount = isset($_POST["pro_discount"]) ? funCheckInput($_POST["pro_discount"]) : "";
		$pro_created_at = isset($_POST["pro_created_at"]) ? funCheckInput($_POST["pro_created_at"]) : "";
		$pro_description = ucwords(strtolower($pro_description));

		if (empty($pro_price_party) || $pro_price_party <= 0) $pro_price_party = $pro_price;
		if (empty($pro_ent_id)) $pro_ent_id = $session_user_ent_id;
		if (empty($pro_pos_id)) $pro_pos_id = $session_user_pos_id;

		try {

			$pdo->beginTransaction();

			$entData = getEnterpriseData($pro_ent_id);
			$ent_folder_name = $entData['ent_folder_name'];
			$saveToFolder = "evosyspos/{$ent_folder_name}/products";

			$isNew = empty(trim($pro_id));

			// Generate code if needed
			if ($isNew && empty($pro_code)) {
				$pro_code = createTokenNumber('tb_products', 'pro_code', '12');
			}

			if ($isNew) {
				// INSERT
				$stmt = $pdo->prepare("INSERT INTO tb_products (
						pro_code, pro_ent_id, pro_pos_id, pro_cat_id,
						pro_description, pro_type, pro_sale_measure,
						pro_price, pro_price_party, pro_discount, pro_created_by
					) VALUES (
						:pro_code, :pro_ent_id, :pro_pos_id, :pro_cat_id,
						:pro_description, :pro_type, :pro_sale_measure,
						:pro_price, :pro_price_party, :pro_discount, :user_id
					)");

				$stmt->execute([
					':pro_code' => $pro_code,
					':pro_ent_id' => $pro_ent_id,
					':pro_pos_id' => $pro_pos_id,
					':pro_cat_id' => $pro_cat_id,
					':pro_description' => $pro_description,
					':pro_type' => $pro_type,
					':pro_sale_measure' => $pro_sale_measure,
					':pro_price' => $pro_price,
					':pro_price_party' => $pro_price_party,
					':pro_discount' => $pro_discount,
					':user_id' => $session_user_id
				]);

				$pro_id = $pdo->lastInsertId();

				// Handle image upload (shared logic)
				if (isset($_FILES['pro_image']) && is_uploaded_file($_FILES['pro_image']['tmp_name'])) {

					$maxSize = 2 * 1024 * 1024; // 2MB
					if ($_FILES["pro_image"]["size"] > $maxSize) {
						// throw new \RuntimeException("File exceeds 2MB limit.");
						if ($pdo->inTransaction()) $pdo->rollBack();
						$response = array("status" => "warning", "message" => "File exceeds 2MB limit.");
						echo json_encode($response);
						exit();
					}

					$sourceFilePath = $_FILES["pro_image"]["tmp_name"];
					$fileName = "product_{$pro_id}";
					$resCloudUpload = fnUploadToCloudinary($sourceFilePath, $saveToFolder, "image", $fileName, $oldFileToDelete = "");

					$imageUrl = $resCloudUpload['secure_url'];

					$sql = "UPDATE tb_products 
                	SET pro_image = :pro_image
                	WHERE pro_id = :pro_id";

					$stmt = $pdo->prepare($sql);
					$stmt->execute([
						':pro_image' => $imageUrl,
						':pro_id'   => $pro_id
					]);
				}

				$response = array("message" => $translate['saved_successfully'], "status" => "success");
			} else {

				// Keep old image if no new one
				$oldImage = getProductsData($pro_id)['pro_image'];
				$imageUrl = $oldImage;

				// Handle image upload (shared logic)
				if (isset($_FILES['pro_image']) && is_uploaded_file($_FILES['pro_image']['tmp_name'])) {

					$maxSize = 2 * 1024 * 1024; // 2MB
					if ($_FILES["pro_image"]["size"] > $maxSize) {
						// throw new \RuntimeException("File exceeds 2MB limit.");
						if ($pdo->inTransaction()) $pdo->rollBack();
						$response = array("status" => "warning", "message" => "File exceeds 2MB limit.");
						echo json_encode($response);
						exit();
					}

					$sourceFilePath = $_FILES["pro_image"]["tmp_name"];
					$fileName = "product_{$pro_id}";
					$resCloudUpload = fnUploadToCloudinary($sourceFilePath, $saveToFolder, "image", $fileName, $oldFileToDelete = "");

					$imageUrl = $resCloudUpload['secure_url'];
				}

				// UPDATE
				$stmt = $pdo->prepare("UPDATE tb_products SET
				pro_description = :pro_description,
				pro_code = :pro_code,
				pro_cat_id = :pro_cat_id,
				pro_type = :pro_type,
				pro_sale_measure = :pro_sale_measure,
				pro_price = :pro_price,
				pro_price_party = :pro_price_party,
				pro_discount = :pro_discount,
				pro_image = :pro_image
				WHERE pro_id = :pro_id");

				$stmt->execute([
					':pro_description' => $pro_description,
					':pro_code' => $pro_code,
					':pro_cat_id' => $pro_cat_id,
					':pro_type' => $pro_type,
					':pro_sale_measure' => $pro_sale_measure,
					':pro_price' => $pro_price,
					':pro_price_party' => $pro_price_party,
					':pro_discount' => $pro_discount,
					':pro_image' => $imageUrl,
					':pro_id' => $pro_id
				]);

				$response = array("message" => $translate['updated_successfully'], "status" => "success");
			}

			$pdo->commit();
		} catch (\RuntimeException | \InvalidArgumentException $e) {
			if ($pdo->inTransaction()) $pdo->rollBack();
			$response = array("status" => "error", "message" => "Database error. {$translate['execution_failed_please_contact_the_system_vendor_for_technical_assistance']} <br>" . $e->getMessage(), "redirect" => true);
		} catch (\PDOException $e) {
			if ($pdo->inTransaction()) $pdo->rollBack();
			$response = array("status" => "error", "message" => "Database error. {$translate['execution_failed_please_contact_the_system_vendor_for_technical_assistance']} <br>" . $e->getMessage(), "redirect" => true);
		}

		echo json_encode($response);

		break;


	case 'ajaxProductsList':

		$pro_ent_id = isset($_GET["ent_id"]) ? funCheckInput($_GET["ent_id"]) : "";
		$pro_pos_id = isset($_GET["pos_id"]) ? funCheckInput($_GET["pos_id"]) : "";
		$pro_status = isset($_GET["pro_status"]) ? funCheckInput($_GET["pro_status"]) : "";
		$pro_type = isset($_GET["pro_type"]) ? funCheckInput($_GET["pro_type"]) : "";

		if (empty($pro_ent_id) || empty($pro_pos_id)) exit();

		$whereProType = "";
		if (!empty($pro_type) && $pro_type != "All") $whereProType = "AND pro_type = '{$pro_type}'";

		$sql = "SELECT
		pro_id
		,pro_ent_id
		,pro_pos_id
		,pro_code
		,(select pos_name FROM tb_pos WHERE pro_pos_id = pos_id) AS pos_name
		,(select cat_name FROM tb_categories WHERE pro_cat_id = cat_id) AS cat_name
		,pro_description
		,pro_cat_id
		,pro_type
		,pro_sale_measure
		,pro_cost
		,pro_price
		,pro_price_party
		,pro_discount
		,pro_image
		,IF(pro_type = 'Service','FULL',(SELECT IFNULL(sum(pur_det_pro_qty),0) FROM tb_purchases_details WHERE pur_det_pro_id=pro_id AND pur_det_status = 'Enabled')-(SELECT IFNULL(sum(sale_det_pro_qty),0) FROM tb_sales_details WHERE sale_det_pro_id=pro_id AND sale_det_status = 'Enabled')+(SELECT IFNULL(SUM(adjust_quantity),0) FROM tb_stock_adjustments WHERE adjust_product_id = pro_id AND adjust_type = 'Increase' AND adjust_status = 'Enabled')-(SELECT IFNULL(SUM(adjust_quantity),0) FROM tb_stock_adjustments WHERE adjust_product_id = pro_id AND adjust_type = 'Decrease' AND adjust_status = 'Enabled')) AS stock_actual
		,(SELECT IFNULL(sum(sale_det_pro_qty),0) FROM tb_sales_details WHERE sale_det_pro_id=pro_id AND sale_det_status = 'Enabled') AS sale_qty
		,pro_status
		FROM tb_products
		WHERE pro_ent_id = '{$pro_ent_id}'
		AND pro_pos_id = '{$pro_pos_id}'
		AND pro_status = '{$pro_status}'
		$whereProType
		ORDER BY pro_description ASC;";

		// exit($sql);

		$rows = executePDOFetchAllAPI($sql);
		echo json_encode($rows);

		break;


	case 'ajax_activate':

		$pro_id = isset($_POST["pro_id"]) ? funCheckInput($_POST["pro_id"]) : "";
		$sql = "UPDATE tb_products SET pro_status = 'Enabled' WHERE pro_id = '{$pro_id}';";
		echo $result = executeQueryPDO($sql, $translate['access_enabled'], $translate['error_access_activation']);

		break;


	case 'ajax_desactivate':

		$pro_id = isset($_POST["pro_id"]) ? funCheckInput($_POST["pro_id"]) : "";
		$sql = "UPDATE tb_products SET pro_status = 'Disabled' WHERE pro_id = '{$pro_id}';";
		echo $result = executeQueryPDO($sql, $translate['access_disabled'], $translate['error_access_deactivation']);

		break;


	case 'ajaxProductDropdownList':

		$pos_id = isset($_GET["pos_id"]) ? funCheckInput($_GET["pos_id"]) : "";
		$type = isset($_GET["type"]) ? funCheckInput($_GET["type"]) : "";

		$whereType = "AND pro_type = '{$type}'";
		if ($type == "All") $whereType = "";

		$sql = "SELECT pro_id,pro_description
		FROM tb_products WHERE pro_pos_id = '{$pos_id}' $whereType
		GROUP BY pro_id ORDER BY pro_description ASC;";

		$answer = executePDOFetchAllAPI($sql);
		echo json_encode($answer);

		break;


	case 'ajax_addProductWithBarCode':

		$sale_pos_id = isset($_POST["sale_pos_id"]) ? funCheckInput($_POST["sale_pos_id"]) : "";
		$pro_code = isset($_POST["pro_code"]) ? funCheckInput($_POST["pro_code"]) : "";

		if (empty($pro_code)) exit();

		$sqlProducts = "SELECT * FROM tb_products WHERE pro_pos_id = $sale_pos_id AND pro_status = 'Enabled' AND pro_code = '$pro_code' ORDER BY pro_description ASC;";

		// exit($sqlProducts);

		$sqlProductsResponse = executePDOFetchOne($sqlProducts, $translate['error_display_sale_details']);

		if ($sqlProductsResponse && count($sqlProductsResponse) >= 1) {

			$pro_price = $sqlProductsResponse['pro_price'];
			if ($posInfo['pos_festive_mode'] == "On") $pro_price = $sqlProductsResponse['pro_price_party'];

			$pro_image = "assets/images/no-image.png";
			if (!empty($sqlProductsResponse['pro_image'])) $pro_image = $sqlProductsResponse['pro_image'];

			$resProductByCode = array("status" => "success", "pro_id" => $sqlProductsResponse['pro_id'], "pro_cat_id" => $sqlProductsResponse['pro_cat_id'], "pro_description" => $sqlProductsResponse['pro_description'], "pro_price" => $pro_price, "pro_image" => $pro_image, "pro_sale_measure" => $sqlProductsResponse['pro_sale_measure']);

			echo json_encode($resProductByCode);
		} else {
			$resProductByCode = array("status" => "error", "message" => $translate['product_code_not_found']);
			echo json_encode($resProductByCode);
		}

		break;


	case 'ajaxShowProductListToSale':

		$ent_id = isset($_GET["ent_id"]) ? funCheckInput($_GET["ent_id"]) : "";
		$pos_id = isset($_GET["pos_id"]) ? funCheckInput($_GET["pos_id"]) : "";

		$productNameOrBarcodeValue = isset($_GET["productNameOrBarcode"]) ? funCheckInput($_GET["productNameOrBarcode"]) : "";
		$PosProductListLimit = isset($_GET["PosProductListLimit"]) ? funCheckInput($_GET["PosProductListLimit"]) : "";

		$whereProCodeOrName = "";
		if (!empty($productNameOrBarcodeValue)) {
			$whereProCodeOrName = "AND (pro_code = '$productNameOrBarcodeValue' OR pro_description LIKE '%$productNameOrBarcodeValue%')";
		}

		$setLimit = "LIMIT 18";
		if (!empty($PosProductListLimit)) {
			$setLimit = "LIMIT {$PosProductListLimit}";
		}

		$sqlProducts = "SELECT *,IF(pro_type = 'Service','FULL',(SELECT IFNULL(sum(pur_det_pro_qty),0) FROM tb_purchases_details WHERE pur_det_pro_id=pro_id AND pur_det_status = 'Enabled')-(SELECT IFNULL(sum(sale_det_pro_qty),0) FROM tb_sales_details WHERE sale_det_pro_id=pro_id AND sale_det_status = 'Enabled')+(SELECT IFNULL(SUM(adjust_quantity),0) FROM tb_stock_adjustments WHERE adjust_product_id = pro_id AND adjust_type = 'Increase' AND adjust_status = 'Enabled')-(SELECT IFNULL(SUM(adjust_quantity),0) FROM tb_stock_adjustments WHERE adjust_product_id = pro_id AND adjust_type = 'Decrease' AND adjust_status = 'Enabled')) AS pro_current_stock
        ,(SELECT cat_name FROM tb_categories WHERE cat_id = pro_cat_id) AS pro_cat_name
        FROM tb_products
		WHERE pro_ent_id = '{$ent_id}' AND pro_pos_id = '$pos_id' AND pro_status = 'Enabled' $whereProCodeOrName
        ORDER BY pro_description ASC $setLimit;";

		// exit($sqlProducts);

		$rows = executePDOFetchAllAPI($sqlProducts);
		echo json_encode($rows);

		break;


	case 'ajaxGetCurrentProductStockById':

		$pro_id = isset($_GET["pro_id"]) ? funCheckInput($_GET["pro_id"]) : "";

		$answer = getProductStockById($pro_id);
		echo json_encode($answer);

		break;


	case 'ajaxSwitchStatus':

		$pro_id = isset($_POST["pro_id"]) ? funCheckInput($_POST["pro_id"]) : "";
		$status = isset($_POST["status"]) ? funCheckInput($_POST["status"]) : "";

		$sql = "UPDATE tb_products SET pro_status = '{$status}' WHERE pro_id = '$pro_id';";
		$result = executeQueryPDO($sql, $translate['successfully_executed'], $translate['execution_failed']);
		echo json_encode($result);

		break;


	case 'ajaxProductReportList':

		$pos_id = isset($_GET["pos_id"]) ? funCheckInput($_GET["pos_id"]) : "";
		$pro_id = isset($_GET["pro_id"]) ? funCheckInput($_GET["pro_id"]) : "";
		$fromDate = isset($_GET["fromDate"]) ? funCheckInput($_GET["fromDate"]) : "";
		$toDate = isset($_GET["toDate"]) ? funCheckInput($_GET["toDate"]) : "";

		if (empty($pos_id)) exit();
		$posInfo = getBranchData($pos_id);

		$whereProId = "";
		if (!empty($pro_id)) $whereProId = "AND sale_det_pro_id = '$pro_id'";

		$DayStartTime = $posInfo["pos_day_start_time"] ?? "07:00:00";
		$DayEndTime = $posInfo["pos_day_end_time"] ?? "06:59:59";

		$fromDate = date("{$fromDate} {$DayStartTime}");
		$toDate = date("Y-m-d", strtotime("{$toDate} +1 day")) . " {$DayEndTime}";

		$whereDate = "AND sale_det_sale_date BETWEEN '{$currentDayStart}' AND '{$currentDayEnd}'";
		if (!empty(trim((string) $fromDate)) && !empty(trim((string) $toDate))) {
			$whereDate = "AND sale_det_sale_date BETWEEN '{$fromDate}' AND '{$toDate}'";
		}

		$sql = "SELECT
			sale_det_sale_id
			,sale_det_ent_id
			,sale_det_pos_id
			,DATE_FORMAT( sale_det_sale_date, '%d-%b-%Y' ) AS sale_det_sale_date
			,(select pos_name FROM tb_pos WHERE pos_id = sale_det_pos_id) AS pos_name
			,(select sale_cus_id FROM tb_sales WHERE sale_id = sale_det_sale_id) AS sale_det_cus_id
			,(select pro_description FROM tb_products WHERE pro_id = sale_det_pro_id) AS pro_description
			,IFNULL(SUM(sale_det_pro_qty),0) AS product_quantity
	
			,IF(pro_type = 'Service','FULL',(SELECT IFNULL(sum(pur_det_pro_qty),0) FROM tb_purchases_details WHERE pur_det_pro_id=pro_id AND pur_det_status = 'Enabled')-(SELECT IFNULL(sum(sale_det_pro_qty),0) FROM tb_sales_details WHERE sale_det_pro_id=pro_id AND sale_det_status = 'Enabled')+(SELECT IFNULL(SUM(adjust_quantity),0) FROM tb_stock_adjustments WHERE adjust_product_id = pro_id AND adjust_type = 'Increase' AND adjust_status = 'Enabled')-(SELECT IFNULL(SUM(adjust_quantity),0) FROM tb_stock_adjustments WHERE adjust_product_id = pro_id AND adjust_type = 'Decrease' AND adjust_status = 'Enabled')) AS stock_actual

			,sale_det_status
	
			FROM tb_sales_details
			LEFT JOIN tb_products ON pro_id = sale_det_pro_id
			WHERE sale_det_pos_id = '$pos_id' $whereProId $whereDate
			AND sale_det_status = 'Enabled'
			GROUP BY sale_det_pro_id,sale_det_sale_id,DATE_FORMAT(sale_det_sale_date, '%d-%b-%Y')
			ORDER BY sale_det_id ASC;";

		// exit($sql);

		$answer = executePDOFetchAllAPI($sql);
		echo json_encode($answer);


		break;


		// case 'ajaxShowCategoryList':

		// 	$cat_pos_id = isset($_POST["cat_pos_id"]) ? funCheckInput($_POST["cat_pos_id"]) : "";

		// 	$wherePos = "";
		// 	if (!empty($cat_pos_id)) $wherePos = "AND cat_pos_id = '{$cat_pos_id}'";

		// 	$sqlSelectCategories = "SELECT cat_name, cat_image FROM tb_categories WHERE cat_access = 'Enabled' {$wherePos} ORDER BY cat_name ASC; ";
		// 	$catSqlResponse = executePDOFetchAll($sqlSelectCategories);
		// 	// exit($sqlSelectCategories);

		// 	$categoriesHtml = '';

		// 	foreach ($catSqlResponse as $key => $value) {

		// 		$categoriesHtml = '';

		// 		$categoriesHtml .= '

		//             <li class="nav-item">
		//                 <a class="nav-link" href="javascript:void(0)" data-filter="' . $value['cat_name'] . '">
		//                     <i class="fa ' . $value['cat_image'] . ' me-1 ms-n2"></i> ' . $value["cat_name"] . '
		//                 </a>
		//             </li>
		//         ';

		// 		echo $categoriesHtml;
		// 	}

		// 	break;
}
