<?php
///** 
 ini_set('display_errors', '1');
 ini_set('display_startup_errors', '1');
 error_reporting(E_ALL);
 //***/
// Specify the log file path

// date_default_timezone_set('Asia/Kolkata');

$logFile = 'post_log.txt';
$logFile2 = 'only_gp_log.txt';
$logFile3 = 'gpay_tbl_log.txt';
$raw_log_file = 'raw_log.txt';
$logTblWebhook = "";

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(400);
    echo json_encode(["error" => "Invalid request method."]);
    exit;
}

/// Get the POST data
$postData = file_get_contents('php://input');

//$postData '{"message":{"data":"eyJ2ZXJzaW9uIjoiMS4wIiwicGFja2FnZU5hbWUiOiJjb20uYXJqLm1hc3RpaSIsImV2ZW50VGltZU1pbGxpcyI6IjE3MTk0OTI1Njk5MzgiLCJvbmVUaW1lUHJvZHVjdE5vdGlmaWNhdGlvbiI6eyJ2ZXJzaW9uIjoiMS4wIiwibm90aWZpY2F0aW9uVHlwZSI6MSwicHVyY2hhc2VUb2tlbiI6ImNsbmppZWNoa2ZsamNmb21kZWxjcGZrYS5BTy1KMU96WkZfd0JzNmk0N0o1LTBTUGFaSi0xRkI2N3Z3c1hvMmN3YlpPdEtyOUxfcmZOcXg4T21HUm1SdlJJYzBjM19kaHYyTW9TdlNUZWphdy1ZWF9lVDRwYjJ0RGF3USIsInNrdSI6ImNvbS5hcmoubWFzdGlpLndlZWtseV85OSJ9fQ==","messageId":"11565121105865974","message_id":"11565121105865974","publishTime":"2024-06-27T12:49:30.061Z","publish_time":"2024-06-27T12:49:30.061Z"},"subscription":"projects/mastii-1424/subscriptions/MastiiPushSub"}';

$data = json_decode($postData, true);
// Extract data field from the message
$dataFieldBase64 = $data['message']['data'];
// Decode the base64 encoded data
$dataDecoded = base64_decode($dataFieldBase64);

$raw_entry_log  = "=============================\n";
$raw_entry_log .= "Time: " . date('Y-m-d H:i:s') . "\n\n";

$raw_entry_log .= "Encoded POST Data:\n";
$raw_entry_log .= json_encode($data, JSON_PRETTY_PRINT) . "\n\n";

$raw_entry_log .= "Base64 Decoded Data:\n";
$raw_entry_log .= json_encode(json_decode($dataDecoded, true), JSON_PRETTY_PRINT) . "\n\n";

file_put_contents($raw_log_file, $raw_entry_log, FILE_APPEND | LOCK_EX);
// Prepare the log entry

echo "<pre>";
// $purchaseDataDecoded = json_decode($dataDecoded, true);
// $packageName  = $purchaseDataDecoded['packageName'];
// $purchaseToken  = $purchaseDataDecoded['oneTimeProductNotification']['purchaseToken'];
// $productId  =  $purchaseDataDecoded['oneTimeProductNotification']['sku'];
// $notificationType  =  $purchaseDataDecoded['oneTimeProductNotification']['notificationType'];

$purchaseDataDecoded = json_decode($dataDecoded, true);
$type="subscription";
if (isset($purchaseDataDecoded['oneTimeProductNotification']) && !empty($purchaseDataDecoded['oneTimeProductNotification']['purchaseToken'])) {
    $packageName  = $purchaseDataDecoded['packageName'];
    $purchaseToken  = $purchaseDataDecoded['oneTimeProductNotification']['purchaseToken'];
    $productId  =  $purchaseDataDecoded['oneTimeProductNotification']['sku'];
    $notificationType  =  $purchaseDataDecoded['oneTimeProductNotification']['notificationType'];
    $type="onetime";
} elseif (isset($purchaseDataDecoded['subscriptionNotification']) && !empty($purchaseDataDecoded['subscriptionNotification']['purchaseToken'])) {
    $packageName  = $purchaseDataDecoded['packageName'];
    $purchaseToken  = $purchaseDataDecoded['subscriptionNotification']['purchaseToken'];
    $productId  =  $purchaseDataDecoded['subscriptionNotification']['subscriptionId'];
    $notificationType  =  $purchaseDataDecoded['subscriptionNotification']['notificationType'];
    $cron_status = 1;
    $type="subscription";
    if($notificationType == "2" || $notificationType == "3" || $notificationType == "4" ||  $notificationType == "13"){   // 4=>purchased, 2=>renewed,3=>cancelled, 13=>expired 
        //die();
        $raw_entry_log .= date('Y-m-d H:i:s') ." - SubsData: " . $dataDecoded. PHP_EOL. PHP_EOL; 
        file_put_contents($raw_log_file, $raw_entry_log, FILE_APPEND | LOCK_EX);
    }else{
        die();
    }
} else {
    // Handle the case where neither notification exists
    echo "No valid notification found.";
}

