<?php
// Database Info
$host = "localhost";
$dbName = "digitalb_beaccurate";
$userName = "digitalb_beaccurate";
$pass = "Saiful.1633";

// Get the product ID from the request (e.g., from a GET or POST parameter)
// For demonstration purposes, let's assume it's passed as a GET parameter:
$product_id = isset($_GET['product_id']) ? $_GET['product_id'] : null;

if ($product_id === null) {
    echo "Product ID is required.";
    exit;
}

try {
    // Establish database connection using PDO
    $pdo = new PDO("mysql:host=$host;dbname=$dbName;charset=utf8", $userName, $pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // 1. Check if the product ID exists in the Products table
    $stmt_check = $pdo->prepare("SELECT ID FROM Products WHERE ID = :product_id");
    $stmt_check->bindParam(':product_id', $product_id, PDO::PARAM_INT);
    $stmt_check->execute();

    if ($stmt_check->rowCount() > 0) {
        // Product found, proceed with updates

        $pdo->beginTransaction(); // Start a transaction to ensure atomicity

        // 2. Update BoycottCount in the Products table
        $stmt_boycott_count = $pdo->prepare("UPDATE Products SET BoycottCount = BoycottCount + 1 WHERE ID = :product_id");
        $stmt_boycott_count->bindParam(':product_id', $product_id, PDO::PARAM_INT);
        $stmt_boycott_count->execute();

        // 3. Update Total Boycott Time in the MetaData table
        $stmt_meta = $pdo->prepare("UPDATE MetaData SET meta_value = meta_value + 1 WHERE meta_id = 1 AND meta_key = 'Totol Boycott Time'");
        $stmt_meta->execute();

        // Check the number of affected rows for the MetaData update (for debugging)
        $affectedRowsMeta = $stmt_meta->rowCount();
        if ($affectedRowsMeta > 0) {
            // echo "Total Boycott Time updated successfully.<br>"; // Optional success message
        } else {
            echo "Warning: Total Boycott Time was not updated. Please double-check meta_id and meta_key in the MetaData table.<br>";
        }

        $pdo->commit(); // Commit the transaction if both updates were successful

    } else {
        echo "Product id Not Found";
    }

} catch (PDOException $e) {
    if (isset($pdo) && $pdo->inTransaction()) {
        $pdo->rollBack(); // Rollback the transaction if any error occurred
    }
    http_response_code(500); // Set HTTP status code to 500 (Internal Server Error)
    echo "Error: " . $e->getMessage();
} finally {
    // Close the database connection
    $pdo = null;
}
?>