<?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
    ];
}

function fetchAmazonOrderContext(mysqli $conn, $orderId)
{
    $orderId = (int)$orderId;
    if ($orderId <= 0) {
        return [null, null];
    }

    $orderStmt = $conn->prepare("SELECT * FROM tbl_order WHERE id = ? LIMIT 1");
    $orderRow = null;
    if ($orderStmt) {
        $orderStmt->bind_param("i", $orderId);
        $orderStmt->execute();
        $orderResult = $orderStmt->get_result();
        $orderRow = $orderResult ? $orderResult->fetch_assoc() : null;
        $orderStmt->close();
    }

    $detailStmt = $conn->prepare("SELECT * FROM tbl_order_details WHERE order_id = ? ORDER BY id DESC LIMIT 1");
    $orderDetailRow = null;
    if ($detailStmt) {
        $detailStmt->bind_param("i", $orderId);
        $detailStmt->execute();
        $detailResult = $detailStmt->get_result();
        $orderDetailRow = $detailResult ? $detailResult->fetch_assoc() : null;
        $detailStmt->close();
    }

    return [$orderRow, $orderDetailRow];
}

function buildAmazonSubscriptionInsertRow(array $existingSubscription, $orderRow, $orderDetailRow, array $context)
{
    unset($existingSubscription['id']);

    $itemPrice = $orderDetailRow['item_price'] ?? $orderDetailRow['real_price'] ?? $orderDetailRow['total'] ?? null;
    $basicAmount = $itemPrice !== null ? $itemPrice : ($existingSubscription['basic_amount'] ?? ($context['price'] ?? '0.00'));
    $msisdn = $orderDetailRow['s_contact_number'] ?? $orderDetailRow['b_contact_number'] ?? ($existingSubscription['msisdn'] ?? '');

    $existingSubscription['app_id'] = $orderDetailRow['app_id'] ?? ($orderRow['app_id'] ?? ($existingSubscription['app_id'] ?? '5013'));
    $existingSubscription['order_id'] = $orderRow['id'] ?? ($existingSubscription['order_id'] ?? 0);
    $existingSubscription['trans_id'] = $orderRow['transaction_id'] ?? ($existingSubscription['trans_id'] ?? '');
    $existingSubscription['pg_ref_id'] = $orderDetailRow['pg_ref_id'] ?? ($orderRow['pg_ref_id'] ?? ($context['receipt_id'] ?? ($existingSubscription['pg_ref_id'] ?? '')));
    $existingSubscription['device_id'] = $orderRow['device_id'] ?? ($existingSubscription['device_id'] ?? 0);
    $existingSubscription['gateway_subscription_id'] = $context['receipt_id'] ?? ($existingSubscription['gateway_subscription_id'] ?? '');
    $existingSubscription['pg_payment_data'] = $context['webhook_payload'] ?? '';
    $existingSubscription['channel'] = $orderRow['channel'] ?? ($existingSubscription['channel'] ?? '');
    $existingSubscription['package_id'] = $orderDetailRow['item_id'] ?? ($existingSubscription['package_id'] ?? 0);
    $existingSubscription['package_title'] = $orderDetailRow['item_name'] ?? ($existingSubscription['package_title'] ?? '');
    $existingSubscription['package_mode'] = $orderDetailRow['package_mode'] ?? ($existingSubscription['package_mode'] ?? 'OTT');
    $existingSubscription['price'] = $context['price'] ?? ($existingSubscription['price'] ?? '0.00');
    $existingSubscription['basic_amount'] = $basicAmount;
    $existingSubscription['tax_amt'] = $orderDetailRow['tax_amt'] ?? ($existingSubscription['tax_amt'] ?? '0');
    $existingSubscription['subscriber_id'] = $orderRow['subscriber_id'] ?? ($orderDetailRow['subscriber_id'] ?? ($existingSubscription['subscriber_id'] ?? 0));
    $existingSubscription['msisdn'] = $msisdn;
    $existingSubscription['role_type'] = $orderRow['role_type'] ?? ($orderDetailRow['role_type'] ?? ($existingSubscription['role_type'] ?? 1));
    $existingSubscription['gateway_type'] = $orderDetailRow['gateway_type'] ?? ($orderRow['gateway_type'] ?? ($existingSubscription['gateway_type'] ?? 30));
    $existingSubscription['pg_name'] = $orderDetailRow['pg_name'] ?? ($orderRow['pg_name'] ?? ($existingSubscription['pg_name'] ?? 'amazon'));
    $existingSubscription['region_type'] = $orderDetailRow['region_type'] ?? ($orderRow['region_type'] ?? ($existingSubscription['region_type'] ?? 1));
    $existingSubscription['local_user'] = $orderDetailRow['local_user'] ?? ($existingSubscription['local_user'] ?? 0);
    $existingSubscription['state_code'] = $orderDetailRow['b_state_code'] ?? ($existingSubscription['state_code'] ?? 0);
    $existingSubscription['period'] = $context['period'] ?? ($orderDetailRow['period'] ?? ($existingSubscription['period'] ?? 'Month'));
    $existingSubscription['period_interval'] = $context['period_interval'] ?? ($orderDetailRow['period_interval'] ?? ($existingSubscription['period_interval'] ?? 1));
    $existingSubscription['subscription_type'] = $orderDetailRow['subscription_type'] ?? ($existingSubscription['subscription_type'] ?? 0);
    $existingSubscription['output_video_limit'] = $orderDetailRow['output_video_limit'] ?? ($existingSubscription['output_video_limit'] ?? 0);
    $existingSubscription['additional_cost_per_unit'] = $orderDetailRow['additional_cost_per_unit'] ?? ($existingSubscription['additional_cost_per_unit'] ?? 0);
    $existingSubscription['platform'] = 'webhook';
    $existingSubscription['purchase_type'] = $context['purchase_type'] ?? 'PURCHASED';
    $existingSubscription['autorenew'] = '1';
    $existingSubscription['status'] = '2';
    $existingSubscription['extended_status'] = $orderRow['extended_status'] ?? ($existingSubscription['extended_status'] ?? 0);
    $existingSubscription['start_date'] = $context['start_date'];
    $existingSubscription['end_date'] = $context['end_date'];
    $existingSubscription['currency_id'] = $orderDetailRow['currency_id'] ?? ($orderRow['currency_id'] ?? ($existingSubscription['currency_id'] ?? 4));
    $existingSubscription['currency'] = $orderDetailRow['currency'] ?? ($orderRow['currency'] ?? ($existingSubscription['currency'] ?? 'USD'));
    $existingSubscription['created'] = $context['created_at'];
    $existingSubscription['updated_at'] = $context['created_at'];

    return $existingSubscription;
}