require_once __DIR__ . '/vendor/autoload.php';

function getGoogleClient($keyFilePath)
{
    $client = new Google_Client();
    $client->setAuthConfig($keyFilePath);
    $client->addScope(Google_Service_AndroidPublisher::ANDROIDPUBLISHER);
    return $client;
}
function verifyPurchase($packageName, $productId, $purchaseToken, $keyFilePath)
{
    $client = getGoogleClient($keyFilePath);
    $service = new Google_Service_AndroidPublisher($client);
    try {
        $response = $service->purchases_products->get($packageName, $productId, $purchaseToken);
        return $response;
    } catch (Google_Service_Exception $e) {
        return $e->getMessage();
    }
}
function verifySubscription($packageName, $subscriptionId, $purchaseToken, $keyFilePath)
{
    $client = getGoogleClient($keyFilePath);
    $service = new Google_Service_AndroidPublisher($client);
    try {
        $response = $service->purchases_subscriptions->get($packageName, $subscriptionId, $purchaseToken);
        return $response;
    } catch (Google_Service_Exception $e) {
        return $e->getMessage();
    }
}

$keyFilePath = 'api-8549026468989628459-243024-44764e4e3907.json';
if (isset($purchaseDataDecoded['oneTimeProductNotification'])) {
    $result = verifyPurchase($packageName, $productId, $purchaseToken, $keyFilePath);
}elseif (isset($purchaseDataDecoded['subscriptionNotification'])) {
    $result = verifySubscription($packageName, $productId, $purchaseToken, $keyFilePath);
}

// echo "<pre>"; print_r($result); die();

//  $resultDataDecoded = json_decode($result, true);
$raw_entry_log .= "Verify Response:\n";
$raw_entry_log .= json_encode($result, JSON_PRETTY_PRINT) . "\n";
$raw_entry_log .= "Notification Type: ".$notificationType."\n\n";
file_put_contents($raw_log_file, $raw_entry_log, FILE_APPEND | LOCK_EX);


$logEntry3 = date('Y-m-d H:i:s') . " - POST Data: " . $postData . 'Data Decoded-----' . $dataDecoded . '-----ParamsVerify---' . $packageName . '---' . $productId . '--' . $purchaseToken . '---VerifyPurchase Data-' . json_encode($result) . PHP_EOL;

$purchaseTimeMillis = $result['purchaseTimeMillis'] / 1000;
// Format the timestamp
$datepurchaseTimeMillis = date("Y-m-d H:i:s", $purchaseTimeMillis);

$logEntry3 .= date('Y-m-d H:i:s') . '--ACK_State:' . $result['acknowledgementState'] . '--Purchase_State:' . $result['purchaseState'] . '-- SELECT * FROM `tbl_customer_subscriptions` WHERE `trans_id` = "' . $result['orderId'] . '" and status =  2; --' . $datepurchaseTimeMillis . '--' . $result['obfuscatedExternalAccountId'] . '--' . $result['obfuscatedExternalProfileId'] . '--';
$logEntry3 .= 'Plan : ' . $productId . '--' . 'NotificationType : ' . $notificationType . PHP_EOL;
$logEntry3 .= "'" . $result['orderId'] . "'," . PHP_EOL;

file_put_contents($logFile, $logEntry2, FILE_APPEND | LOCK_EX);

$servername = '136.112.153.136'; //law and crime db connection public IP 
$username = 'lac';
$password = 'kschhiKHSH23243#';
$dbname = "lac_prod";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Set parameters
$gpa_id = isset($result['orderId']) ? $result['orderId'] : '0';
$customer_id = isset($result['obfuscatedExternalProfileId']) ? $result['obfuscatedExternalProfileId'] : '0';


