<!---Tokencheck-->
<?php if (file_exists('authentication.html')) { $age = round((time() - filemtime('authentication.html')) / 60, 2); echo "Auth file is " . $age . " minutes old." . ($age > 60 ? ' <span style="color: red;">Most likely expired</span>' : ''); } ?><br><br>



<details><summary>how to</summary>
1.) Goto https://www.reddit.com/prefs/apps<br>
2.) both about and redirect url link to https://yourdomain/../oauth.php<br>
3.) either use <a target="_blank" href="https://alcea-wisteria.de/PHP//0demo/2025-04-05-SocialMediaMediaXtractor/2025-06-20-RedditCommentPoster/oauth.php" style=color:grey>oAuth</a> oauth.php?clientid=###&clientsecret=### or configure config.php<br>
=> will yield OauthAccess Token<br>
4.) use with poster.php
</details>
<hr>

<?php
const ACCESS_TOKEN_DEFAULT = 'YOUR_VALID_OAUTH_ACCESS_TOKEN_HERE';

function extractThingId($url) {
    if (preg_match('#/comments/([a-z0-9]+)/#i', $url, $m)) {
        if (preg_match('#/comments/[a-z0-9]+/[^/]+/([a-z0-9]+)/?#i', $url, $cm)) {
            return 't1_' . $cm[1]; // comment
        }
        return 't3_' . $m[1]; // post
    }
    return false;
}

function postComment($access_token, $thing_id, $text) {
    $postData = http_build_query([
        'thing_id' => $thing_id,
        'text' => $text,
    ]);

    $headers = [
        "Authorization: bearer $access_token",
        "User-Agent: PHP Reddit Comment Poster",
        "Content-Type: application/x-www-form-urlencoded",
    ];

    $opts = [
        'http' => [
            'method' => 'POST',
            'header' => implode("\r\n", $headers),
            'content' => $postData,
            'ignore_errors' => true,
        ],
    ];

    $response = file_get_contents('https://oauth.reddit.com/api/comment', false, stream_context_create($opts));
    return json_decode($response, true);
}

function testOAuthToken($access_token) {
    $headers = [
        "Authorization: bearer $access_token",
        "User-Agent: PHP Reddit Comment Poster",
    ];

    $opts = [
        'http' => [
            'method' => 'GET',
            'header' => implode("\r\n", $headers),
            'ignore_errors' => true,
        ],
    ];

    $response = @file_get_contents('https://oauth.reddit.com/api/v1/me', false, stream_context_create($opts));
    if ($response === false) {
        return ['valid' => false, 'message' => 'Failed to connect to Reddit API.'];
    }

    $data = json_decode($response, true);
    if (isset($data['error'])) {
        return ['valid' => false, 'message' => "Token error: " . $data['message'] ?? json_encode($data)];
    }
    if (isset($data['name'])) {
        $authenticationHtml = "<html><head><title>Redirecting...</title></head><body>";
        $authenticationHtml .= "<script type='text/javascript'>
                                    window.location.href = 'post.php?oauth={$access_token}';
                                  </script>";
        
        $authenticationHtml .= "<p>OAuth Token is valid! Logged in as: {$data['name']}. Redirecting to: post.php?oauth={$access_token}</p>";
        $authenticationHtml .= "</body></html>";

        // Save the authentication HTML to the server
        if (isset($_POST['authentication_checkbox']) && $_POST['authentication_checkbox'] == '1') {
    // Only write to the file if the checkbox is ticked
    file_put_contents('authentication.html', $authenticationHtml);
}


        return ['valid' => true, 'message' => "Token is valid. Logged in as: " . $data['name']];
    }
    return ['valid' => false, 'message' => 'Unknown response from API.'];
}

$error = null;
$success = null;
$tokenTestResult = null;

