<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

date_default_timezone_set('Asia/Kolkata');

/* ==========================
   DB CONFIG
========================== */
$DB_HOST = '136.112.153.136';
$DB_USER = 'lac';
$DB_PASS = 'kschhiKHSH23243#';
$DB_NAME = 'lac_prod';
$DB_PORT = 3306;
$AMAZON_SHARED_SECRET = getenv('AMAZON_SHARED_SECRET') ?: '';

/**
 * Verify Amazon receipt with RVS and return parsed response.
 */
function verifyAmazonReceiptRvs($sharedSecret, $appUserId, $receiptId)
{
    if (empty($sharedSecret)) {
        return [
            'ok' => false,
            'error' => 'AMAZON_SHARED_SECRET is empty',
            'http_code' => 0,
            'raw' => null,
            'decoded' => null
        ];
    }

    if (empty($receiptId)) {
        return [
            'ok' => false,
            'error' => 'receiptId is empty',
            'http_code' => 0,
            'raw' => null,
            'decoded' => null
        ];
    }

    // RVS endpoint: include appUserId when available.
    if (!empty($appUserId)) {
        $verifyUrl = "https://appstore-sdk.amazon.com/version/1.0/verifyReceiptId/developer/"
            . rawurlencode($sharedSecret)
            . "/user/" . rawurlencode($appUserId)
            . "/receiptId/" . rawurlencode($receiptId);
    } else {
        $verifyUrl = "https://appstore-sdk.amazon.com/version/1.0/verifyReceiptId/developer/"
            . rawurlencode($sharedSecret)
            . "/receiptId/" . rawurlencode($receiptId);
    }

    $ch = curl_init($verifyUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 20);
    curl_setopt($ch, CURLOPT_HTTPGET, true);

    $rawResponse = curl_exec($ch);
    $curlError = curl_error($ch);
    $httpCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($rawResponse === false) {
        return [
            'ok' => false,
            'error' => $curlError ?: 'RVS request failed',
            'http_code' => $httpCode,
            'raw' => null,
            'decoded' => null
        ];
    }

    $decoded = json_decode($rawResponse, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        return [
            'ok' => false,
            'error' => 'Invalid JSON from RVS',
            'http_code' => $httpCode,
            'raw' => $rawResponse,
            'decoded' => null
        ];
    }

    return [
        'ok' => ($httpCode >= 200 && $httpCode < 300),
        'error' => null,
        'http_code' => $httpCode,
        'raw' => $rawResponse,
        'decoded' => $decoded
    ];
}

/* ==========================
   DB CONNECTION
========================== */
$conn = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME, $DB_PORT);
if ($conn->connect_error) {
    http_response_code(500);
    exit('DB connection failed');
}

/* ==========================
   FETCH 10 AMAZON FIRE TV LOGS
========================== */
$source = 'AMAZON FIRE TV';
 $sql = "SELECT * FROM roku_webhook_log WHERE source = ? AND sync = 0 and log_data !='' ORDER BY id DESC LIMIT 1";

$stmt = $conn->prepare($sql);
if (!$stmt) {
    http_response_code(500);
    $conn->close();
    exit('Failed to prepare query');
}

$stmt->bind_param("s", $source);
$stmt->execute();
$result = $stmt->get_result();

