<?php
/**
 * BlogPostAI Main Entry Point
 */

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../config/routes.php';
require_once __DIR__ . '/../api/auth.php';

// Initialize router
$router = new Router();

// ============================================
// Public Routes (No Authentication)
// ============================================

$router->get('/', function() {
    Response::json([
        'name' => 'BlogPostAI API',
        'version' => '1.0.0',
        'status' => 'running',
        'timestamp' => date('Y-m-d H:i:s')
    ]);
});

$router->get('/health', function() {
    try {
        $db = Database::getInstance()->getConnection();
        $stmt = $db->query('SELECT 1');
        $dbStatus = $stmt !== false ? 'ok' : 'error';
    } catch (Exception $e) {
        $dbStatus = 'error';
    }

    Response::json([
        'status' => $dbStatus === 'ok' ? 'healthy' : 'unhealthy',
        'database' => $dbStatus,
        'timestamp' => date('Y-m-d H:i:s')
    ]);
});

// ============================================
// Authentication Routes
// ============================================

$router->post('/api/auth/login', function() {
    $body = getRequestBody();
    $username = $body['username'] ?? '';
    $password = $body['password'] ?? '';

    if (empty($username) || empty($password)) {
        Response::error('Username and password are required', 400);
    }

    $auth = new AuthService();
    $result = $auth->login($username, $password);

    if ($result['success']) {
        $auth->logAudit('user.login', 'user', $result['user']['id']);
        Response::success($result);
    } else {
        Response::error($result['message'], 401);
    }
});

$router->post('/api/auth/logout', function() {
    $auth = new AuthService();
    $user = $auth->getCurrentUser();

    if ($user) {
        $auth->logAudit('user.logout', 'user', $user['id']);
    }

    $result = $auth->logout();
    Response::success($result);
});

$router->get('/api/auth/me', function() {
    if (!requireAuth()) return;

    $auth = new AuthService();
    $user = $GLOBALS['current_user'];
    $permissions = $auth->getUserPermissions($user['id']);

    Response::success([
        'user' => $user,
        'permissions' => $permissions
    ]);
});

// ============================================
// Settings API (Requires Authentication)
// ============================================

