<?php
require_once '../../config/database.php';
require_once '../../config/auth.php';
require_once '../../config/rbac.php';
require_once '../../includes/functions.php';

header('Content-Type: application/json');

// Check authentication
if (!isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Authentication required']);
    exit;
}

$db = getDB();
$userId = $_SESSION['user_id'];

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

try {
    $questionId = $_POST['question_id'] ?? null;
    $status = $_POST['status'] ?? '';
    $reason = $_POST['reason'] ?? '';

    if (!$questionId || !in_array($status, ['draft', 'pending_review', 'approved', 'rejected'])) {
        throw new Exception('Invalid parameters');
    }

    // Check permissions
    if (in_array($status, ['approved', 'rejected']) && !hasRole('admin')) {
        throw new Exception('Only administrators can approve or reject questions');
    }

    // Check if user owns the question (for non-admin actions)
    if (!hasRole('admin')) {
        $stmt = $db->prepare("SELECT id FROM questions WHERE id = ? AND instructor_id = ?");
        $stmt->execute([$questionId, $userId]);
        if (!$stmt->fetch()) {
            throw new Exception('Question not found or access denied');
        }
    }

    // Update question status
    $stmt = $db->prepare("
        UPDATE questions SET
            status = ?,
            review_status = ?,
            updated_at = NOW()
        WHERE id = ?
    ");

    $reviewStatus = 'not_submitted';
    if ($status === 'pending_review') {
        $reviewStatus = 'pending';
    } elseif ($status === 'approved') {
        $reviewStatus = 'approved';
    } elseif ($status === 'rejected') {
        $reviewStatus = 'rejected';
    }

    $stmt->execute([$status, $reviewStatus, $questionId]);

    // Log the status change
    $action = ucfirst($status);
    if ($reason) {
        $action .= ': ' . $reason;
    }

    // You might want to add audit logging here
    // logQuestionAction($questionId, $action, $userId);

    echo json_encode([
        'success' => true,
        'message' => 'Question status updated successfully'
    ]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>