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

switch ($_GET["op"]) {

	case 'ajaxSaveUpdate':

		// POST VARIABLES
		$requested = isset($_POST["requested"]) ? funCheckInput($_POST["requested"]) : "";
		$ent_id = isset($_POST["ent_id"]) ? funCheckInput($_POST["ent_id"]) : "";
		$ent_name = isset($_POST["ent_name"]) ? funCheckInput($_POST["ent_name"]) : "";
		$ent_document = isset($_POST["ent_document"]) ? funCheckInput($_POST["ent_document"]) : "";
		$ent_document_number = isset($_POST["ent_document_number"]) ? funCheckInput($_POST["ent_document_number"]) : "";
		$ent_email = isset($_POST["ent_email"]) ? funCheckInput($_POST["ent_email"]) : "";
		$ent_website_url = isset($_POST["ent_website_url"]) ? funCheckInput($_POST["ent_website_url"]) : "";
		$ent_online_billing_status = isset($_POST["ent_online_billing_status"]) ? funCheckInput($_POST["ent_online_billing_status"]) : "";
		$ent_plan_id = isset($_POST["ent_plan_id"]) ? funCheckInput($_POST["ent_plan_id"]) : "";
		$ent_cancel_password = isset($_POST["ent_cancel_password"]) ? funCheckInput($_POST["ent_cancel_password"]) : "";
		$ent_discount_password = isset($_POST["ent_discount_password"]) ? funCheckInput($_POST["ent_discount_password"]) : "";
		$ent_statistic_password = isset($_POST["ent_statistic_password"]) ? funCheckInput($_POST["ent_statistic_password"]) : "";
		$ent_notification_text = isset($_POST["ent_notification_text"]) ? funCheckInput($_POST["ent_notification_text"]) : "";

		$ent_name = mb_strtoupper($ent_name);

		try {

			$pdo->beginTransaction();

			// Generate folder name
			$ent_folder_name = generateEnterpriseFolderName($ent_name);
			$saveToFolder = "evosyspos/{$ent_folder_name}/logo";

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

			if ($isNew) {

				// Generate code
				$ent_code = createTokenNumber('tb_enterprises', 'ent_code', '6');

				// Base fields
				$fields = [
					'ent_code'               => $ent_code,
					'ent_name'               => $ent_name,
					'ent_document'           => $ent_document,
					'ent_document_number'    => $ent_document_number,
					'ent_email'              => $ent_email,
					'ent_website_url'        => $ent_website_url,
					'ent_cancel_password'    => $ent_cancel_password,
					'ent_discount_password'  => $ent_discount_password,
					'ent_statistic_password' => $ent_statistic_password,
					'ent_folder_name'        => $ent_folder_name
				];

				// Admin extra fields
				if ($requested === "admin") {
					$fields['ent_online_billing_status'] = $ent_online_billing_status;
					$fields['ent_plan_id'] = $ent_plan_id;
					$fields['ent_notification_text'] = $ent_notification_text;
				}

				// Build dynamic INSERT
				$columns = implode(',', array_keys($fields));
				$placeholders = ':' . implode(',:', array_keys($fields));

				$sql = "INSERT INTO tb_enterprises ($columns) VALUES ($placeholders)";
				$stmt = $pdo->prepare($sql);
				$stmt->execute($fields);

				$ent_id = $pdo->lastInsertId();

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

					$maxSize = 2 * 1024 * 1024; // 2MB
					if ($_FILES["ent_logo"]["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["ent_logo"]["tmp_name"];
					$fileName = "enterprise_{$ent_id}";
					$resCloudUpload = fnUploadToCloudinary($sourceFilePath, $saveToFolder, "image", $fileName);

					$imageUrl = $resCloudUpload['secure_url'];

					$sql = "UPDATE tb_enterprises 
					SET ent_logo = :ent_logo 
					WHERE ent_id = :ent_id";

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

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

				$entInfo = getEnterpriseData($ent_id);
				$imageUrl = $entInfo['ent_logo'];

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

					$maxSize = 2 * 1024 * 1024; // 2MB
					if ($_FILES["ent_logo"]["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["ent_logo"]["tmp_name"];
					$fileName = "enterprise_{$ent_id}";
					$resCloudUpload = fnUploadToCloudinary($sourceFilePath, $saveToFolder, "image", $fileName);

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

				// Base fields
				$fields = [
					'ent_name'               => $ent_name,
					'ent_document'           => $ent_document,
					'ent_document_number'    => $ent_document_number,
					'ent_email'              => $ent_email,
					'ent_website_url'        => $ent_website_url,
					'ent_logo'               => $imageUrl,
					'ent_cancel_password'    => $ent_cancel_password,
					'ent_discount_password'  => $ent_discount_password,
					'ent_statistic_password' => $ent_statistic_password,
					'ent_id'                 => $ent_id
				];

				if ($requested === "admin") {
					$fields['ent_online_billing_status'] = $ent_online_billing_status;
					$fields['ent_plan_id'] = $ent_plan_id;
					$fields['ent_notification_text'] = $ent_notification_text;
				}

				// Build dynamic UPDATE
				$setParts = [];
				foreach ($fields as $key => $value) {
					if ($key !== 'ent_id') {
						$setParts[] = "$key = :$key";
					}
				}

				$sql = "UPDATE tb_enterprises SET " . implode(',', $setParts) . " WHERE ent_id = :ent_id";

				$stmt = $pdo->prepare($sql);
				$stmt->execute($fields);

				$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 'ajax_show':
		$ent_id = isset($_POST["ent_id"]) ? funCheckInput($_POST["ent_id"]) : "";
		$sql = "SELECT * FROM tb_enterprises WHERE ent_id = '$ent_id';";
		$result = executePDOFetchOne($sql, $translate['could_not_show_data']);
		echo json_encode($result);
		break;


	case 'ajax_show_notification_status':

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

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

		break;


	case 'ajaxSwitchEmailReportStatus':

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

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

		break;


	case 'ajaxSwitchStatus':

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

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

		break;


	case 'ajaxEntContractStatus':

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

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

		break;


	case 'ajaxEnterpriseList':

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

		$sql = "SELECT * FROM tb_enterprises WHERE ent_status = '{$ent_status}' ORDER BY ent_id DESC;";
		// exit($sql);
		$rows = executePDOFetchAllAPI($sql);
		echo json_encode($rows);

		break;


	case 'ajaxGetEnterpriseData':

		$ent_id = isset($_GET["ent_id"]) ? funCheckInput($_GET["ent_id"]) : "";
		$entInfo = getEnterpriseData($ent_id);
		echo json_encode($entInfo);

		break;


	case 'ajaxShowEnterprisePasswords':

		$ent_id = $_SESSION["user_ent_id"];
		$entInfo = getEnterpriseData($ent_id);
		echo json_encode($entInfo);

		break;


	case 'ajaxResetAllPasswords':
		$ent_id = $_SESSION["user_ent_id"];
		fnGenerateNewCancelPassword($ent_id);
		fnGenerateNewDiscountPassword($ent_id);
		fnGenerateNewStatisticPassword($ent_id);
		break;


	case 'ajaxGenerateNewCancelPassword':
		$entId = isset($_POST["entId"]) ? funCheckInput($_POST["entId"]) : "";
		fnGenerateNewCancelPassword($entId);
		break;


	case 'ajaxGenerateNewDiscountPassword':
		$entId = isset($_POST["entId"]) ? funCheckInput($_POST["entId"]) : "";
		fnGenerateNewDiscountPassword($entId);
		break;


	case 'ajaxGenerateNewStatisticPassword':
		$entId = isset($_POST["entId"]) ? funCheckInput($_POST["entId"]) : "";
		fnGenerateNewStatisticPassword($entId);
		break;
}
