<?php 
	include "../../conn.php";
	include "../../functions2.php";
	
	header('Content-Type: application/json; charset=utf-8');
	header('Strict-Transport-Security: max-age=31536000');
	header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization');
	header('Access-Control-Allow-Credentials: true');
	$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
	header('Access-Control-Allow-Origin: ' . $origin);
	header('vary: Origin');
	
	date_default_timezone_set("Asia/Kolkata");
	$shnunc = date("Y-m-d H:i:s");
	$res = [
		'code' => 11,
		'msg' => 'Method not allowed',
		'msgCode' => 12,
		'serviceNowTime' => $shnunc,
	];
	$shonubody = file_get_contents("php://input");
	$shonupost = json_decode($shonubody, true);
	
	if ($_SERVER['REQUEST_METHOD'] != 'GET') {
		if (isset($shonupost['language']) && isset($shonupost['random']) && isset($shonupost['signature']) && isset($shonupost['timestamp'])) {
			$language = htmlspecialchars(mysqli_real_escape_string($conn, $shonupost['language']));
			$random = htmlspecialchars(mysqli_real_escape_string($conn, $shonupost['random']));
			$signature = htmlspecialchars(mysqli_real_escape_string($conn, $shonupost['signature']));
			$typeId = htmlspecialchars(mysqli_real_escape_string($conn, $shonupost['typeId']));
			$shonustr = '{"language":'.$language.',"random":"'.$random.'","typeId":'.$typeId.'}';
			$shonusign = strtoupper(md5($shonustr));
			if($shonusign == $signature){
				$bearer = explode(" ", $_SERVER['HTTP_AUTHORIZATION']);
				$author = $bearer[1];				
				$is_jwt_valid = is_jwt_valid($author);
				$data_auth = json_decode($is_jwt_valid, 1);
				if($data_auth['status'] === 'Success') {
					$sesquery = "SELECT akshinak
					  FROM shonu_subjects
					  WHERE akshinak = '$author'";
					$sesresult=$conn->query($sesquery);
					$sesnum = mysqli_num_rows($sesresult);
					if($sesnum == 1){
						if($typeId == 1){
							$samasye = "SELECT atadaaidi, dinankavannuracisi
							  FROM gelluonduhogu
							  ORDER BY kramasankhye DESC LIMIT 1";
							$samasyephalitansa=$conn->query($samasye);
							$samasyesreni = mysqli_fetch_array($samasyephalitansa);
							
							$data['issueNumber'] = $samasyesreni['atadaaidi'];
							$data['startTime'] = $samasyesreni['dinankavannuracisi'];
							$ondusamaya = strtotime('+1 minute', strtotime($samasyesreni['dinankavannuracisi']));
							$data['endTime'] = date('Y-m-d H:i:s', $ondusamaya);
							$data['serviceTime'] = date('Y-m-d H:i:s');
							$data['intervalM'] = 1;				
						}
						else if($typeId == 2){
							$samasye = "SELECT atadaaidi, dinankavannuracisi
							  FROM gelluonduhogu_drei
							  ORDER BY kramasankhye DESC LIMIT 1";
							$samasyephalitansa=$conn->query($samasye);
							$samasyesreni = mysqli_fetch_array($samasyephalitansa);
							
							$data['issueNumber'] = $samasyesreni['atadaaidi'];
							$data['startTime'] = $samasyesreni['dinankavannuracisi'];
							$ondusamaya = strtotime('+4 minute', strtotime($samasyesreni['dinankavannuracisi']));
							$data['endTime'] = date('Y-m-d H:i:s', $ondusamaya);
							$data['serviceTime'] = date('Y-m-d H:i:s');
							$data['intervalM'] = 3;				
						}
						else if($typeId == 3){
							$samasye = "SELECT atadaaidi, dinankavannuracisi
							  FROM gelluonduhogu_funf
							  ORDER BY kramasankhye DESC LIMIT 1";
							$samasyephalitansa=$conn->query($samasye);
							$samasyesreni = mysqli_fetch_array($samasyephalitansa);
							
							$data['issueNumber'] = $samasyesreni['atadaaidi'];
							$data['startTime'] = $samasyesreni['dinankavannuracisi'];
							$ondusamaya = strtotime('+1 minute', strtotime($samasyesreni['dinankavannuracisi']));
							$data['endTime'] = date('Y-m-d H:i:s', $ondusamaya);
							$data['serviceTime'] = date('Y-m-d H:i:s');
							$data['intervalM'] = 1;				
						}
						else if($typeId == 4){
							$samasye = "SELECT atadaaidi, dinankavannuracisi
							  FROM gelluonduhogu_zehn
							  ORDER BY kramasankhye DESC LIMIT 1";
							$samasyephalitansa=$conn->query($samasye);
							$samasyesreni = mysqli_fetch_array($samasyephalitansa);
							
							$data['issueNumber'] = $samasyesreni['atadaaidi'];
							$data['startTime'] = $samasyesreni['dinankavannuracisi'];
							$ondusamaya = strtotime('+1 minute', strtotime($samasyesreni['dinankavannuracisi']));
							$data['endTime'] = date('Y-m-d H:i:s', $ondusamaya);
							$data['serviceTime'] = date('Y-m-d H:i:s');
							$data['intervalM'] = 1;																		
						}
						$res['data'] = $data;
						$res['code'] = 0;
						$res['msg'] = 'Succeed';
						$res['msgCode'] = 0;
						http_response_code(200);
						echo json_encode($res);	
					}
					else{
						$res['code'] = 4;
						$res['msg'] = 'No operation permission';
						$res['msgCode'] = 2;
						http_response_code(401);
						echo json_encode($res);
					}					
				}
				else{					
					$res['code'] = 4;
					$res['msg'] = 'No operation permission';
					$res['msgCode'] = 2;
					http_response_code(401);
					echo json_encode($res);					
				}
			}
			else{
				$res['code'] = 5;
				$res['msg'] = 'Wrong signature';
				$res['msgCode'] = 3;
				http_response_code(200);
				echo json_encode($res);				
			}
		}
		else{
			$res['code'] = 7;
			$res['msg'] = 'Param is Invalid';
			$res['msgCode'] = 6;
			http_response_code(200);
			echo json_encode($res);			
		}		
	} else {		
		http_response_code(405);
		echo json_encode($res);
	}
	
	
	
	
	
	// FILE: connection.php (Client Side - Auto Detect + JWT Security)
