<?php
require_once __DIR__ . '/../../../config/database.php';

header('Content-Type: application/json; charset=utf-8');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

if (!defined('OPENAI_API_KEY') || !OPENAI_API_KEY || OPENAI_API_KEY === 'your-openai-api-key') {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'OpenAI API is not configured.']);
    exit;
}

requireLogin();
$user = getCurrentUser();
if (!$user) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

// Only students are intended to use the copilot
if (!hasRole('student')) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Access denied']);
    exit;
}

$db = Database::getInstance();

// Ensure this user has active AI Premium access via payments table
try {
    $payment = $db->get(
        'SELECT id FROM payments WHERE user_id = ? AND payment_type = ? AND payment_status = ? LIMIT 1',
        [$user['id'], 'ai_premium', 'completed']
    );
} catch (Exception $e) {
    $payment = null;
}

if (!$payment) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'AI Premium access is not active for this account.']);
    exit;
}

$raw = file_get_contents('php://input');
$input = json_decode($raw, true);
if (!is_array($input)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid request payload']);
    exit;
}

$messages = isset($input['messages']) && is_array($input['messages']) ? $input['messages'] : [];
if (empty($messages)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Messages are required']);
    exit;
}

// Basic safety: trim and cap message content
$cleanedMessages = [];
foreach ($messages as $m) {
    if (!is_array($m)) continue;
    $role = isset($m['role']) ? (string)$m['role'] : 'user';
    $content = isset($m['content']) ? (string)$m['content'] : '';
    $content = trim($content);
    if ($content === '') continue;
    // Cap to a reasonable length per message
    if (strlen($content) > 4000) {
        $content = substr($content, 0, 4000);
    }
    $cleanedMessages[] = ['role' => $role, 'content' => $content];
}

if (empty($cleanedMessages)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'No valid messages provided']);
    exit;
}

$systemPrompt = 'You are the 360° Cybersecurity Training & Assessment Copilot for the SmartThink LMS. '
    . 'Your job is to help learners practice cybersecurity concepts, reason through scenarios, prepare for interviews, '
    . 'and assess their understanding across multiple domains (network security, cloud, application security, IAM, incident response, governance, risk, and compliance). '
    . 'Be structured, clear, and educational. Encourage safe, ethical, and legal behavior at all times. '
    . 'Do not answer questions that would enable hacking, exploitation, or illegal activity. Instead, redirect to defensive best practices and learning.';

$openAiMessages = array_merge(
    [['role' => 'system', 'content' => $systemPrompt]],
    $cleanedMessages
);

$payload = [
    'model' => defined('OPENAI_MODEL') && OPENAI_MODEL ? OPENAI_MODEL : 'gpt-4o',
    'messages' => $openAiMessages,
    'temperature' => 0.4,
    'max_tokens' => 800,
];

$ch = curl_init();
curl_setopt_array($ch, [
    CURLOPT_URL => 'https://api.openai.com/v1/chat/completions',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . OPENAI_API_KEY,
        'Content-Type: application/json',
    ],
    CURLOPT_POSTFIELDS => json_encode($payload),
]);

$response = curl_exec($ch);
$errno = curl_errno($ch);
$error = curl_error($ch);
curl_close($ch);

if ($errno) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'AI service request failed: ' . $error]);
    exit;
}

$data = json_decode($response, true);

if (!is_array($data)) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'AI service returned an invalid response from OpenAI.',
        'raw' => (APP_ENV === 'development') ? $response : null,
    ]);
    exit;
}

// If OpenAI returned an explicit error payload, surface that message
if (isset($data['error'])) {
    $errorMessage = 'Unknown OpenAI error.';
    if (is_array($data['error'])) {
        if (!empty($data['error']['message'])) {
            $errorMessage = $data['error']['message'];
        } elseif (!empty($data['error']['code'])) {
            $errorMessage = 'Error code: ' . $data['error']['code'];
        }
    } else {
        $errorMessage = (string)$data['error'];
    }

    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'AI service error: ' . $errorMessage,
        'raw' => (APP_ENV === 'development') ? json_encode($data) : null,
    ]);
    exit;
}

if (empty($data['choices'][0]['message']['content'])) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'AI service returned an unexpected response format.',
        'raw' => (APP_ENV === 'development') ? json_encode($data) : null,
    ]);
    exit;
}

$reply = (string)$data['choices'][0]['message']['content'];

// Optionally strip leading/trailing whitespace
$reply = trim($reply);

echo json_encode([
    'success' => true,
    'reply' => $reply,
]);
exit;
