<?php
require_once("dbconn.php");

function executeQuery($conn, $query, $types = null, $params = null) {
    $stmt = $conn->prepare($query);
    if ($stmt === false) {
        error_log("Prepare failed: (" . $conn->errno . ") " . $conn->error);
        return false;
    }

    if ($types !== null && $params !== null) {
        $stmt->bind_param($types, ...$params);
    }

    $success = $stmt->execute();
    if (!$success) {
        error_log("Execute failed: (" . $stmt->errno . ") " . $stmt->error);
        return false;
    }

    if (strpos($query, "SELECT") === 0) {
        $result = $stmt->get_result();
        if ($result === false) {
            error_log("Get result failed: (" . $stmt->errno . ") " . $stmt->error);
            return false;
        }
        $stmt->close();
        return $result;
    } else {
        $affected_rows = $stmt->affected_rows;
        $stmt->close();
        return $affected_rows;
    }
}

function getDataFromPost($keys, $post) {
    $data = [];
    foreach ($keys as $key) 
	{
		$data[$key] = $post[$key];
    }
    return sanitizeAndValidate($data);
}

function sanitizeAndValidate($data) {
    $sanitizedData = [];
    foreach ($data as $key => $value) {
        $value = trim($value);
        $value = stripslashes($value);
        $value = htmlspecialchars_decode($value, ENT_QUOTES);

        $sanitizedData[$key] = $value;
    }
    return $sanitizedData;
}

function fetchOriginalData($conn, $id) {
    $userType = isset($_SESSION["type"]) ? $_SESSION["type"] : null;
    $superUser = isset($_SESSION["superUser"]) ? $_SESSION["superUser"] : null;

    if (isset($_GET["p"])) {
		$page = $_GET["p"];

		if ($page === "es") {
			$dbTable = "egg_standards";
		} elseif ($userType === 2 || isset($superUser)) {
			$dbTable = ($page === "ipep") ? "predata_ip" : 
					   (($page === "ipes") ? "predata_ew" : 
					   (($page === "ipfd") ? "predata_fd" : 
					   (($page === "iptemp") ? "predata_temp" : "table-error")));
		} elseif ($userType === 1 || $userType === 3) {
			$dbTable = ($page === "ipep") ? "input_production" : 
					   (($page === "ipes") ? "egg_weight" : 
					   (($page === "ipfd") ? "feed_delivery" : 
					   (($page === "iptemp") ? "input_temp" : "table-error")));
		} else {
			$dbTable = "table-error";
		}
	} else {
		$dbTable = "table-error";
	}

    $query = "SELECT * FROM {$dbTable} WHERE id = ?";
    $stmt = mysqli_prepare($conn, $query);
    if ($stmt === false) {
        throw new Exception("Failed to prepare statement: " . $conn->error);
    }

    mysqli_stmt_bind_param($stmt, "i", $id);
    $executeResult = mysqli_stmt_execute($stmt);
    if ($executeResult === false) {
        mysqli_stmt_close($stmt);
        throw new Exception("Failed to execute statement: " . $conn->error);
    }

    $result = mysqli_stmt_get_result($stmt);
    if ($result === false) {
        mysqli_stmt_close($stmt);
        throw new Exception("Failed to get result: " . $conn->error);
    }

    $data = mysqli_fetch_assoc($result);
    mysqli_stmt_close($stmt);

    return $data;
}

function hasChanges($originalData, $newData) {
    foreach ($newData as $key => $value) {
        $originalKey = preg_replace('/_\d+$/', '', $key);

        if (!array_key_exists($originalKey, $originalData)) {
            continue; 
        }

        $originalValue = trim($originalData[$originalKey]);
        $newValue = trim($value);

        if ($originalValue !== $newValue) {
            return true; 
        }
    }
    return false; 
}

function getBatchNameOptions($conn,$status=null) {
	if ($status !== "All") { 
		$result = executeQuery($conn, "SELECT DISTINCT BatchName FROM batch_details WHERE Status = 1 AND is_deleted = FALSE AND is_current = TRUE ORDER BY CheckInDate");
	} else {
		$result = executeQuery($conn, "SELECT DISTINCT BatchName FROM batch_details WHERE is_deleted = FALSE AND is_current = TRUE ORDER BY CheckInDate");
	}
	
	if ($result === false) { 
		throw new Exception("Error executing query: " . $conn->error);
	} 

	$options = '<option value="" disabled selected>SELECT</option>';
	
    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
			$options .= '<option value="' . $row['BatchName'] . '">' . $row['BatchName'] . '</option>';
        }
    }

    return $options;
}

function getBreedTypeOptions($conn) {
    $result = executeQuery($conn, "SELECT DISTINCT BreedType FROM egg_standards WHERE is_deleted = FALSE AND is_current = TRUE");
	
	if ($result === false) { 
		throw new Exception("Error executing query: " . $conn->error);
	} 

	$options = '<option value="" disabled selected>SELECT</option>';

    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
			$options .= '<option value="' . $row['BreedType'] . '">' . $row['BreedType'] . '</option>';
        }
    }

    return $options;
}

function getCustomerNames($conn) {
    $result = executeQuery($conn, "SELECT customer_name FROM customer_names WHERE is_deleted = FALSE");
    
    if ($result === false) { 
        throw new Exception("Error executing query: " . $conn->error);
    } 

    $options = '<option value="" disabled selected>SELECT</option>';

	if ($result->num_rows > 0) {
		while($row = $result->fetch_assoc()) {
			$options .= '<option value="' . $row['customer_name'] . '">' . $row['customer_name'] . '</option>';
		}
	}

    return $options;
}

function generateDRNumber($conn) {
    $id = 1;
	$dr_number = "DR-" . date("Ymd") . "-" . $id;

    do {
		$result = executeQuery($conn, "SELECT COUNT(*) as count FROM transactions WHERE dr_number = ?", "s", [$dr_number]);
		
		if ($result === false) { 
			throw new Exception("Error executing query: " . $conn->error);
		} 
		
        $row = $result->fetch_assoc();
        $count = $row["count"];

        if ($count > 0) {
            $id++;
			$dr_number = "DR-" . date("Ymd") . "-" . $id;
        }
    } while ($count > 0);

    return $dr_number;
}

function numberFormatPrecision($number, $precision = 2, $separator = '.')
{
    $numberParts = explode($separator, $number);
    $response = $numberParts[0];
    if (count($numberParts)>1 && $precision > 0) {
        $response .= $separator;
        $response .= substr($numberParts[1], 0, $precision);
    }
    return $response;
}
?>