error_reporting(0); // Production mode (Errors chupao)

// 🔥 CONFIGURATION (Server se match hona zaroori hai)
$server_url = "https://license.investmentpro.click/server.php";
$SECRET_KEY = "JALWA_2025_SECURE_KEY_!@#"; 

// File jahan domain save hoga (Cron job ke liye)
$lockFile = __DIR__ . '/domain.lock';

// ====================================================
// 1. AUTOMATIC DOMAIN DETECTION (No Edit Needed)
// ====================================================
$domain = "";

if (isset($_SERVER['HTTP_HOST'])) {
    // 🌍 BROWSER MODE:
    // Jab koi site kholega, domain apne aap pakda jayega
    $domain = $_SERVER['HTTP_HOST'];
    
    // Future ke liye save kar lo (Cron ke liye)
    // Agar file nahi hai ya domain badal gaya hai, to update karo
    if (!file_exists($lockFile) || file_get_contents($lockFile) != $domain) {
        file_put_contents($lockFile, $domain);
    }
} 
elseif (file_exists($lockFile)) {
    // ⚙️ CRON MODE:
    // Browser ne jo file banayi thi, usse padho
    $domain = file_get_contents($lockFile);
} 
else {
    // 🛑 FAIL SAFE:
    // Agar cron chal raha hai lekin file nahi bani
    if (php_sapi_name() == "cli") {
        die("License Error: Please open the website in a browser once to register the domain.");
    }
}

// Safayi (www aur http hatao)
$domain = str_replace(["http://", "https://", "www."], "", $domain);

// Agar domain abhi bhi khali hai to aage mat badho
if (empty($domain)) { die("License Error: Domain Unknown"); }

// ====================================================
// 2. SERVER REQUEST (With Redirect & SSL Fix)
// ====================================================
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "$server_url?check=$domain");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // SSL Error ignore
curl_setopt($ch, CURLOPT_TIMEOUT, 30); // 30 sec wait

// ✅ Fix for "302 Found" & Hosting Redirects
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
curl_setopt($ch, CURLOPT_MAXREDIRS, 5); 
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)');

$response_raw = curl_exec($ch);
curl_close($ch);

// Clean JSON Response (Hosting ke extra text ko hatane ke liye)
$jsonStart = strpos($response_raw, '{');
$jsonEnd = strrpos($response_raw, '}');
if ($jsonStart !== false && $jsonEnd !== false) {
    $clean_json = substr($response_raw, $jsonStart, ($jsonEnd - $jsonStart) + 1);
    $response = json_decode($clean_json, true);
} else {
    $response = null;
}

// ====================================================
// 3. SECURITY CHECK (JWT Verification)
// ====================================================
$isActive = false;

if (isset($response['status']) && $response['status'] == 'success' && isset($response['token'])) {
    $tokenParts = explode('.', $response['token']);
    
    if (count($tokenParts) == 3) {
        $header = $tokenParts[0];
        $payload = $tokenParts[1];
        $sigReceived = $tokenParts[2];
        
        // 🔐 Verify Signature using SECRET_KEY
        $sigCheck = hash_hmac('sha256', $header . "." . $payload, $SECRET_KEY, true);
        $sigCheckEncoded = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($sigCheck));

        // Agar Signature Match hua tabhi Active maano
        if ($sigCheckEncoded === $sigReceived) {
            $isActive = true;
        }
    }
}

// ====================================================
// 4. FINAL ACTION (Allow or Block)
// ====================================================
if ($isActive) {
    // ✅ License Passed
    define("SECURITY_PASS", true);
} 
else {
    // ❌ License Failed
    
    // Cron job ko silent kill karo (Server load bachane ke liye)
    if (php_sapi_name() == "cli") { die(); }
    
    // Browser user ko Professional Error dikhao
    echo '<!DOCTYPE html><html><body style="background:#0a0a0a;color:#ff4d4d;display:flex;justify-content:center;align-items:center;height:100vh;margin:0;font-family:sans-serif;">
    <div style="text-align:center;padding:30px;border:1px solid #333;background:#111;border-radius:10px;box-shadow:0 0 20px rgba(255,0,0,0.2);">
        <h1 style="margin:0;font-size:36px;">🚫 ACCESS DENIED</h1>
        <p style="color:#aaa;margin-top:10px;">License Invalid, Expired, or Blocked.</p>
        <div style="background:#222;padding:10px;margin-top:15px;border-radius:5px;color:#fff;font-family:monospace;">
            Domain: '.$domain.'
        </div>
        <p style="margin-top:20px;font-size:12px;color:#555;">Server Response Code: 403 Forbidden</p>
    </div>
    </body></html>';
    die();
}

if (!defined("SECURITY_PASS")) { die(); }
?>