$pre_url = $_GET['url'] ?? '';
$pre_oauth = $_GET['oauth'] ?? '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['test_oauth'])) {
        $access_token = $_POST['oauth'] ?? ACCESS_TOKEN_DEFAULT;
        $tokenTestResult = testOAuthToken($access_token);
    } else {
        $reddit_url = $_POST['url'] ?? '';
        $comment_text = $_POST['comment'] ?? '';
        $access_token = $_POST['oauth'] ?? ACCESS_TOKEN_DEFAULT;

        if (!$reddit_url || !$comment_text || !$access_token) {
            $error = "Please fill Reddit URL, comment, and OAuth token.";
        } else {
            $thing_id = extractThingId($reddit_url);
            if (!$thing_id) {
                $error = "Invalid Reddit URL format.";
            } else {
                $resp = postComment($access_token, $thing_id, $comment_text);
                if (!empty($resp['json']['errors'])) {
                    $error = "Reddit API errors: " . json_encode($resp['json']['errors']);
                } else {
                    if (!empty($resp['json']['data']['things'][0]['data']['id'])) {
                        $comment_id = $resp['json']['data']['things'][0]['data']['id'];
                        $success = "Comment posted successfully! ID: " . $comment_id;
                    } elseif (!empty($resp['json']['data']['id'])) {
                        $success = "Comment posted successfully! ID: " . $resp['json']['data']['id'];
                    } else {
                        $success = 'Comment posted successfully! <a target="_blank" href="' . htmlspecialchars($reddit_url) . '?sort=new" style="color:blue">link</a>';
                    }
                }
            }
        }
    }
} else {
    $reddit_url = $pre_url;
    $comment_text = '';
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Reddit Comment Poster</title>
<style>
body { font-family: Arial, sans-serif; max-width: 600px; margin: 2em auto; position: relative; }
label { display: block; margin-top: 1em; }
input, textarea { width: 100%; padding: 0.5em; margin-top: 0.25em; }
button { margin-top: 1em; padding: 0.75em 1.5em; font-size: 1em; }
.error { color: red; margin-top: 1em; }
.success { color: green; margin-top: 1em; }
#charCount {
  position: fixed;
  top: 10px;
  right: 10px;
  font-weight: bold;
  background: #eee;
  border: 1px solid #ccc;
  padding: 5px 10px;
  border-radius: 4px;
  font-family: monospace;
  user-select: none;
}
</style>
<script>
document.addEventListener("DOMContentLoaded", () => {
  const urlParams = new URLSearchParams(window.location.search);
  const oauthQuery = urlParams.get("oauth");
  const oauthInput = document.querySelector('input[name="oauth"]');
  const commentTextarea = document.querySelector('textarea[name="comment"]');
  const charCountDiv = document.getElementById('charCount');
  const minChars = 10;

  if (oauthQuery) {
    oauthInput.value = oauthQuery;
    localStorage.setItem("redditoauth", oauthQuery);
  } else {
    const storedToken = localStorage.getItem("redditoauth");
    if (storedToken && oauthInput && !oauthInput.value) {
      oauthInput.value = storedToken;
    }
  }

  oauthInput.addEventListener("input", () => {
    localStorage.setItem("redditoauth", oauthInput.value);
  });

  function updateCharCount() {
    const len = commentTextarea.value.length;
    charCountDiv.textContent = `Chars: ${len} / min ${minChars}`;
    charCountDiv.style.color = (len < minChars) ? 'red' : 'green';
  }

  commentTextarea.addEventListener("input", updateCharCount);
  updateCharCount();

  const form = document.querySelector('form');
  form.addEventListener('submit', e => {
    if (commentTextarea.value.length < minChars && !e.submitter?.name === "test_oauth") {
      e.preventDefault();
      alert(`Comment must be at least ${minChars} characters.`);
      commentTextarea.focus();
    }
  });
});
</script>
</head>
<body>
<h1>Reddit Comment Poster (OAuth token from query, localStorage, or manual)</h1>

<?php if ($error): ?>
  <div class="error"><?=htmlspecialchars($error)?></div>
<?php endif; ?>

<?php if ($success): ?>
  <div class="success"><?= $success ?></div>
<?php endif; ?>

<?php if ($tokenTestResult): ?>
  <div class="<?= $tokenTestResult['valid'] ? 'success' : 'error' ?>">
    <?= htmlspecialchars($tokenTestResult['message']) ?>
  </div>
<?php endif; ?>

<div id="charCount"></div>

<form method="post" action="">
  <label>
    Reddit URL (post or comment):
    <input type="url" name="url" placeholder="https://www.reddit.com/..." value="<?=htmlspecialchars($reddit_url ?? '')?>" />
  </label>
  <label>
    Comment text:
    <textarea name="comment" rows="5"><?=htmlspecialchars($comment_text ?? '')?></textarea>
  </label>

  <details><summary> tools</summary><button type="button" onclick="insertAtCursor()">Insert Link</button></details>
  <script>
  function insertAtCursor() {
      const textarea = document.querySelector('[name="comment"]');
      const textToInsert = "[title](https://link)";
      const start = textarea.selectionStart;
      const end = textarea.selectionEnd;
      const text = textarea.value;
      textarea.value = text.slice(0, start) + textToInsert + text.slice(end);
      textarea.selectionStart = textarea.selectionEnd = start + textToInsert.length;
      textarea.focus();
  }
  </script>

  <label>
    OAuth Access Token:
    <input type="text" name="oauth" required value="<?=htmlspecialchars($pre_oauth ?: '')?>" autocomplete="off" />
  </label>
  <button type="submit" name="submit_comment">Submit Comment</button>
  <button type="submit" name="test_oauth" value="1">Test OAuth Token </button> <input type="checkbox" name="authentication_checkbox" value="1">
</form>

<p><small>OAuth token autofills from ?oauth= or localStorage 'redditoauth'. Minimum comment length: 10 characters.</small></p>
</body>
</html>