$router->get('/api/settings', function() {
    if (!requireAuth()) return;

    $auth = new AuthService();
    $user = $GLOBALS['current_user'];

    if (!$auth->hasPermission($user['id'], 'program.settings', 'read')) {
        Response::error('Permission denied', 403);
    }

    $db = Database::getInstance()->getConnection();
    $stmt = $db->query("
        SELECT section, `key`, value_encrypted, is_sensitive
        FROM settings
        ORDER BY section, `key`
    ");

    $settings = [];
    while ($row = $stmt->fetch()) {
        if (!isset($settings[$row['section']])) {
            $settings[$row['section']] = [];
        }

        // Mask sensitive values
        $value = $row['value_encrypted'];
        if ($row['is_sensitive'] && !empty($value)) {
            $value = str_repeat('•', 8);
        }

        $settings[$row['section']][$row['key']] = $value;
    }

    Response::success($settings);
});

$router->put('/api/settings/{section}', function($section) {
    if (!requireAuth()) return;

    $auth = new AuthService();
    $user = $GLOBALS['current_user'];

    if (!$auth->hasPermission($user['id'], 'program.settings', 'config')) {
        Response::error('Permission denied', 403);
    }

    $body = getRequestBody();
    $db = Database::getInstance()->getConnection();

    try {
        $db->beginTransaction();

        foreach ($body as $key => $value) {
            // Check if key exists
            $stmt = $db->prepare("SELECT id, version, is_sensitive FROM settings WHERE section = ? AND `key` = ?");
            $stmt->execute([$section, $key]);
            $existing = $stmt->fetch();

            if ($existing) {
                // Save to version history
                $stmt = $db->prepare("
                    INSERT INTO settings_versions (section, `key`, value_encrypted, version, updated_by)
                    SELECT section, `key`, value_encrypted, version, updated_by
                    FROM settings
                    WHERE section = ? AND `key` = ?
                ");
                $stmt->execute([$section, $key]);

                // Update current setting
                $stmt = $db->prepare("
                    UPDATE settings
                    SET value_encrypted = ?, version = version + 1, updated_by = ?
                    WHERE section = ? AND `key` = ?
                ");
                $stmt->execute([$value, $user['id'], $section, $key]);
            } else {
                // Insert new setting
                $stmt = $db->prepare("
                    INSERT INTO settings (section, `key`, value_encrypted, updated_by)
                    VALUES (?, ?, ?, ?)
                ");
                $stmt->execute([$section, $key, $value, $user['id']]);
            }
        }

        $db->commit();

        $auth->logAudit('settings.update', 'settings', $section, ['keys' => array_keys($body)]);

        Response::success(['message' => 'Settings updated successfully']);

    } catch (Exception $e) {
        $db->rollBack();
        Response::error('Failed to update settings: ' . $e->getMessage(), 500);
    }
});

// ============================================
// Users API (Requires User Admin Permission)
// ============================================

$router->get('/api/users', function() {
    if (!requireAuth()) return;

    $auth = new AuthService();
    $user = $GLOBALS['current_user'];

    if (!$auth->hasPermission($user['id'], 'program.user_admin', 'read')) {
        Response::error('Permission denied', 403);
    }

    $db = Database::getInstance()->getConnection();
    $stmt = $db->query("
        SELECT id, username, email, full_name, locale, timezone, status,
               twofa_enabled, created_at, last_login_at
        FROM users
        WHERE status != 'deleted'
        ORDER BY created_at DESC
    ");

    $users = $stmt->fetchAll();
    Response::success($users);
});

$router->post('/api/users', function() {
    if (!requireAuth()) return;

    $auth = new AuthService();
    $user = $GLOBALS['current_user'];

    if (!$auth->hasPermission($user['id'], 'program.user_admin', 'create')) {
        Response::error('Permission denied', 403);
    }

    $body = getRequestBody();
    $username = $body['username'] ?? '';
    $password = $body['password'] ?? '';
    $email = $body['email'] ?? null;
    $fullName = $body['full_name'] ?? null;

    if (empty($username) || empty($password)) {
        Response::error('Username and password are required', 400);
    }

    if (strlen($password) < PASSWORD_MIN_LENGTH) {
        Response::error('Password must be at least ' . PASSWORD_MIN_LENGTH . ' characters', 400);
    }

    $db = Database::getInstance()->getConnection();

    try {
        $passwordHash = password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);

        $stmt = $db->prepare("
            INSERT INTO users (username, password_hash, email, full_name)
            VALUES (?, ?, ?, ?)
        ");
        $stmt->execute([$username, $passwordHash, $email, $fullName]);

        $newUserId = $db->lastInsertId();

        $auth->logAudit('user.create', 'user', $newUserId, ['username' => $username]);

        Response::success([
            'id' => $newUserId,
            'username' => $username,
            'message' => 'User created successfully'
        ], 201);

    } catch (PDOException $e) {
        if ($e->getCode() == 23000) { // Duplicate entry
            Response::error('Username already exists', 409);
        }
        Response::error('Failed to create user: ' . $e->getMessage(), 500);
    }
});

// ============================================
// Audit Logs API
// ============================================

$router->get('/api/audit', function() {
    if (!requireAuth()) return;

    $auth = new AuthService();
    $user = $GLOBALS['current_user'];

    if (!$auth->hasPermission($user['id'], 'program.audit', 'read')) {
        Response::error('Permission denied', 403);
    }

    $params = getQueryParams();
    $limit = isset($params['limit']) ? (int)$params['limit'] : 50;
    $offset = isset($params['offset']) ? (int)$params['offset'] : 0;

    $db = Database::getInstance()->getConnection();
    $stmt = $db->prepare("
        SELECT a.*, u.username, u.full_name
        FROM audit_logs a
        LEFT JOIN users u ON a.actor_user_id = u.id
        ORDER BY a.created_at DESC
        LIMIT ? OFFSET ?
    ");
    $stmt->execute([$limit, $offset]);

    $logs = $stmt->fetchAll();
    Response::success($logs);
});

// ============================================
// WebChat AI API
// ============================================

require_once __DIR__ . '/../api/webchat.php';

$router->post('/api/chat/send', function() {
    if (!requireAuth()) return;

    $auth = new AuthService();
    $user = $GLOBALS['current_user'];

    // Check if user has permission to use webchat
    $isAdmin = $auth->hasPermission($user['id'], 'program.webchat_admin', 'execute');
    $isFrontend = $auth->hasPermission($user['id'], 'program.webchat_front', 'execute');

    if (!$isAdmin && !$isFrontend) {
        Response::error('Permission denied', 403);
    }

    $body = getRequestBody();
    $message = $body['message'] ?? '';
    $sessionId = $body['session_id'] ?? null;

    if (empty($message)) {
        Response::error('Message is required', 400);
    }

    $chatService = new WebChatService();
    $result = $chatService->chat($user['id'], $message, $sessionId);

    if ($result['success']) {
        // Return result directly without double-wrapping
        Response::json($result);
    } else {
        Response::error($result['message'], 500);
    }
});

$router->get('/api/chat/history', function() {
    if (!requireAuth()) return;

    $user = $GLOBALS['current_user'];
    $params = getQueryParams();
    $sessionId = $params['session_id'] ?? null;
    $limit = isset($params['limit']) ? (int)$params['limit'] : 50;

    $chatService = new WebChatService();
    $history = $chatService->getChatHistory($user['id'], $sessionId, $limit);

    Response::success($history);
});

$router->post('/api/chat/clear', function() {
    if (!requireAuth()) return;

    $user = $GLOBALS['current_user'];
    $body = getRequestBody();
    $sessionId = $body['session_id'] ?? null;

    $chatService = new WebChatService();
    $result = $chatService->clearChatHistory($user['id'], $sessionId);

    Response::success($result);
});

// ============================================
// Ollama Server Management API
// ============================================

$router->get('/api/ollama/servers', function() {
    if (!requireAuth()) return;

    $auth = new AuthService();
    $user = $GLOBALS['current_user'];

    if (!$auth->hasPermission($user['id'], 'program.settings', 'read')) {
        Response::error('Permission denied', 403);
    }

    $db = Database::getInstance()->getConnection();
    $stmt = $db->query("
        SELECT id, server_name, ip, port, is_default, last_health, created_at, updated_at
        FROM ollama_servers
        ORDER BY is_default DESC, created_at DESC
    ");

    $servers = $stmt->fetchAll();
    Response::success($servers);
});

$router->post('/api/ollama/servers', function() {
    if (!requireAuth()) return;

    $auth = new AuthService();
    $user = $GLOBALS['current_user'];

    if (!$auth->hasPermission($user['id'], 'program.settings', 'config')) {
        Response::error('Permission denied', 403);
    }

    $body = getRequestBody();
    $serverName = $body['server_name'] ?? '';
    $ip = $body['ip'] ?? '';
    $port = isset($body['port']) ? (int)$body['port'] : 11434;
    $isDefault = !empty($body['is_default']);

    if (empty($serverName) || empty($ip)) {
        Response::error('Server name and IP are required', 400);
    }

    $db = Database::getInstance()->getConnection();

    try {
        $db->beginTransaction();

        // If this is set as default, unset others
        if ($isDefault) {
            $db->exec("UPDATE ollama_servers SET is_default = 0");
        }

        $stmt = $db->prepare("
            INSERT INTO ollama_servers (server_name, ip, port, is_default)
            VALUES (?, ?, ?, ?)
        ");
        $stmt->execute([$serverName, $ip, $port, $isDefault ? 1 : 0]);

        $serverId = $db->lastInsertId();
        $db->commit();

        $auth->logAudit('ollama.server.create', 'ollama_server', $serverId, [
            'server_name' => $serverName,
            'ip' => $ip
        ]);

        Response::success(['id' => $serverId, 'message' => 'Ollama server added successfully']);

    } catch (Exception $e) {
        $db->rollBack();
        Response::error('Failed to add Ollama server: ' . $e->getMessage(), 500);
    }
});

$router->post('/api/ollama/servers/{id}/test', function($id) {
    if (!requireAuth()) return;

    $auth = new AuthService();
    $user = $GLOBALS['current_user'];

    if (!$auth->hasPermission($user['id'], 'program.settings', 'config')) {
        Response::error('Permission denied', 403);
    }

    $db = Database::getInstance()->getConnection();
    $stmt = $db->prepare("SELECT ip, port FROM ollama_servers WHERE id = ?");
    $stmt->execute([$id]);
    $server = $stmt->fetch();

    if (!$server) {
        Response::error('Server not found', 404);
    }

    // Test connection to Ollama server
    $url = "http://{$server['ip']}:{$server['port']}/api/version";
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);

    $startTime = microtime(true);
    $response = curl_exec($ch);
    $responseTime = round((microtime(true) - $startTime) * 1000, 2);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    $healthData = [
        'status' => $httpCode === 200 ? 'healthy' : 'unhealthy',
        'http_code' => $httpCode,
        'response_time_ms' => $responseTime,
        'tested_at' => date('Y-m-d H:i:s')
    ];

    // Update health status
    $stmt = $db->prepare("UPDATE ollama_servers SET last_health = ? WHERE id = ?");
    $stmt->execute([json_encode($healthData), $id]);

    if ($httpCode === 200) {
        Response::success($healthData);
    } else {
        Response::error('Connection test failed', 500, $healthData);
    }
});

$router->get('/api/ollama/servers/{id}/models', function($id) {
    if (!requireAuth()) return;

    $auth = new AuthService();
    $user = $GLOBALS['current_user'];

    if (!$auth->hasPermission($user['id'], 'program.settings', 'read')) {
        Response::error('Permission denied', 403);
    }

    $db = Database::getInstance()->getConnection();
    $stmt = $db->prepare("SELECT ip, port FROM ollama_servers WHERE id = ?");
    $stmt->execute([$id]);
    $server = $stmt->fetch();

    if (!$server) {
        Response::error('Server not found', 404);
    }

    // Fetch models from Ollama server
    $url = "http://{$server['ip']}:{$server['port']}/api/tags";
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpCode !== 200) {
        Response::error('Failed to fetch models from Ollama server', 500);
    }

    $result = json_decode($response, true);
    $models = $result['models'] ?? [];

    // Cache models in database
    try {
        $db->beginTransaction();

        // Clear old cache for this server
        $stmt = $db->prepare("DELETE FROM ollama_models_cache WHERE server_id = ?");
        $stmt->execute([$id]);

        // Insert new models
        $stmt = $db->prepare("
            INSERT INTO ollama_models_cache (server_id, name, size_bytes, modified_at)
            VALUES (?, ?, ?, ?)
        ");

        foreach ($models as $model) {
            $stmt->execute([
                $id,
                $model['name'] ?? '',
                $model['size'] ?? null,
                isset($model['modified_at']) ? date('Y-m-d H:i:s', strtotime($model['modified_at'])) : null
            ]);
        }

        $db->commit();

        Response::success($models);

    } catch (Exception $e) {
        $db->rollBack();
        Response::error('Failed to cache models: ' . $e->getMessage(), 500);
    }
});

// ============================================
// Publishing API (Requires Authentication)
// ============================================

require_once __DIR__ . '/../api/publishing.php';
require_once __DIR__ . '/../api/facebook.php';
require_once __DIR__ . '/../api/instagram.php';
require_once __DIR__ . '/../api/xiaohongshu.php';

// Publish to multiple platforms
$router->post('/api/publish', function() {
    if (!requireAuth()) return;

    $auth = new AuthService();
    $user = $GLOBALS['current_user'];

    if (!$auth->hasPermission($user['id'], 'program.publishing', 'create')) {
        Response::error('Permission denied', 403);
    }

    $body = getRequestBody();
    $platforms = $body['platforms'] ?? [];
    $data = $body['data'] ?? [];

    if (empty($platforms) || empty($data)) {
        Response::error('Missing platforms or data', 400);
    }

    $publishing = new PublishingService();
    $result = $publishing->publish($data, $platforms);

    if ($result['success']) {
        $auth->logAudit('publish.create', 'publish', null, [
            'platforms' => $platforms,
            'summary' => $result['summary']
        ]);
    }

    Response::json($result);
});

// Schedule publication
$router->post('/api/publish/schedule', function() {
    if (!requireAuth()) return;

    $auth = new AuthService();
    $user = $GLOBALS['current_user'];

    if (!$auth->hasPermission($user['id'], 'program.publishing', 'create')) {
        Response::error('Permission denied', 403);
    }

    $body = getRequestBody();
    $platforms = $body['platforms'] ?? [];
    $data = $body['data'] ?? [];
    $scheduledTime = $body['scheduled_time'] ?? '';

    if (empty($platforms) || empty($data) || empty($scheduledTime)) {
        Response::error('Missing required fields', 400);
    }

    $publishing = new PublishingService();
    $result = $publishing->schedulePublish($data, $platforms, $scheduledTime);

    if ($result['success']) {
        $auth->logAudit('publish.schedule', 'publish', $result['data']['schedule_id']);
    }

    Response::json($result);
});

// Get publication history
$router->get('/api/publish/history', function() {
    if (!requireAuth()) return;

    $auth = new AuthService();
    $user = $GLOBALS['current_user'];

    if (!$auth->hasPermission($user['id'], 'program.publishing', 'read')) {
        Response::error('Permission denied', 403);
    }

    $filters = [
        'platform' => $_GET['platform'] ?? null,
        'status' => $_GET['status'] ?? null,
        'date_from' => $_GET['date_from'] ?? null,
        'date_to' => $_GET['date_to'] ?? null
    ];
    $limit = intval($_GET['limit'] ?? 50);
    $offset = intval($_GET['offset'] ?? 0);

    $publishing = new PublishingService();
    $result = $publishing->getHistory($filters, $limit, $offset);

    Response::json($result);
});

// Get publication statistics
$router->get('/api/publish/statistics', function() {
    if (!requireAuth()) return;

    $auth = new AuthService();
    $user = $GLOBALS['current_user'];

    if (!$auth->hasPermission($user['id'], 'program.publishing', 'read')) {
        Response::error('Permission denied', 403);
    }

    $dateFrom = $_GET['date_from'] ?? null;
    $dateTo = $_GET['date_to'] ?? null;

    $publishing = new PublishingService();
    $result = $publishing->getStatistics($dateFrom, $dateTo);

    Response::json($result);
});

// Delete published content
$router->delete('/api/publish/{id}', function($params) {
    if (!requireAuth()) return;

    $auth = new AuthService();
    $user = $GLOBALS['current_user'];

    if (!$auth->hasPermission($user['id'], 'program.publishing', 'delete')) {
        Response::error('Permission denied', 403);
    }

    $recordId = $params['id'];

    $publishing = new PublishingService();
    $result = $publishing->deletePublished($recordId);

    if ($result['success']) {
        $auth->logAudit('publish.delete', 'publish', $recordId);
    }

    Response::json($result);
});

// Test platform connections
$router->get('/api/publish/test-connections', function() {
    if (!requireAuth()) return;

    $auth = new AuthService();
    $user = $GLOBALS['current_user'];

    if (!$auth->hasPermission($user['id'], 'program.settings', 'read')) {
        Response::error('Permission denied', 403);
    }

    $publishing = new PublishingService();
    $result = $publishing->testConnections();

    Response::json($result);
});

// Facebook specific endpoints
$router->get('/api/facebook/post/{id}', function($params) {
    if (!requireAuth()) return;

    $auth = new AuthService();
    $user = $GLOBALS['current_user'];

    if (!$auth->hasPermission($user['id'], 'program.publishing', 'read')) {
        Response::error('Permission denied', 403);
    }

    $facebook = new FacebookService();
    $result = $facebook->getPost($params['id']);

    Response::json($result);
});

$router->get('/api/facebook/insights', function() {
    if (!requireAuth()) return;

    $auth = new AuthService();
    $user = $GLOBALS['current_user'];

    if (!$auth->hasPermission($user['id'], 'program.publishing', 'read')) {
        Response::error('Permission denied', 403);
    }

    $metrics = !empty($_GET['metrics']) ? explode(',', $_GET['metrics']) : [];
    $period = $_GET['period'] ?? 'day';

    $facebook = new FacebookService();
    $result = $facebook->getInsights($metrics, $period);

    Response::json($result);
});

// Extend Facebook Token to 60 days
$router->post('/api/facebook/extend-token', function() {
    if (!requireAuth()) return;

    $auth = new AuthService();
    $user = $GLOBALS['current_user'];

    // Allow users with publishing permission to extend token
    if (!$auth->hasPermission($user['id'], 'program.publishing', 'create')) {
        Response::error('Permission denied', 403);
    }

    // Get settings from database
    $db = Database::getInstance()->getConnection();
    $stmt = $db->prepare("SELECT `key`, value_encrypted FROM settings WHERE section = 'facebook'");
    $stmt->execute();
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $settings = [];
    foreach ($rows as $row) {
        $key = str_replace('FB_', '', $row['key']);
        $key = str_replace('META_', '', $key);
        $settings[$key] = $row['value_encrypted'];
    }

    // Validate required fields
    if (empty($settings['PAGE_ACCESS_TOKEN'])) {
        Response::error('Current Page Access Token not found');
    }
    if (empty($settings['APP_ID'])) {
        Response::error('Meta App ID not configured');
    }
    if (empty($settings['APP_SECRET'])) {
        Response::error('Meta App Secret not configured');
    }

    $currentToken = $settings['PAGE_ACCESS_TOKEN'];
    $appId = $settings['APP_ID'];
    $appSecret = $settings['APP_SECRET'];

    // Call Facebook API to exchange token
    $url = "https://graph.facebook.com/v23.0/oauth/access_token?" . http_build_query([
        'grant_type' => 'fb_exchange_token',
        'client_id' => $appId,
        'client_secret' => $appSecret,
        'fb_exchange_token' => $currentToken
    ]);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);

    if ($error) {
        Response::error('Failed to connect to Facebook API: ' . $error);
    }

    if ($httpCode !== 200) {
        $errorData = json_decode($response, true);
        $errorMsg = $errorData['error']['message'] ?? 'Facebook API error';
        Response::error($errorMsg);
    }

    $result = json_decode($response, true);

    if (empty($result['access_token'])) {
        Response::error('Failed to get new token from Facebook');
    }

    $newToken = $result['access_token'];
    $expiresIn = $result['expires_in'] ?? null;

    // Update token in database
    $stmt = $db->prepare("
        UPDATE settings
        SET value_encrypted = ?, updated_at = NOW()
        WHERE section = 'facebook' AND `key` = 'FB_PAGE_ACCESS_TOKEN'
    ");
    $stmt->execute([$newToken]);

    // Log the action
    $auth->logAudit('facebook.token_extended', 'settings', null, [
        'expires_in' => $expiresIn,
        'expires_in_days' => $expiresIn ? round($expiresIn / 86400) : null
    ]);

    Response::success([
        'new_token' => $newToken,
        'expires_in' => $expiresIn,
        'message' => 'Token extended successfully'
    ]);
});

// Instagram specific endpoints
$router->get('/api/instagram/media/{id}', function($params) {
    if (!requireAuth()) return;

    $auth = new AuthService();
    $user = $GLOBALS['current_user'];

    if (!$auth->hasPermission($user['id'], 'program.publishing', 'read')) {
        Response::error('Permission denied', 403);
    }

    $instagram = new InstagramService();
    $result = $instagram->getMedia($params['id']);

    Response::json($result);
});

$router->get('/api/instagram/insights', function() {
    if (!requireAuth()) return;

    $auth = new AuthService();
    $user = $GLOBALS['current_user'];

    if (!$auth->hasPermission($user['id'], 'program.publishing', 'read')) {
        Response::error('Permission denied', 403);
    }

    $metrics = !empty($_GET['metrics']) ? explode(',', $_GET['metrics']) : [];
    $period = $_GET['period'] ?? 'day';

    $instagram = new InstagramService();
    $result = $instagram->getInsights($metrics, $period);

    Response::json($result);
});

$router->get('/api/instagram/media/{id}/insights', function($params) {
    if (!requireAuth()) return;

    $auth = new AuthService();
    $user = $GLOBALS['current_user'];

    if (!$auth->hasPermission($user['id'], 'program.publishing', 'read')) {
        Response::error('Permission denied', 403);
    }

    $metrics = !empty($_GET['metrics']) ? explode(',', $_GET['metrics']) : [];

    $instagram = new InstagramService();
    $result = $instagram->getMediaInsights($params['id'], $metrics);

    Response::json($result);
});

// XiaoHongShu specific endpoints
$router->get('/api/xhs/note/{id}', function($params) {
    if (!requireAuth()) return;

    $auth = new AuthService();
    $user = $GLOBALS['current_user'];

    if (!$auth->hasPermission($user['id'], 'program.publishing', 'read')) {
        Response::error('Permission denied', 403);
    }

    $xhs = new XiaoHongShuService();
    $result = $xhs->getNote($params['id']);

    Response::json($result);
});

// ============================================
// AI Writer API (Requires Authentication)
// ============================================

$router->post('/api/ai-writer', function() {
    if (!requireAuth()) return;

    $auth = new AuthService();
    $user = $GLOBALS['current_user'];

    if (!$auth->hasPermission($user['id'], 'program.publishing', 'create')) {
        Response::error('Permission denied', 403);
    }

    $body = getRequestBody();
    $topic = $body['topic'] ?? '';

    if (empty($topic)) {
        Response::error('Topic is required');
    }

    // Get AI settings
    $db = Database::getInstance()->getConnection();
    $stmt = $db->prepare("SELECT `key`, value_encrypted FROM settings WHERE section = 'ai'");
    $stmt->execute();
    $settings = [];
    foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
        $key = strtoupper(str_replace('AI_', '', $row['key']));
        $settings[$key] = $row['value_encrypted'];
    }

    $serviceType = $settings['SERVICE_TYPE'] ?? 'external';

    // Generate content based on service type
    if ($serviceType === 'external') {
        $result = generateWithExternalPlatform($settings, $topic, $body);
    } else if ($serviceType === 'openai') {
        $result = generateWithOpenAI($settings, $topic, $body);
    } else if ($serviceType === 'ollama') {
        $result = generateWithOllama($settings, $topic, $body);
    } else {
        Response::error('Invalid AI service type: ' . $serviceType);
    }

    if (!$result['success']) {
        Response::error($result['message']);
    }

    // Log AI usage
    $auth->logAudit('ai.generate', 'content', null, [
        'topic' => $topic,
        'service' => $serviceType
    ]);

    // Return generated content
    Response::success($result['data']);
});

// Helper function: Generate with external AI platform
function generateWithExternalPlatform($settings, $topic, $body) {
    $baseUrl = $settings['BASE_URL'] ?? '';
    $apiKey = $settings['API_KEY'] ?? '';

    if (empty($baseUrl)) {
        return ['success' => false, 'message' => 'AI platform URL not configured'];
    }

    // Map parameters according to API documentation
    $language = $body['locale'] ?? $settings['DEFAULT_LOCALE'] ?? 'zh-TW';
    $length = $body['length'] ?? $settings['DEFAULT_LENGTH'] ?? 'short';

    // Map length values: short/medium/long
    $lengthMap = [
        'short' => 'short',
        'medium' => 'medium',
        'long' => 'long'
    ];
    $apiLength = $lengthMap[$length] ?? 'medium';

    // Build request according to API spec
    $requestData = [
        'topic' => $topic,
        'language' => $language,
        'style' => 'casual',  // 輕鬆對話風格，適合社群媒體
        'length' => $apiLength,
        'tone' => 'friendly',
        'audience' => 'general',
        'keywords' => []
    ];

    $ch = curl_init();
    // API endpoint: /api/public/ai-writer
    curl_setopt($ch, CURLOPT_URL, rtrim($baseUrl, '/') . '/api/public/ai-writer');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestData));

    // Use X-API-Key header as per documentation
    $headers = ['Content-Type: application/json'];
    if (!empty($apiKey)) {
        $headers[] = 'X-API-Key: ' . $apiKey;
    }
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_TIMEOUT, 60);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);

    if ($error) {
        return ['success' => false, 'message' => 'AI service connection error: ' . $error];
    }

    if ($httpCode !== 200) {
        $errorData = json_decode($response, true);
        $errorMsg = $errorData['error'] ?? $errorData['message'] ?? 'AI service returned error';
        return ['success' => false, 'message' => $errorMsg . ' (HTTP ' . $httpCode . ')'];
    }

    $result = json_decode($response, true);

    if (!$result || !isset($result['success'])) {
        return ['success' => false, 'message' => 'Invalid response from AI service'];
    }

    if (!$result['success']) {
        $errorMsg = $result['error'] ?? $result['message'] ?? 'AI generation failed';
        return ['success' => false, 'message' => $errorMsg];
    }

    // Map response fields according to API response format
    $data = $result['data'] ?? [];

    // Extract content (strip HTML tags for social media)
    $content = $data['content'] ?? '';
    $plainContent = strip_tags($content);

    // Extract hashtags from keywords_used
    $hashtags = [];
    if (isset($data['keywords_used']) && is_array($data['keywords_used'])) {
        $hashtags = array_map(function($keyword) {
            return '#' . str_replace(' ', '', $keyword);
        }, $data['keywords_used']);
    }

    return [
        'success' => true,
        'data' => [
            'title' => $data['title'] ?? '',
            'content' => $plainContent ?: $content,
            'hashtags' => $hashtags
        ]
    ];
}

// Helper function: Generate with OpenAI
function generateWithOpenAI($settings, $topic, $body) {
    $apiKey = $settings['OPENAI_API_KEY'] ?? '';
    $model = $settings['OPENAI_MODEL'] ?? 'gpt-4o-mini';

    if (empty($apiKey)) {
        return ['success' => false, 'message' => 'OpenAI API key not configured'];
    }

    $locale = $body['locale'] ?? $settings['DEFAULT_LOCALE'] ?? 'zh-TW';
    $length = $body['length'] ?? $settings['DEFAULT_LENGTH'] ?? 'short';

    $lengthMap = [
        'short' => '200-300字',
        'medium' => '400-600字',
        'long' => '800-1000字'
    ];
    $lengthDesc = $lengthMap[$length] ?? '200-300字';

    $prompt = "請以「{$topic}」為主題，用{$locale}語言撰寫一篇社群媒體貼文。\n\n要求：\n1. 長度：{$lengthDesc}\n2. 風格：輕鬆有趣，適合社群媒體\n3. 包含適當的表情符號\n4. 提供3-5個相關的hashtag標籤\n5. 提供一個吸引人的標題\n\n請以JSON格式回應：\n{\n  \"title\": \"標題\",\n  \"content\": \"貼文內容\",\n  \"hashtags\": [\"標籤1\", \"標籤2\"]\n}";

    $requestData = [
        'model' => $model,
        'messages' => [
            ['role' => 'system', 'content' => '你是一個專業的社群媒體內容創作者。請始終以 JSON 格式回應。'],
            ['role' => 'user', 'content' => $prompt]
        ],
        'temperature' => 0.7,
        'response_format' => ['type' => 'json_object']
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://api.openai.com/v1/chat/completions');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestData));
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $apiKey
    ]);
    curl_setopt($ch, CURLOPT_TIMEOUT, 60);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);

    if ($error) {
        return ['success' => false, 'message' => 'OpenAI connection error: ' . $error];
    }

    if ($httpCode !== 200) {
        $errorData = json_decode($response, true);
        $errorMsg = $errorData['error']['message'] ?? 'OpenAI API error';
        return ['success' => false, 'message' => $errorMsg];
    }

    $result = json_decode($response, true);
    $content = $result['choices'][0]['message']['content'] ?? '';

    if (empty($content)) {
        return ['success' => false, 'message' => 'Empty response from OpenAI'];
    }

    $generated = json_decode($content, true);

    // Ensure hashtags is an array
    $hashtags = [];
    if (isset($generated['hashtags'])) {
        if (is_array($generated['hashtags'])) {
            $hashtags = $generated['hashtags'];
        } else if (is_string($generated['hashtags'])) {
            // If it's a string, split by comma or space
            $hashtags = preg_split('/[,\s]+/', trim($generated['hashtags']));
        }
    }

    return [
        'success' => true,
        'data' => [
            'title' => $generated['title'] ?? '',
            'content' => $generated['content'] ?? $content,
            'hashtags' => array_filter($hashtags) // Remove empty values
        ]
    ];
}

