<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once 'config.php';

function debug_log($message) {
    error_log("[DEBUG] " . $message);
}

// Start OAuth flow
session_start();

try {
    if (isset($_GET['error'])) {
        throw new Exception("OAuth error: " . htmlspecialchars($_GET['error']));
    }

    if (!isset($_GET['code'])) {
        // Step 1: Redirect user to Reddit authorization URL
        $state = bin2hex(random_bytes(8));
        $_SESSION['oauth_state'] = $state;

        $params = http_build_query([
            'client_id' => CLIENT_ID,
            'response_type' => 'code',
            'state' => $state,
            'redirect_uri' => REDIRECT_URI,
            'duration' => 'temporary',
            'scope' => 'submit identity',
        ]);

        $authUrl = "https://www.reddit.com/api/v1/authorize?" . $params;
        debug_log("Redirecting user to authorization URL: $authUrl");
        header("Location: $authUrl");
        exit;
    } else {
        // Step 2: Handle callback with code
        if (!isset($_GET['state']) || $_GET['state'] !== $_SESSION['oauth_state']) {
            throw new Exception("Invalid OAuth state");
        }

        $code = $_GET['code'];
        debug_log("Received OAuth code: $code");

        // Prepare token request
        $postData = http_build_query([
            'grant_type' => 'authorization_code',
            'code' => $code,
            'redirect_uri' => REDIRECT_URI,
        ]);

        $headers = [
            "Authorization: Basic " . base64_encode(CLIENT_ID . ":" . CLIENT_SECRET),
            "Content-Type: application/x-www-form-urlencoded",
            "User-Agent: " . USER_AGENT,
        ];

        debug_log("Requesting access token with POST data: $postData");

        $context = stream_context_create([
            'http' => [
                'method' => 'POST',
                'header' => implode("\r\n", $headers),
                'content' => $postData,
                'ignore_errors' => true,  // Capture error response bodies
            ]
        ]);

        $response = file_get_contents('https://www.reddit.com/api/v1/access_token', false, $context);
        debug_log("Token endpoint response: $response");

        if ($response === false) {
            throw new Exception("Failed to get access token from Reddit");
        }

        $tokenData = json_decode($response, true);
        if (!isset($tokenData['access_token'])) {
            throw new Exception("No access token in response: " . $response);
        }

        $accessToken = $tokenData['access_token'];
        debug_log("Access token received: $accessToken");

        // Here you can proceed to submit comment or get user identity with $accessToken

        echo "OAuth success! Access token: " . htmlspecialchars($accessToken);
    }
} catch (Exception $e) {
    error_log("[ERROR] " . $e->getMessage());
    echo "<h2>Error during OAuth process</h2>";
    echo "<p>" . htmlspecialchars($e->getMessage()) . "</p>";
    echo "<pre>Debug info:\n" . print_r($_GET, true) . "</pre>";
}
