<?php

set_time_limit(0);
require_once("includes/config.php");
$conn = new mysqli($host, $username, $password, $dbname);

if ($conn->connect_error) {		
    die("");
}

$user_id =45000; 
$shopifyShopUrl ='';
$accessToken ='';
$userQuery = "SELECT shopurl, token FROM users WHERE id = $user_id ";
$userResult = $conn->query($userQuery);

if ($userResult->num_rows > 0) {
    $userData = $userResult->fetch_assoc();
    $shopifyShopUrl = $userData['shopurl'];
    $accessToken = $userData['token'];


$productIds = [];
$productQuery = "select * from products  where user_id = 45000  and status='imported' order by shopifyproductid  desc limit 100";
// $productQuery = " select * from shopifyproducts where user_id = 48019 and productid not  in (select shopifyproductid from products where user_id = 48019)";
$productResult = $conn->query($productQuery);

if ($productResult->num_rows > 0) {
    while ($row = $productResult->fetch_assoc()) {
        $shopifyProductId =$row['shopifyproductid'];
        $globalId = "gid://shopify/Product/" . $shopifyProductId;
        $productIds[] = $globalId;
    }
    print_r($productIds);
foreach ($productIds as $productId) {
    $query = <<<GRAPHQL
    mutation {
        productDelete(input: {id: "$productId"}) {
            deletedProductId
            userErrors {
                field
                message
            }
        }
    }
    GRAPHQL;

    $response = makeGraphQLRequest($shopifyShopUrl, $accessToken, $query);

    if (isset($response['error'])) {
        echo "HTTP Error: {$response['error']}\n 00000";
        continue;
    }

    if (isset($response['data']['productDelete']['deletedProductId'])) {
        echo "Product with ID {$response['data']['productDelete']['deletedProductId']} deleted successfully.\n";
    } else {
        $errors = $response['data']['productDelete']['userErrors'] ?? [['message' => 'Unknown error']];
        foreach ($errors as $error) {
            echo "Error deleting product: {$error['message']}\n";
        }
    }
}
}
}

function makeGraphQLRequest($shopifyShopUrl, $accessToken, $query) {
    $url = "https://$shopifyShopUrl/admin/api/2024-10/graphql.json";
    
    $headers = [
        "Content-Type: application/json",
        "X-Shopify-Access-Token: $accessToken",
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['query' => $query]));

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpCode !== 200) {
        return ['error' => "HTTP error code: $httpCode", 'response' => $response];
    }

    return json_decode($response, true);
}



$conn->close();

?>
