<?php
header('Content-Type: application/json; charset=utf-8');
include 'connection.php';
include 'decrypt_and_validate.php'; // contains decryptData()

$response = [];

try {
    if (!isset($_POST['user_id']) || !isset($_POST['API_Key'])) {
        throw new Exception("Missing parameters");
    }

    // Encrypted values from Android
    $uidEnc = $_POST['user_id'];
    $apiEnc = $_POST['API_Key'];

    // Decrypt both
    $userId = decryptData($uidEnc);
    $apiKey = decryptData($apiEnc);

    if (empty($userId)) {
        throw new Exception("Invalid user_id");
    }

    // Validate API key
    $validApiKey = "AbuTamim"; // your constant key
    if ($apiKey !== $validApiKey) {
        throw new Exception("Unauthorized API key");
    }

    $stmt = $conn->prepare("SELECT id, Title, Notice_, Bond_Series, Date, Draw_Number, Win_Number, Show_Or_Not, Send_Notification 
                            FROM Notification_Bond_Win 
                            WHERE User_ID = ? 
                            ORDER BY Date DESC");
    $stmt->bind_param("s", $userId);
    $stmt->execute();
    $result = $stmt->get_result();

    $notifications = [];
    while ($row = $result->fetch_assoc()) {
        $notifications[] = $row;
    }

    if (count($notifications) > 0) {
        $response = ["status" => "success", "notifications" => $notifications];
    } else {
        $response = ["status" => "empty", "message" => "No notifications found"];
    }

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

echo json_encode($response);
?>
