<?php

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

$DB_HOST = 'localhost';
$DB_NAME = 'menthanecon_oddroadmin';
$DB_USER = 'root';
$DB_PASS = '';

$API_KEY = 'supersecretkey123';

// Base URLs for media
$BASE_URL = 'http://localhost/oddroadmin.moneycardwave.com';
$IMAGE_BASE_URL = $BASE_URL . '/questionbank/images/';
$AUDIO_BASE_URL = $BASE_URL . '/questionbank/audio/';

try {
    $pdo = new PDO(
        "mysql:host=$DB_HOST;dbname=$DB_NAME;charset=utf8mb4",
        $DB_USER,
        $DB_PASS,
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
    );
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode([
        'status' => false,
        'message' => 'Database connection failed',
        'error' => $e->getMessage()
    ]);
    exit;
}

function response($status, $message, $data = null)
{
    echo json_encode([
        'status' => $status,
        'message' => $message,
        'data' => $data
    ]);
    exit;
}

function authenticateRequest($expectedKey)
{
    $headers = getallheaders();
    $providedKey = null;

    if (isset($headers['X-API-KEY'])) {
        $providedKey = $headers['X-API-KEY'];
    } elseif (isset($_SERVER['HTTP_X_API_KEY'])) {
        $providedKey = $_SERVER['HTTP_X_API_KEY'];
    }

    if (!$providedKey) {
        http_response_code(401);
        response(false, 'Missing API Key');
    }

    if ($providedKey !== $expectedKey) {
        http_response_code(403);
        response(false, 'Invalid API Key');
    }
}

function handleFileUpload($file, $targetDir)
{
    if (!isset($file['name']) || $file['error'] !== UPLOAD_ERR_OK) {
        return null;
    }

    $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
    $filename = uniqid() . '.' . $extension;
    $targetFile = $targetDir . $filename;

    if (move_uploaded_file($file['tmp_name'], $targetFile)) {
        return $filename;
    }

    return null;
}

?>