<?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");
    }

    $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
    if ($apiKey !== $validApiKey) {
        throw new Exception("Unauthorized API key");
    }

    $stmt = $conn->prepare("SELECT COUNT(*) as unread_count 
                            FROM Notification_Bond_Win 
                            WHERE User_ID = ? AND Show_Or_Not = 0");
    $stmt->bind_param("s", $userId);
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();

    $response = ["status" => "success", "unread_count" => intval($row['unread_count'])];

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

echo json_encode($response);
?>
