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

switch ($_GET["op"]) {

	case 'ajaxSaveUpdate':

		// POST VARIABLES
		$exp_id = isset($_POST["exp_id"]) ? funCheckInput($_POST["exp_id"]) : "";
		$exp_ent_id = isset($_POST["exp_ent_id"]) ? funCheckInput($_POST["exp_ent_id"]) : "";
		$exp_pos_id = isset($_POST["exp_pos_id"]) ? funCheckInput($_POST["exp_pos_id"]) : "";
		$exp_date =  isset($_POST["exp_date"]) ? funCheckInput($_POST["exp_date"]) : "";
		$exp_type =  isset($_POST["exp_type"]) ? funCheckInput($_POST["exp_type"]) : "";
		$exp_total = isset($_POST["exp_total"]) ? funCheckInput($_POST["exp_total"]) : "";

		if ($exp_ent_id == "") $exp_ent_id = $session_user_ent_id;
		if ($exp_pos_id == "") $exp_pos_id = $session_user_pos_id;

		if (empty($exp_date)) {
			$exp_date_time = $currentDateTimeByZone;
		} else {
			$exp_date_time = "{$exp_date} {$currentTime}";
		}

		try {

			$pdo->beginTransaction();

			// =========================
			// SAVE EXPENSE (MASTER)
			// =========================
			$isNew = empty(trim($exp_id));

			if ($isNew) {

				$sql = "INSERT INTO tb_expenses 
					(exp_ent_id, exp_pos_id, exp_date, exp_type, exp_total, exp_created_by)
					VALUES (:ent_id, :pos_id, :date, :type, :total, :created_by)";

				$stmt = $pdo->prepare($sql);
				$stmt->execute([
					':ent_id'    => $exp_ent_id,
					':pos_id'    => $exp_pos_id,
					':date'      => $exp_date_time,
					':type'      => $exp_type,
					':total'     => $exp_total,
					':created_by' => $session_user_id
				]);

				$exp_id = $pdo->lastInsertId();

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

				$sql = "UPDATE tb_expenses 
						SET exp_date = :date, exp_type = :type, exp_total = :total 
						WHERE exp_id = :exp_id";

				$stmt = $pdo->prepare($sql);
				$stmt->execute([
					':date'   => $exp_date_time,
					':type'   => $exp_type,
					':total'  => $exp_total,
					':exp_id' => $exp_id
				]);

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

			/*=============================================
			SAVE EXPENSE DETAILS
			=============================================*/
			$totalRows = count($_POST['exp_det_description']);

			$sqlDetailsBase = "INSERT INTO tb_expenses_details (
			exp_det_ent_id,
			exp_det_pos_id,
			exp_det_exp_id,
			exp_det_exp_date,
			exp_det_type,
			exp_det_description,
			exp_det_cost ) VALUES ";

			$detailsField = [];
			$paramsValueDetails = [];

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

				$detailsField[] = "(
					:exp_det_ent_id_$row,
					:exp_det_pos_id_$row,
					:exp_det_exp_id_$row,
					:exp_det_exp_date_$row,
					:exp_det_type_$row,
					:exp_det_description_$row,
					:exp_det_cost_$row
                )";

				$paramsValueDetails[":exp_det_ent_id_$row"]       = $exp_ent_id;
				$paramsValueDetails[":exp_det_pos_id_$row"]       = $exp_pos_id;
				$paramsValueDetails[":exp_det_exp_id_$row"]       = $exp_id;
				$paramsValueDetails[":exp_det_exp_date_$row"]     = $exp_date_time;
				$paramsValueDetails[":exp_det_type_$row"]     	  = $exp_type;
				$paramsValueDetails[":exp_det_description_$row"]  = funCheckInput($_POST['exp_det_description'][$row]);
				$paramsValueDetails[":exp_det_cost_$row"]         = funCheckInput($_POST['exp_det_cost'][$row]);
			}

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

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

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

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

		$ent_id = isset($_GET["ent_id"]) ? funCheckInput($_GET["ent_id"]) : "";
		$pos_id = isset($_GET["pos_id"]) ? funCheckInput($_GET["pos_id"]) : "";
		$dateFrom = isset($_GET["fromDate"]) ? funCheckInput($_GET["fromDate"]) : "";
		$dateTo = isset($_GET["toDate"]) ? funCheckInput($_GET["toDate"]) : "";
		$expType = isset($_GET["exp_type"]) ? funCheckInput($_GET["exp_type"]) : "";

		$fromDate = date("{$dateFrom} 07:00:00");
		$toDate = date("Y-m-d", strtotime("{$dateTo} +1 day")) . " 06:59:59";

		$whereDate = "WHERE DATE_FORMAT(exp_date, '%Y-%m-%d %H:%i:%s') BETWEEN '{$currentDayStart}' AND '{$currentDayEnd}'";
		if (!empty($dateFrom)) $whereDate = "AND DATE_FORMAT(exp_date, '%Y-%m-%d %H:%i:%s') BETWEEN '{$fromDate}' AND '{$toDate}'";

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

		$whereType = "AND exp_type = 'Daily'";
		if (!empty($pos_id)) $whereType = "AND exp_type = '{$expType}'";

		$sql = "SELECT
			exp_id
			,exp_ent_id
			,exp_pos_id
			,(select pos_name FROM tb_pos WHERE pos_id = exp_pos_id) AS pos_name
			,(select pos_currency FROM tb_pos WHERE pos_id = exp_pos_id) AS pos_currency
			,DATE_FORMAT(exp_date, '%Y-%m-%d') AS exp_date
			,DATE_FORMAT(exp_date, '%d-%b-%Y %H:%i:%s') AS exp_date_formated
			,exp_type
			,(SELECT GROUP_CONCAT(`exp_det_description` separator ' , ') FROM tb_expenses_details WHERE exp_det_exp_id = exp_id) AS general_description			
			,IFNULL(exp_total,0) AS exp_total
			FROM tb_expenses
			WHERE exp_ent_id = {$ent_id}
			$whereDate $wherePos $whereType;";

		// exit($sql);

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

		break;


	case 'ajaxShowExpenseDetails':
		$exp_id = isset($_GET["exp_id"]) ? funCheckInput($_GET["exp_id"]) : "";

		if (!empty(trim((string) $exp_id))) {
			$sqlGetExpenseDetails = "SELECT * FROM tb_expenses_details WHERE exp_det_exp_id = '{$exp_id}'";
			$resGetExpenseDetails = executePDOFetchAllAPI($sqlGetExpenseDetails);
			echo json_encode($resGetExpenseDetails);
		} else {
			echo json_encode(array('status' => 'error', 'message' => 'Empty ID value was sent'));
		}
		break;


	case 'ajax_delete_item':

		$exp_id = isset($_POST["id"]) ? funCheckInput($_POST["id"]) : "";
		$reason = isset($_POST["reason"]) ? funCheckInput($_POST["reason"]) : "";

		if (!empty($exp_id)) {

			$sqlExpenseInfo = "SELECT
			exp_id
			,exp_ent_id
			,exp_pos_id
			,(SELECT pos_name FROM tb_pos WHERE pos_id = exp_pos_id) AS pos_name
			,exp_type
			,IFNULL(exp_total,0) AS final_exp_total
			FROM tb_expenses
			WHERE exp_id = {$exp_id};";

			$expInfo = executePDOFetchOne($sqlExpenseInfo);

			$sql = "DELETE FROM tb_expenses WHERE exp_id ='{$exp_id}'";
			$result = executeQueryPDO($sql, 'success', 'error');

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

				$type = $posTranslate['fixed'];
				if ($expInfo['exp_type'] == "Daily") $type = $posTranslate['daily'];
				if ($posLang == "fr") $type = $posTranslate['daily_f'];

				$final_exp_total = number_format($expInfo['final_exp_total'], 2);

				$log_description = "{$posTranslate['the_user']}: {$session_user_fullname} (ID:{$session_user_id}) {$posTranslate['has_eliminated_an_expense']} {$type} (ID:{$expInfo['exp_id']}), {$posTranslate['of_the_pos']} {$expInfo['pos_name']} (ID:{$expInfo['exp_pos_id']}), {$posTranslate['for_a_total_of']} {$final_exp_total} {$posTranslate['the_reason_given_is']}: {$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($expInfo['exp_ent_id'], $expInfo['exp_pos_id'], $session_user_id, $log_description, $currentDateTimeByZone);
				}
				// sendEmail($emailSender,$emailSenderName,$emailSubject,$emailReciver,$emailReciverName,$log_description);
				$response = array('title' => "{$translate['successfully_deleted']}", '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;
}
