<?php
/* 
Auther: Subhash Shipu
*/
function callApi($url)
{
  // Initialize cURL session
  $ch = curl_init($url);

  // Set cURL options
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the response as a string
  curl_setopt($ch, CURLOPT_HTTPGET, true); // Use GET method
  // Execute the request
  $response = curl_exec($ch);

  // Check for errors
  if (curl_errno($ch)) {
    die('cURL error: ' . curl_error($ch));
  }

  // Close the cURL session
  curl_close($ch);

  // Decode the JSON response
  return json_decode($response);
}

function _p($a, $die = false)
{
  if (is_array($a) || is_object($a)) {
    echo "<pre>";
    print_r($a);
    echo "</pre>";
  } else {
    echo $a;
  }
  if ($die) {
    die();
  }
}

function qi($name)
{
  return '`' . str_replace('`', '``', $name) . '`';
}

/**
 * Check if a duplicate record exists in a table.
 *
 * @param string $table
 * @param array $conditions Key-value pairs for WHERE clause
 * @return bool true if duplicate exists, false otherwise
 */
function checkDuplicate(string $table, array $conditions): int
{
  global $conn;
  // Build WHERE clause dynamically
  $where = [];
  foreach ($conditions as $col => $val) {
    $where[] = "$col = :$col";
  }
  $whereSql = implode(" AND ", $where);

  $sql = "SELECT COUNT(*) FROM {$table} WHERE {$whereSql}";
  $stmt = $conn->prepare($sql);

  // Bind values safely
  foreach ($conditions as $col => $val) {
    $stmt->bindValue(":$col", $val);
  }

  $stmt->execute();
  return $stmt->fetchColumn();
}
