<?php
header('Content-Type: application/json; charset=utf-8');

// Secure API key check
$validApiKey = "AbuSecureKey123";
if (!isset($_GET['api_key']) || $_GET['api_key'] !== $validApiKey) {
    http_response_code(403);
    echo json_encode(["status" => "error", "message" => "Forbidden: Invalid API key"]);
    exit;
}

include 'connection.php';
include '/home/screensh/private/encryption_helper.php'; // AES-256-CBC encrypt/decrypt
include '/home/screensh/private/privet_key.php';
require 'get-access-token.php'; // helper to get FCM access token

$response = [];

try {
    $drawSql = "SELECT id, Draw_Number, Draw_Date, Winner_Position_Number, Winner_Bond_Number 
                FROM Past_Draw_History";
    $drawRes = $conn->query($drawSql);

    $notifications = [];

    if ($drawRes && $drawRes->num_rows > 0) {
        $accessToken = getAccessToken('/home/screensh/public_html/Bond_Data/service-account-file.json');

        while ($drawRow = $drawRes->fetch_assoc()) {
            $winnerBondNumber = $drawRow['Winner_Bond_Number'];

            $userSql = "SELECT id, User_ID, Bond_Series, Bond_Number, Bond_Add_Date 
                        FROM User_Bond_Add_History";
            $userRes = $conn->query($userSql);

            while ($userRow = $userRes->fetch_assoc()) {
                $bondSeries = decryptSensitive($userRow['Bond_Series'], $GLOBALS['PRIVATE_KEY']);
                $bondNumber = decryptSensitive($userRow['Bond_Number'], $GLOBALS['PRIVATE_KEY']);

                if ($bondNumber === $winnerBondNumber) {
                    $userId = $userRow['User_ID'];

                    // Step A: Check Notification_Bond_Win table for duplicates
                    $checkStmt = $conn->prepare("SELECT id FROM Notification_Bond_Win 
                                                 WHERE User_ID = ? AND Win_Number = ? AND Send_Notification = 1");
                    $checkStmt->bind_param("ss", $userId, $bondNumber);
                    $checkStmt->execute();
                    $checkRes = $checkStmt->get_result();

                    if ($checkRes->num_rows > 0) {
                        $notifications[] = [
                            "status" => "skipped",
                            "bond_number" => $bondNumber,
                            "draw_number" => $drawRow['Draw_Number']
                        ];
                        $checkStmt->close();
                        continue;
                    }
                    $checkStmt->close();

                    // Step B: Get user FCM token
                    $stmt = $conn->prepare("SELECT FCM_Token FROM User_Database WHERE id = ?");
                    $stmt->bind_param("s", $userId);
                    $stmt->execute();
                    $res2 = $stmt->get_result();

                    if ($userData = $res2->fetch_assoc()) {
                        $fcm_token = $userData['FCM_Token'];

                        if (!empty($fcm_token) && strlen($fcm_token) > 50) {
                            $title = "🎉 Winning Bond!";
                            $body  = "Your bond number {$bondNumber} won in Draw #{$drawRow['Draw_Number']} on {$drawRow['Draw_Date']}.";

                            $headers = [
                                'Content-Type: application/json',
                                'Authorization: Bearer ' . $accessToken
                            ];

                            $payload = json_encode([
                                'message' => [
                                    'token' => $fcm_token,
                                    'notification' => [
                                        'title' => $title,
                                        'body'  => $body
                                    ],
                                    'data' => [
                                        'type' => 'winning_bond',
                                        'bond_number' => $bondNumber,
                                        'draw_number' => $drawRow['Draw_Number']
                                    ]
                                ]
                            ]);

                            $ch = curl_init();
                            curl_setopt($ch, CURLOPT_URL, "https://fcm.googleapis.com/v1/projects/bond-aa1e8/messages:send");
                            curl_setopt($ch, CURLOPT_POST, true);
                            curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
                            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

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

                            // Step C: Insert into Notification_Bond_Win with actual Draw_Date
                            $insertStmt = $conn->prepare("INSERT INTO Notification_Bond_Win 
                                (User_ID, Title, Notice_, Bond_Series, Date, Draw_Number, Win_Number, Show_Or_Not, Send_Notification) 
                                VALUES (?, ?, ?, ?, ?, ?, ?, 0, 1)");
                            $noticeText = $body;
                            $insertStmt->bind_param("sssssss", $userId, $title, $noticeText, $bondSeries, $drawRow['Draw_Date'], $drawRow['Draw_Number'], $bondNumber);
                            $insertStmt->execute();
                            $insertStmt->close();

                            $notifications[] = [
                                "status" => "success",
                                "bond_number" => $bondNumber,
                                "draw_number" => $drawRow['Draw_Number'],
                                "draw_date" => $drawRow['Draw_Date'],
                                "fcm_response" => $fcmResponse
                            ];
                        }
                    }
                    $stmt->close();
                }
            }
            $userRes->close();
        }
    }

    $response = ["status" => "done", "notifications" => $notifications];

} catch (Exception $e) {
    $response = ["status" => "error", "message" => $e->getMessage()];
} finally {
    $conn->close();
}

echo json_encode($response, JSON_PRETTY_PRINT);
?>