$logs = [];
while ($row = $result->fetch_assoc()) {
    $receiptId = null;
    $notificationType = null;
    $appUserId = null;
    $webhookTimestampMs = null;
    $amazonRvs = null;

    if (!empty($row['log_data'])) {
        $outerPayload = json_decode($row['log_data'], true);
        if (json_last_error() === JSON_ERROR_NONE && !empty($outerPayload['Message'])) {
            $innerMessage = json_decode($outerPayload['Message'], true);
            if (json_last_error() === JSON_ERROR_NONE) {
                $receiptId = $innerMessage['receiptId'] ?? null;
                $notificationType = $innerMessage['notificationType'] ?? null;
                $appUserId = $innerMessage['appUserId'] ?? null;
                $webhookTimestampMs = $innerMessage['timestamp'] ?? null;
            }
        }
    }

    $row['receipt_id'] = $receiptId;
    $row['notification_type'] = $notificationType;
    $row['app_user_id'] = $appUserId;
    $row['webhook_timestamp_ms'] = $webhookTimestampMs;
    $row['subscription'] = null;
    $row['subscription_insert'] = null;
    $row['amazon_rvs'] = null;

    // Start verification from parsed values (receiptId + appUserId).
    if (!empty($receiptId)) {
        $amazonRvs = verifyAmazonReceiptRvs($AMAZON_SHARED_SECRET, $appUserId, $receiptId);
        $row['amazon_rvs'] = [
            'ok' => $amazonRvs['ok'],
            'http_code' => $amazonRvs['http_code'],
            'error' => $amazonRvs['error'],
            'values' => $amazonRvs['decoded']
        ];
    }
   $processableNotificationTypes = ['SUBSCRIPTION_RENEWED', 'SUBSCRIPTION_PURCHASED'];
    if (in_array($notificationType, $processableNotificationTypes, true) && !empty($receiptId)) {
		
        $purchaseType = ($notificationType === 'SUBSCRIPTION_PURCHASED') ? 'PURCHASED' : 'RENEWED';
         $subscriptionSql = "SELECT * FROM tbl_customer_subscriptions WHERE gateway_subscription_id = ? AND pg_name = 'amazon' ORDER BY id DESC LIMIT 1";
        $subscriptionStmt = $conn->prepare($subscriptionSql);
        if ($subscriptionStmt) {
            $subscriptionStmt->bind_param("s", $receiptId);
            $subscriptionStmt->execute();
            $subscriptionResult = $subscriptionStmt->get_result();

            if ($subscriptionResult && $subscriptionResult->num_rows > 0) {
                $existingSubscription = $subscriptionResult->fetch_assoc();
                //echo "<pre>";
                //print_r($existingSubscription);
                $row['subscription'] = $existingSubscription;

                // Insert subscription record in same table with required field changes.
                if (!empty($existingSubscription)) {
					
					if (
    $notificationType === 'SUBSCRIPTION_PURCHASED'
    && ($existingSubscription['platform'] ?? '') === 'platform'
    && ($existingSubscription['purchase_type'] ?? '') === 'PURCHASED'
) {
    // Existing record me webhook payload save karna optional hai.
    $existingId = (int)$existingSubscription['id'];
    $webhookPayload = $row['log_data'];

    $updateStmt = $conn->prepare(
        "UPDATE tbl_customer_subscriptions
         SET pg_payment_data = ?, updated_at = NOW()
         WHERE id = ?
         LIMIT 1"
    );

    if ($updateStmt) {
        $updateStmt->bind_param("si", $webhookPayload, $existingId);
        $updateStmt->execute();
        $updateStmt->close();
    }

    // Webhook log ko processed mark karo.
    $webhookLogId = (int)$row['id'];

    $syncStmt = $conn->prepare(
        "UPDATE roku_webhook_log
         SET sync = 1
         WHERE id = ?
         LIMIT 1"
    );

    if ($syncStmt) {
        $syncStmt->bind_param("i", $webhookLogId);
        $syncStmt->execute();
        $syncStmt->close();
        $row['sync'] = 1;
    }

    $row['subscription_insert'] = [
        'ok' => true,
        'insert_id' => 0,
        'error' => null,
        'message' => 'Existing platform purchase found; duplicate webhook insert skipped'
    ];

    $subscriptionStmt->close();
    $logs[] = $row;
    continue;
}
					
                    unset($existingSubscription['id']); // New row should have new PK.

                    // period_interval: use existing value if valid, else fallback to 1.
                    $allowedIntervals = ['1', '2', '3', '6', '12'];
                    $periodInterval = trim((string)($existingSubscription['period_interval'] ?? ''));
                    if (!in_array($periodInterval, $allowedIntervals, true)) {
                        $periodInterval = '1';
                    }

                    // period: support Month/Year, fallback to Month.
                    $periodRaw = strtolower(trim((string)($existingSubscription['period'] ?? 'month')));
                    $period = ($periodRaw === 'year' || $periodRaw === 'years') ? 'Year' : 'Month';

                    // start_date from webhook timestamp (epoch milliseconds).
                    if (is_numeric((string)$webhookTimestampMs) && (int)$webhookTimestampMs > 0) {
                        $startTs = (int)floor(((int)$webhookTimestampMs) / 1000);
                    } else {
                        $startTs = time();
                    }
                    $startDate = date('Y-m-d H:i:s', $startTs);

                    // end_date = start_date + period_interval (Month/Year).
                    if ($period === 'Year') {
                        $endTs = strtotime('+' . (int)$periodInterval . ' year', $startTs);
                    } else {
                        $endTs = strtotime('+' . (int)$periodInterval . ' month', $startTs);
                    }
                    if ($endTs === false) {
                        $endTs = $startTs;
                    }
                    $endDate = date('Y-m-d H:i:s', $endTs);

                    
                    $existingSubscription['start_date'] = $startDate;
                    $existingSubscription['end_date'] = $endDate;
                    $existingSubscription['platform'] = 'webhook';
                    $existingSubscription['purchase_type'] = $purchaseType;
                    $existingSubscription['autorenew'] = '1';
                    $existingSubscription['status'] = '2';
                    $existingSubscription['pg_ref_id'] = $receiptId;
                    $existingSubscription['pg_payment_data'] = $row['log_data'];
                    $existingSubscription['created'] = date('Y-m-d H:i:s');
                    $existingSubscription['updated_at'] = date('Y-m-d H:i:s');


                    $columns = [];
                    $values = [];
                    foreach ($existingSubscription as $column => $value) {
                        $safeColumn = str_replace('`', '``', (string)$column);
                        $columns[] = "`{$safeColumn}`";

                        if ($value === null) {
                            $values[] = "NULL";
                        } else {
                            $values[] = "'" . $conn->real_escape_string((string)$value) . "'";
                        }
                    }

//echo "<br>";
                     $insertSql = "INSERT INTO tbl_customer_subscriptions (" . implode(', ', $columns) . ") VALUES (" . implode(', ', $values) . ")";

                    $insertOk = $conn->query($insertSql);
                    if ($insertOk) {
                        $row['subscription_insert'] = [
                            'ok' => true,
                            'insert_id' => (int)$conn->insert_id,
                            'error' => null
                        ];

                        //update the roku_webhook_log table with colm sync= 1
                        $webhookLogId = isset($row['id']) ? (int)$row['id'] : 0;
                        if ($webhookLogId > 0) {
                            $syncStmt = $conn->prepare("UPDATE roku_webhook_log SET sync = 1 WHERE id = ? LIMIT 1");
                            if ($syncStmt) {
                                $syncStmt->bind_param("i", $webhookLogId);
                                $syncStmt->execute();
                                $syncStmt->close();
                                $row['sync'] = 1;
                            }
                        }

                    } else {
                        $row['subscription_insert'] = [
                            'ok' => false,
                            'insert_id' => 0,
                            'error' => $conn->error
                        ];
                    }
                } else {
                    $row['subscription_insert'] = [
                        'ok' => false,
                        'insert_id' => 0,
                        'error' => 'Source subscription row is empty'
                    ];
                }
            } else {
               
						$row['subscription_insert'] = [
        'ok' => false,
        'insert_id' => 0,
        'error' => 'No existing subscription found for receiptId; customer/order cannot be identified'
    ];

    $webhookLogId = (int)$row['id'];

    $syncStmt = $conn->prepare(
        "UPDATE roku_webhook_log
         SET sync = 1
         WHERE id = ?
         LIMIT 1"
    );

    if ($syncStmt) {
        $syncStmt->bind_param("i", $webhookLogId);
        $syncStmt->execute();
        $syncStmt->close();
        $row['sync'] = 1;
    }
               
               
            }

            $subscriptionStmt->close();
        }else{
			
			echo "i am here";
			}
    }else{
		
		$row['subscription_insert'] = [
        'ok' => false,
        'insert_id' => 0,
        'error' => 'Notification type not handled: ' . $notificationType
    ];

    $webhookLogId = (int)$row['id'];

    $syncStmt = $conn->prepare(
        "UPDATE roku_webhook_log
         SET sync = 1
         WHERE id = ?
         LIMIT 1"
    );

    if ($syncStmt) {
        $syncStmt->bind_param("i", $webhookLogId);
        $syncStmt->execute();
        $syncStmt->close();

        $row['sync'] = 1;
    }


		}

    $logs[] = $row;
}

$stmt->close();
$conn->close();

header('Content-Type: application/json');
echo json_encode([
    'status' => 'success',
    'count' => count($logs),
    'data' => $logs
]);
?>
