<?php
error_reporting(E_ALL);

// Errors ko display karein
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);


date_default_timezone_set('Asia/Kolkata');
require_once('dbconfig.php');

try {
    $conn = new PDO("$driver:host=$servername;dbname=".$dbname, $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_BOTH);
    $wsql = $conn->prepare("select * from settings WHERE weburl = ?");
    $wsql->execute([$_SERVER['SERVER_NAME']]);
    $webdata=$wsql->fetch();

    // Fallback: If no settings found for this specific domain, fetch the first available settings (common for single setups)
    if (!$webdata) {
        $wsql = $conn->prepare("select * from settings LIMIT 1");
        $wsql->execute();
        $webdata = $wsql->fetch();
    }

    // Initialize objects with null checks to prevent errors
	$sms_obj = ($webdata && isset($webdata['smsapi'])) ? json_decode($webdata['smsapi']) : null;
	
	
    $msql = $conn->prepare("select * from settings WHERE id = ?");
    $msql->execute(['1']);
    $mw_data=$msql->fetch();
	$pg_obj = ($mw_data && isset($mw_data['pgapi'])) ? json_decode($mw_data['pgapi']) : null;

	
	$webname = ($webdata && isset($webdata['webname'])) ? $webdata['webname'] : 'UPI Gateway';
	$site_short = rtrim(preg_replace('#([^ ])[^ ]* *#i', '$1', $webname)," ");
	$order_id =rand(100000,999999);
    $pin_id =rand(1000,9999);
    $pay_id = "PY".rand(1000,9999);
    $date_time =date('Y-m-d', time());
    $date =date('m/d/Y', time());
    }
catch(PDOException $e)
    {
    echo "Connection failed: " . $e->getMessage();
    }

if (substr($_SERVER['SERVER_NAME'], 0, 4) === 'www.')
{
    header('Location: http://' . substr($_SERVER['SERVER_NAME'], 4)); exit();
}

//$api_key = $sms_obj->{'api_key'};
// $sms_username = $sms_obj->{'username'};
// $sms_password = $sms_obj->{'password'};
// $senderid = $sms_obj->{'senderid'};
//$route = $sms_obj->{'route'};

function SendSMS($sms_number,$msg){

$message = str_replace(' ', '%20',$msg);  
$url = "https://smsapi.rechpay.in/http-api.php?username=".$GLOBALS["sms_username"]."&password=".$GLOBALS["sms_password"]."&senderid=".$GLOBALS["senderid"]."&route=".$GLOBALS["route"]."&number=$sms_number&message=$message";
$response = file_get_contents($url);  
return $response;
}

function isIpBlocked($ip, $conn) {
    $stmt = $conn->prepare("SELECT ip_address FROM blocked_ips WHERE ip_address = ?");
    $stmt->execute([$ip]);
    return $stmt->fetch() ? true : false;
}

// Get user's IP address
$user_ip = $_SERVER['REMOTE_ADDR'];

// Check if IP is blocked
if (isIpBlocked($user_ip, $conn)) {
    // If IP is blocked, show an error message and stop further execution
    die("Access Denied:");
}

// Agar IP blocked nahi hai, toh normal site chalegi
//echo "Welcome to the site!";

?>