// Helper function: Generate with Ollama
function generateWithOllama($settings, $topic, $body) {
    $baseUrl = $settings['OLLAMA_BASE_URL'] ?? 'http://10.66.88.208:11434';
    $model = $settings['OLLAMA_MODEL'] ?? 'llama3.2:latest';

    $locale = $body['locale'] ?? $settings['DEFAULT_LOCALE'] ?? 'zh-TW';
    $length = $body['length'] ?? $settings['DEFAULT_LENGTH'] ?? 'short';

    $lengthMap = [
        'short' => '200-300字',
        'medium' => '400-600字',
        'long' => '800-1000字'
    ];
    $lengthDesc = $lengthMap[$length] ?? '200-300字';

    $prompt = "請以「{$topic}」為主題，用{$locale}語言撰寫一篇社群媒體貼文。\n\n要求：\n1. 長度：{$lengthDesc}\n2. 風格：輕鬆有趣，適合社群媒體\n3. 包含適當的表情符號\n4. 提供3-5個相關的hashtag標籤\n5. 提供一個吸引人的標題\n\n請以JSON格式回應：\n{\n  \"title\": \"標題\",\n  \"content\": \"貼文內容\",\n  \"hashtags\": [\"標籤1\", \"標籤2\"]\n}";

    $requestData = [
        'model' => $model,
        'prompt' => $prompt,
        'stream' => false,
        'format' => 'json'
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, rtrim($baseUrl, '/') . '/api/generate');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestData));
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    curl_setopt($ch, CURLOPT_TIMEOUT, 120);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);

    if ($error) {
        return ['success' => false, 'message' => 'Ollama connection error: ' . $error];
    }

    if ($httpCode !== 200) {
        return ['success' => false, 'message' => 'Ollama API error (HTTP ' . $httpCode . ')'];
    }

    $result = json_decode($response, true);
    $content = $result['response'] ?? '';

    if (empty($content)) {
        return ['success' => false, 'message' => 'Empty response from Ollama'];
    }

    $generated = json_decode($content, true);

    // Ensure hashtags is an array
    $hashtags = [];
    if (isset($generated['hashtags'])) {
        if (is_array($generated['hashtags'])) {
            $hashtags = $generated['hashtags'];
        } else if (is_string($generated['hashtags'])) {
            $hashtags = preg_split('/[,\s]+/', trim($generated['hashtags']));
        }
    }

    return [
        'success' => true,
        'data' => [
            'title' => $generated['title'] ?? '',
            'content' => $generated['content'] ?? $content,
            'hashtags' => array_filter($hashtags)
        ]
    ];
}

// ============================================
// Run Router
// ============================================

$router->run();