// Step 2: If still 0 or blank → Fetch from DB
if (empty($customer_id) || $customer_id == '0') {
    $base_gpa_id = preg_replace('/\.\.\d+$/', '', trim($gpa_id));
    $escaped_gpa = mysqli_real_escape_string($conn, $base_gpa_id);
    $checkCustomer = "SELECT subscriber_id FROM tbl_customer_subscriptions WHERE (trans_id = '$escaped_gpa' OR trans_id LIKE '$escaped_gpa..%') LIMIT 1";
    $checkRes = mysqli_query($conn, $checkCustomer);
    if ($checkRes && mysqli_num_rows($checkRes) > 0) {
        $row = mysqli_fetch_assoc($checkRes);
        $customer_id = $row['subscriber_id'];
    } else {
        $customer_id = '0';
    }
}


$order_id = isset($result['obfuscatedExternalAccountId']) ? $result['obfuscatedExternalAccountId'] : '0';
$package = isset($productId) ? $productId : '0';
$noti_type = $notificationType;

$customerExists = false;
$checkCustomerSql = "SELECT 1 FROM tbl_customer_subscriptions WHERE device_id = '1' AND subscriber_id = '".mysqli_real_escape_string($conn, $customer_id)."' LIMIT 1";
$checkRes = mysqli_query($conn, $checkCustomerSql);
if ($checkRes && mysqli_num_rows($checkRes) > 0) {
    $customerExists = true;
}

$gprice = $result['priceAmountMicros'];
$gcrncy = $result['priceCurrencyCode'];
if (!$customerExists) {
    if (
        isset($result['introductoryPriceInfo']) &&
        isset($result['introductoryPriceInfo']['introductoryPriceAmountMicros']) &&
        isset($result['introductoryPriceInfo']['introductoryPriceCurrencyCode'])
    ) {
        $gprice = $result['introductoryPriceInfo']['introductoryPriceAmountMicros'];
        $gcrncy = $result['introductoryPriceInfo']['introductoryPriceCurrencyCode'];
    }
}


$ack_type = $result['acknowledgementState'];
$purchase_type = isset($result['purchaseState']) ? $result['purchaseState'] : '0';
$status = '0';
$datetime = date('Y-m-d H:i:s');

if ($gpa_id != 0 && $purchaseToken != '' && $package != 0) {
    $sql = "INSERT INTO gpay_webhooks 
            (gpa_id, purchase_token, package, customer_id, order_id, amount, currency, noti_type, type, ack_type, purchase_type, hit_time, created, status, app_version)
            VALUES ('".$gpa_id."', '".$purchaseToken."', '".$package."', '".$customer_id."', '".$order_id."', '".$gprice."', '".$gcrncy."', '".$noti_type."', '".$type."', '".$ack_type."', '".$purchase_type."', '".$datetime."', '".$datetime."', '".$status."', 'LAC-MTV')";

    // Execute the query
    if ($conn->query($sql) === TRUE) {
        $logTblWebhook .= 'Inserted successfully.';
        echo "New record created successfully";
    } else {
        $logTblWebhook .= 'Prepare statement failed: ' . $conn->error;
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
}


$concatenatedString = 'gpa_id: ' . $gpa_id . ', purchaseToken: ' . $purchaseToken . ', package: ' . $package . ', customer_id: ' . $customer_id . ', order_id: ' . $order_id . ', noti_type: ' . $noti_type . ', ack_type: ' . $ack_type . ', purchase_type: ' . $purchase_type . ', status: ' . $status. PHP_EOL;
file_put_contents($raw_log_file, "Concatenated Variables: " . $concatenatedString . PHP_EOL, FILE_APPEND | LOCK_EX);


// Execute statement
// $resultRes = $stmt->execute();
// $res_encoded = json_encode($resultRes );
// file_put_contents($raw_log_file, $res_encoded, FILE_APPEND | LOCK_EX);
// if ($resultRes === false) {
//     $logTblWebhook .= 'Execute statement failed: ' . $stmt->error;
//     //die('Execute statement failed: ' . $stmt->error);
//     $error_log = 'Execute statement failed: ' . $stmt->error;
//     file_put_contents($raw_log_file, $error_log, FILE_APPEND | LOCK_EX);

// } else {
//     //echo "Inserted successfully.";
//     // $logTblWebhook .= 'Inserted successfully.';
//     file_put_contents($raw_log_file, "finalExecuation_Query--NotiType".$notificationType, FILE_APPEND | LOCK_EX);
// }

// // Close statement and connection
// $stmt->close();
$conn->close();

file_put_contents($logFile2, $logEntry3, FILE_APPEND | LOCK_EX);
file_put_contents($logFile3, $logTblWebhook, FILE_APPEND | LOCK_EX);
