<?php
/**
 * OpenAI Explanation API Endpoint
 * Proxies requests to OpenAI API to explain quiz answers
 */

// Set headers for JSON response and CORS
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

// Read OpenAI API key from environment variable
$apiKey = getenv('OPENAI_API_KEY');

// If not in environment, try reading from .env file
if (!$apiKey) {
    $envFile = dirname(__DIR__) . '/.env';
    if (file_exists($envFile)) {
        $lines = file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        foreach ($lines as $line) {
            $line = trim($line);
            if (empty($line) || strpos($line, '#') === 0) {
                continue; // Skip comments and empty lines
            }
            if (strpos($line, '=') === false) {
                continue; // Skip lines without =
            }
            $parts = explode('=', $line, 2);
            if (count($parts) === 2 && trim($parts[0]) === 'OPENAI_API_KEY') {
                $apiKey = trim($parts[1]);
                break;
            }
        }
    }
}

if (!$apiKey) {
    http_response_code(500);
    echo json_encode(['error' => 'OpenAI API key not configured']);
    exit;
}

// Get request body
$input = file_get_contents('php://input');
$data = json_decode($input, true);

if (!$data) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid JSON data']);
    exit;
}

// Validate required fields
$required = ['question', 'selectedAnswer', 'selectedAnswerText', 'correctAnswers', 'choiceA', 'choiceB', 'choiceC', 'choiceD'];
foreach ($required as $field) {
    if (!isset($data[$field])) {
        http_response_code(400);
        echo json_encode(['error' => "Missing required field: $field"]);
        exit;
    }
}

// Sanitize input
$question = htmlspecialchars($data['question'], ENT_QUOTES, 'UTF-8');
$selectedAnswer = htmlspecialchars($data['selectedAnswer'], ENT_QUOTES, 'UTF-8');
$selectedAnswerText = htmlspecialchars($data['selectedAnswerText'], ENT_QUOTES, 'UTF-8');
$correctAnswers = is_array($data['correctAnswers']) ? $data['correctAnswers'] : [$data['correctAnswers']];
$choiceA = htmlspecialchars($data['choiceA'], ENT_QUOTES, 'UTF-8');
$choiceB = htmlspecialchars($data['choiceB'], ENT_QUOTES, 'UTF-8');
$choiceC = htmlspecialchars($data['choiceC'], ENT_QUOTES, 'UTF-8');
$choiceD = htmlspecialchars($data['choiceD'], ENT_QUOTES, 'UTF-8');

// Build prompt
$correctAnswersText = implode(', ', $correctAnswers);
$isCorrect = in_array($selectedAnswer, $correctAnswers);

$prompt = "You are an AWS certification exam tutor. Explain why the answer to this question is correct or incorrect.

Question: {$question}

Selected Answer: {$selectedAnswer}. {$selectedAnswerText}
Correct Answer(s): {$correctAnswersText}

All Options:
A. {$choiceA}
B. {$choiceB}
C. {$choiceC}
D. {$choiceD}

Provide a clear, educational explanation. " . ($isCorrect ? "The selected answer is correct." : "The selected answer is incorrect.") . " Explain why.";

// Prepare OpenAI API request
$openaiUrl = 'https://api.openai.com/v1/chat/completions';

$payload = [
    'model' => 'gpt-3.5-turbo',
    'messages' => [
        [
            'role' => 'system',
            'content' => 'You are a helpful AWS certification exam tutor. Provide clear, concise explanations.'
        ],
        [
            'role' => 'user',
            'content' => $prompt
        ]
    ],
    'max_tokens' => 300,
    'temperature' => 0.7
];

// Initialize cURL
$ch = curl_init($openaiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Bearer ' . $apiKey
]);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
// SSL certificate handling - use system certificates or disable for local dev
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
// Try to use system certificate store (Windows)
if (PHP_OS_FAMILY === 'Windows') {
    // Try common Windows certificate locations
    $certPaths = [
        getenv('CURL_CA_BUNDLE'),
        getenv('SSL_CERT_FILE'),
        'C:\\Windows\\System32\\curl-ca-bundle.crt',
        ini_get('curl.cainfo'),
        ini_get('openssl.cafile')
    ];
    foreach ($certPaths as $certPath) {
        if ($certPath && file_exists($certPath)) {
            curl_setopt($ch, CURLOPT_CAINFO, $certPath);
            break;
        }
    }
    // If no certificate found, disable verification for local development
    // WARNING: Only for local development, not for production!
    if (!isset($certPath) || !file_exists($certPath)) {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    }
}

// Execute request
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);

// Handle errors
if ($curlError) {
    http_response_code(500);
    echo json_encode(['error' => 'Failed to connect to OpenAI API: ' . $curlError]);
    exit;
}

if ($httpCode !== 200) {
    http_response_code($httpCode);
    $errorData = json_decode($response, true);
    $errorMsg = isset($errorData['error']['message']) ? $errorData['error']['message'] : 'OpenAI API error';
    echo json_encode(['error' => $errorMsg]);
    exit;
}

// Parse response
$responseData = json_decode($response, true);

if (!isset($responseData['choices'][0]['message']['content'])) {
    http_response_code(500);
    echo json_encode(['error' => 'Invalid response from OpenAI API']);
    exit;
}

$explanation = trim($responseData['choices'][0]['message']['content']);

// Return explanation
echo json_encode([
    'explanation' => $explanation,
    'success' => true
]);
