<?php
require "global.ajax.php";

switch ($_GET["op"]) {

	case 'ajaxSaveUpdate':

		// POST VARIABLES
		$pur_id = isset($_POST["pur_id"]) ? funCheckInput($_POST["pur_id"]) : "";
		$pur_ent_id = isset($_POST["pur_ent_id"]) ? funCheckInput($_POST["pur_ent_id"]) : "";
		$pur_pos_id = isset($_POST["pur_pos_id"]) ? funCheckInput($_POST["pur_pos_id"]) : "";
		$pur_provider_id = isset($_POST["pur_provider_id"]) ? funCheckInput($_POST["pur_provider_id"]) : "";
		$pur_date = isset($_POST["pur_date"]) ? funCheckInput($_POST["pur_date"]) : "";
		$pur_cost = isset($_POST["pur_cost"]) ? funCheckInput($_POST["pur_cost"]) : "";
		$pur_shipping = isset($_POST["pur_shipping"]) ? funCheckInput($_POST["pur_shipping"]) : "";
		$pur_created_by = isset($_POST["pur_created_by"]) ? funCheckInput($_POST["pur_created_by"]) : "";

		if ($pur_ent_id == "") $pur_ent_id = $session_user_ent_id;
		if ($pur_pos_id == "") $pur_pos_id = $session_user_pos_id;

		if (empty($pur_date)) {
			$pur_date_time = $currentDateTimeByZone;
		} else {
			$pur_date_time = "{$pur_date} {$currentTimeByZone}";
		}

		try {

			$pdo->beginTransaction();

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

			if ($isNew) {

				$pur_code = createTokenNumber('tb_purchases', 'pur_code', '8');

				$stmt = $pdo->prepare("INSERT INTO tb_purchases (
				pur_code, pur_ent_id, pur_pos_id, pur_provider_id,
				pur_date, pur_cost, pur_shipping, pur_created_by
				) VALUES (
				:code, :ent_id, :pos_id, :provider_id,
				:date, :cost, :shipping, :user_id)
				");

				$stmt->execute([
					':code' => $pur_code,
					':ent_id' => $pur_ent_id,
					':pos_id' => $pur_pos_id,
					':provider_id' => $pur_provider_id,
					':date' => $pur_date_time,
					':cost' => $pur_cost,
					':shipping' => $pur_shipping,
					':user_id' => $session_user_id
				]);

				$pur_id = $pdo->lastInsertId();

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

				$stmt = $pdo->prepare("UPDATE tb_purchases SET
				pur_date = :date,
				pur_provider_id = :provider_id,
				pur_cost = :cost,
				pur_shipping = :shipping,
				pur_edited_by = :user_id
				WHERE pur_id = :pur_id
				");

				$stmt->execute([
					':date' => $pur_date_time,
					':provider_id' => $pur_provider_id,
					':cost' => $pur_cost,
					':shipping' => $pur_shipping,
					':user_id' => $session_user_id,
					':pur_id' => $pur_id
				]);

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

			$purchase_info = getPurchaseData($pur_id);

			if ($purchase_info['status'] == 'success') {
				$pur_code = $purchase_info['data']['pur_code'];
			} else {
				$response = array("status" => "error", "message" => "{$translate['data_could_not_be_saved']}");
				echo json_encode($response);
				exit();
			}

			/*=============================================
			INSERT DETAILS + UPDATE PRODUCTS
			=============================================*/
			$totalRows = count($_POST['pur_det_pro_id']);

			$sqlDetailsBase = "INSERT INTO tb_purchases_details (
				pur_det_ent_id, pur_det_pos_id, pur_det_pur_id,
				pur_det_code, pur_det_pur_date,
				pur_det_pro_id, pur_det_cat_id, pur_det_pro_code,
				pur_det_pro_cost, pur_det_pro_price,
				pur_det_pro_qty, pur_det_total
			) VALUES ";

			$stmtUpdateProduct = $pdo->prepare("
				UPDATE tb_products SET
				pro_cost 		= :cost,
				pro_price 		= :price,
				pro_price_party = :price_party
				WHERE pro_id 	= :pro_id
			");

			$detailsField = [];
			$paramsValueDetails = [];
			$productUpdates = []; // Collect product update data

			for ($row = 0; $row < $totalRows; $row++) {

				$detailsField[] = "(
					:pur_det_ent_id_$row,
					:pur_det_pos_id_$row,
					:pur_det_pur_id_$row,
					:pur_det_code_$row,
					:pur_det_pur_date_$row,
					:pur_det_pro_id_$row,
					:pur_det_cat_id_$row,
					:pur_det_pro_code_$row,
					:pur_det_pro_cost_$row,
					:pur_det_pro_price_$row,
					:pur_det_pro_qty_$row,
					:pur_det_total_$row
				)";

				$paramsValueDetails[":pur_det_ent_id_$row"]    = $pur_ent_id;
				$paramsValueDetails[":pur_det_pos_id_$row"]    = $pur_pos_id;
				$paramsValueDetails[":pur_det_pur_id_$row"]    = $pur_id;
				$paramsValueDetails[":pur_det_code_$row"]      = $pur_code;
				$paramsValueDetails[":pur_det_pur_date_$row"]  = $pur_date_time;
				$paramsValueDetails[":pur_det_pro_id_$row"]    = funCheckInput($_POST['pur_det_pro_id'][$row]);
				$paramsValueDetails[":pur_det_cat_id_$row"]    = funCheckInput($_POST['pur_det_cat_id'][$row]);
				$paramsValueDetails[":pur_det_pro_code_$row"]  = funCheckInput($_POST['pur_det_pro_code'][$row]);
				$paramsValueDetails[":pur_det_pro_cost_$row"]  = funCheckInput($_POST['pur_det_pro_cost'][$row]);
				$paramsValueDetails[":pur_det_pro_price_$row"] = funCheckInput($_POST['pur_det_pro_price'][$row]);
				$paramsValueDetails[":pur_det_pro_qty_$row"]   = funCheckInput($_POST['pur_det_pro_qty'][$row]);
				$paramsValueDetails[":pur_det_total_$row"]     = funCheckInput($_POST['pur_det_total'][$row]);

				// Collect product update data
				$productUpdates[] = [
					':cost'   			=> funCheckInput($_POST['pur_det_pro_cost'][$row]),
					':price'  			=> funCheckInput($_POST['pur_det_pro_price'][$row]),
					':price_party'  	=> funCheckInput($_POST['pur_det_pro_price'][$row]),
					':pro_id' 			=> funCheckInput($_POST['pur_det_pro_id'][$row])
				];
			}

			/*=============================================
			DELETE OLD DETAILS
			=============================================*/
			if (!$isNew) {
				$pdo->prepare("DELETE FROM tb_purchases_details WHERE pur_det_pur_id = :id")
					->execute([':id' => $pur_id]);
			}

			$sqlDetails = $sqlDetailsBase . implode(',', $detailsField);

			// Insert data to tb_purchases_details
			$pdo->prepare($sqlDetails)->execute($paramsValueDetails);

			// Execute all product updates outside the loop
			foreach ($productUpdates as $updateData) {
				$stmtUpdateProduct->execute($updateData);
			}

			$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 'ajaxPurchasesList':

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

		$wherePos = "AND pur_pos_id = {$session_user_pos_id}";
		if (!empty($pos_id)) $wherePos = "AND pur_pos_id = {$pos_id}";

		$whereDate = "WHERE DATE_FORMAT(pur_date, '%Y-%m-%d') BETWEEN '{$last7Days}' AND '{$todayDate}'";
		if (!empty($toDate)) $whereDate = "AND DATE_FORMAT(pur_date, '%Y-%m-%d') BETWEEN '{$fromDate}' AND '{$toDate}'";

		$sql = "SELECT
		pur_id
		,pur_ent_id
		,pur_pos_id
		,DATE_FORMAT(pur_date, '%Y-%m-%d') AS pur_date
		,DATE_FORMAT(pur_date, '%d-%b-%Y %H:%i:%s') AS pur_date_formated
		,(select pos_name FROM tb_pos WHERE pos_id = pur_pos_id) AS pos_name
		,(select prov_name FROM tb_providers WHERE prov_id = pur_provider_id) AS provider_name
		,(select CONCAT(user_firstname,' ',user_lastname) FROM tb_users WHERE user_id = pur_created_by) AS createdBy
		,pur_provider_id
		,pur_shipping
		,pur_cost
		,pur_status
		,SUM(pur_det_pro_price*pur_det_pro_qty) AS total_precio_venta
		,SUM(pur_det_pro_price*pur_det_pro_qty)-(pur_cost) AS total_ganancia
		FROM tb_purchases
		LEFT JOIN tb_purchases_details ON  pur_det_pur_id = pur_id
		WHERE pur_ent_id = '{$ent_id}' AND pur_status = '{$status}' $wherePos $whereDate
		GROUP BY pur_id ORDER BY pur_id DESC;";

		// exit($sql);

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

		break;


	case 'ajaxShowPurchaseDetails':
		$pur_id = isset($_GET["pur_id"]) ? funCheckInput($_GET["pur_id"]) : "";

		if (!empty(trim((string) $pur_id))) {
			$sqlGetExpenseDetails = "SELECT *,(select pro_description FROM tb_products WHERE pro_id = pur_det_pro_id) AS pro_description FROM tb_purchases_details WHERE pur_det_pur_id = '{$pur_id}'";
			$resGetExpenseDetails = executePDOFetchAllAPI($sqlGetExpenseDetails);
			echo json_encode($resGetExpenseDetails);
		} else {
			echo json_encode(array('status' => 'error', 'message' => 'Empty ID value was sent'));
		}
		break;


	case 'ajaxCancelData':

		$transaction_id = isset($_POST["transaction_id"]) ? funCheckInput($_POST["transaction_id"]) : "";
		$transaction_reason = isset($_POST["transaction_reason"]) ? funCheckInput($_POST["transaction_reason"]) : "";

		$sqlPurchaseInfo = "SELECT
		pur_id
		,pur_ent_id
		,pur_pos_id
		,(SELECT pos_name FROM tb_pos WHERE pos_id = pur_pos_id) AS pos_name
		,(SELECT pos_currency FROM tb_pos WHERE pos_id = pur_pos_id) AS pos_currency
		,IFNULL(pur_cost,0) AS pur_total_cost
		FROM tb_purchases
		WHERE pur_id = {$transaction_id};";
		$purInfo = executePDOFetchOne($sqlPurchaseInfo);

		$sql = "UPDATE tb_purchases SET pur_status = 'Disabled' WHERE pur_id ='{$transaction_id}';
		UPDATE tb_purchases_details SET pur_det_status = 'Disabled' WHERE pur_det_pur_id ='{$transaction_id}';";
		$result = executeQueryPDO($sql, 'success', 'error');

		if ($result['status'] == "success") {

			$pur_total_cost = number_format($purInfo['pur_total_cost'], 2);

			$log_description = "{$session_user_fullname} ID:{$session_user_id}, {$posTranslate['canceled_a_purchase']} (ID:{$purInfo['pur_id']}), {$posTranslate['of_the_pos']} {$purInfo['pur_pos_id']}-{$purInfo['pos_name']}, {$posTranslate['for_a_total_of']} {$purInfo['pos_currency']} {$pur_total_cost} {$posTranslate['the_reason_given_is']}: {$transaction_reason}.";

			fnGenerateNewCancelPassword($session_user_ent_id);

			if ($session_user_profile == "ROOT") {
				$saveLogs = saveLog($session_user_ent_id, $session_user_pos_id, $session_user_id, $log_description, $currentDateTimeByZone);
			} else {
				$saveLogs = saveLog($purInfo['pur_ent_id'], $purInfo['pur_pos_id'], $session_user_id, $log_description, $currentDateTimeByZone);
			}
			// sendEmail($emailSender,$emailSenderName,$emailSubject,$emailReciver,$emailReciverName,$log_description);
			$response = array('title' => "{$translate['canceled_successfully']}", 'message' => "{$translate['this_action_has_been_registered_in_the_audit_system_for_control_purposes']}", 'type' => 'success');
		} else {
			$response = array('message' => $translate['execution_failed'], 'type' => 'error');
		}
		echo json_encode($response);

		break;
}