function fetchAmazonSubscriptionByTransId(mysqli $conn, $transId)
{
    $transId = trim((string)$transId);
    if ($transId === '') {
        return null;
    }

    $stmt = $conn->prepare("SELECT id, order_id, gateway_subscription_id, purchase_type, platform, created FROM tbl_customer_subscriptions WHERE trans_id = ? AND pg_name = 'amazon' ORDER BY id DESC LIMIT 1");
    if (!$stmt) {
        return null;
    }

    $stmt->bind_param("s", $transId);
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result ? $result->fetch_assoc() : null;
    $stmt->close();

    return $row ?: null;
}

/* ==========================
   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);

                    
                    list($orderRow, $orderDetailRow) = fetchAmazonOrderContext($conn, $existingSubscription['order_id'] ?? 0);
                    if (!$orderRow || !$orderDetailRow) {
                        $row['subscription_insert'] = [
                            'ok' => false,
                            'insert_id' => 0,
                            'error' => 'Order or order details not found for order_id=' . ($existingSubscription['order_id'] ?? 0)
                        ];
                        $logs[] = $row;
                        $subscriptionStmt->close();
                        continue;
                    }

                    $existingSubscription = buildAmazonSubscriptionInsertRow(
                        $existingSubscription,
                        $orderRow,
                        $orderDetailRow,
                        [
                            'receipt_id' => $receiptId,
                            'purchase_type' => $purchaseType,
                            'price' => $orderDetailRow['item_price'] ?? $orderDetailRow['total'] ?? ($existingSubscription['price'] ?? '0.00'),
                            'period' => $period,
                            'period_interval' => $periodInterval,
                            'start_date' => $startDate,
                            'end_date' => $endDate,
                            'created_at' => date('Y-m-d H:i:s'),
                            'webhook_payload' => $row['log_data'],
                        ]
                    );

                    $duplicateTransIdRow = fetchAmazonSubscriptionByTransId($conn, $existingSubscription['trans_id'] ?? '');
                    if ($duplicateTransIdRow) {
                        $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;
                            }
                        }

                        $row['subscription_insert'] = [
                            'ok' => true,
                            'insert_id' => 0,
                            'error' => null,
                            'message' => 'Duplicate trans_id found; insert skipped',
                            'duplicate_subscription_id' => (int)($duplicateTransIdRow['id'] ?? 0),
                        ];
                        $subscriptionStmt->close();
                        $logs[] = $row;
                        continue;
                    }


                    $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
]);
?>
