<?php

// --- Database Configuration ---
$host = "localhost";
$dbName = "digitalb_beaccurate";
$userName = "digitalb_beaccurate";
$pass = "Saiful.1633"; // WARNING: Hardcoding passwords is insecure. Consider environment variables or config files.
$tableName = "MetaData";
$metaKeyToUpdate = "App Open"; // The specific meta_key we want to update

// --- Establish Database Connection ---
// Use mysqli extension (recommended over the old mysql_* functions)
$conn = mysqli_connect($host, $userName, $pass, $dbName);

// Check connection
if (!$conn) {
    // Log the detailed error for server admins, show a generic message to users
    error_log("Database Connection Error: " . mysqli_connect_error());
    die("Connection failed. Please try again later."); // Use die() to stop script execution
}

// --- Prepare the SQL Update Statement ---
// Using SQL's ability to increment directly is efficient and avoids race conditions.
// Make sure meta_value is an integer type (INT, BIGINT, etc.) in your database.
$sql = "UPDATE `" . $tableName . "` 
        SET `meta_value` = `meta_value` + 1 
        WHERE `meta_key` = ?"; // Use a placeholder for the key

// --- Prepare and Bind ---
// Using prepared statements is safer against SQL injection, even if the key is hardcoded here.
$stmt = mysqli_prepare($conn, $sql);

if ($stmt) {
    // Bind the parameter (s = string type)
    mysqli_stmt_bind_param($stmt, "s", $metaKeyToUpdate);

    // --- Execute the Statement ---
    if (mysqli_stmt_execute($stmt)) {
        // Check how many rows were actually affected
        $affected_rows = mysqli_stmt_affected_rows($stmt);

        if ($affected_rows > 0) {
            echo "Success: '" . htmlspecialchars($metaKeyToUpdate) . "' count incremented successfully.";
        } else {
            // This means the query ran okay, but no row matched the WHERE clause
            echo "Notice: No row found with meta_key = '" . htmlspecialchars($metaKeyToUpdate) . "'. No value was updated.";
            // You might want to consider INSERTING the row if it doesn't exist,
            // depending on your application's logic. Example (add this logic if needed):
            // $insertSql = "INSERT INTO `$tableName` (meta_key, meta_value) VALUES (?, 1) ON DUPLICATE KEY UPDATE meta_value = meta_value + 1";
            // ... (re-prepare and execute with $insertSql) ...
        }
    } else {
        // Execution failed
        error_log("Error executing update statement: " . mysqli_stmt_error($stmt));
        echo "Error: Could not update the database.";
    }

    // Close the statement
    mysqli_stmt_close($stmt);

} else {
    // Statement preparation failed
    error_log("Error preparing update statement: " . mysqli_error($conn));
    echo "Error: Could not prepare the database update.";
}


// --- Close Database Connection ---
mysqli_close($conn);

?>