<?php
/**
 * RSS Dashboard API
 * Backend API to handle AJAX requests from dashboard
 */

require_once '../inc/con.php';

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

$action = $_GET['action'] ?? '';

try {
    switch ($action) {
        case 'get_source_stats':
            $logId = $_GET['log_id'] ?? 0;
            if (!$logId) {
                throw new Exception('Log ID is required');
            }

            $stmt = $db->prepare("
                SELECT rsl.*, cs.name as source_name, cs.json_feed
                FROM rss_source_logs rsl
                LEFT JOIN cat_sources cs ON rsl.source_id = cs.id
                WHERE rsl.log_id = ?
                ORDER BY rsl.id DESC
            ");
            $stmt->execute([$logId]);
            $results = $stmt->fetchAll();

            echo json_encode($results);
            break;

        case 'get_stats':
            $stats = [];

            // Total posts
            $stmt = $db->query("SELECT COUNT(*) as total FROM social_media_content");
            $stats['total_posts'] = $stmt->fetch()['total'];

            // Last run
            $stmt = $db->query("SELECT * FROM rss_logs ORDER BY run_date DESC LIMIT 1");
            $stats['last_run'] = $stmt->fetch();

            // Content breakdown
            $stmt = $db->query("
                SELECT content_type, COUNT(*) as count 
                FROM social_media_content 
                GROUP BY content_type
            ");
            $stats['content_breakdown'] = $stmt->fetchAll();

            // Today's posts
            $stmt = $db->query("
                SELECT COUNT(*) as count 
                FROM social_media_content 
                WHERE DATE(create_date) = CURDATE()
            ");
            $stats['today_posts'] = $stmt->fetch()['count'];

            echo json_encode($stats);
            break;

        case 'get_recent_runs':
            $limit = $_GET['limit'] ?? 10;
            $stmt = $db->prepare("
                SELECT * FROM rss_logs 
                ORDER BY run_date DESC 
                LIMIT ?
            ");
            $stmt->execute([$limit]);
            $results = $stmt->fetchAll();

            echo json_encode($results);
            break;

        case 'get_video_stats':
            $stats = [];

            // Total videos
            $stmt = $db->query("
                SELECT COUNT(*) as count 
                FROM social_media_content 
                WHERE content_type IN (2, 21)
            ");
            $stats['total_videos'] = $stmt->fetch()['count'];

            // YouTube videos
            $stmt = $db->query("
                SELECT COUNT(*) as count 
                FROM social_media_content 
                WHERE content_type = 2
            ");
            $stats['youtube_videos'] = $stmt->fetch()['count'];

            // Twitter videos
            $stmt = $db->query("
                SELECT COUNT(*) as count 
                FROM social_media_content 
                WHERE content_type = 21
            ");
            $stats['twitter_videos'] = $stmt->fetch()['count'];

            // Videos without photo
            $stmt = $db->query("
                SELECT COUNT(*) as count 
                FROM social_media_content 
                WHERE content_type IN (2, 21) AND (photo IS NULL OR photo = '')
            ");
            $stats['videos_without_photo'] = $stmt->fetch()['count'];

            echo json_encode($stats);
            break;

        case 'get_error_logs':
            $limit = $_GET['limit'] ?? 50;
            $logFile = __DIR__ . '/rss_errors.log';

            if (!file_exists($logFile)) {
                echo json_encode([]);
                break;
            }

            $lines = file($logFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
            $lines = array_reverse($lines);
            $lines = array_slice($lines, 0, $limit);

            echo json_encode($lines);
            break;

        case 'get_content_breakdown':
            $stmt = $db->query("
                SELECT content_type, COUNT(*) as count 
                FROM social_media_content 
                GROUP BY content_type
                ORDER BY count DESC
            ");
            $results = $stmt->fetchAll();

            echo json_encode($results);
            break;

        case 'get_videos_by_status':
            $status = $_GET['status'] ?? 0;
            $limit = $_GET['limit'] ?? 50;

            $stmt = $db->prepare("
                SELECT id, post_id, content_type, video_url, photo, create_date, video_processing
                FROM social_media_content 
                WHERE video_url IS NOT NULL 
                AND video_url != '' 
                AND video_processing = ?
                ORDER BY create_date DESC
                LIMIT ?
            ");
            $stmt->bindValue(1, (int) $status, PDO::PARAM_INT);
            $stmt->bindValue(2, (int) $limit, PDO::PARAM_INT);
            $stmt->execute();
            $results = $stmt->fetchAll();

            echo json_encode($results);
            break;

        case 'trigger_video_processing':
            // Trigger video processing script
            $phpPath = '/usr/bin/php'; // Default PHP path
            $scriptPath = __DIR__ . '/process_videos.php';

            // Check if script exists
            if (!file_exists($scriptPath)) {
                throw new Exception('Video processing script not found');
            }

            // Execute in background
            $command = "$phpPath $scriptPath > /dev/null 2>&1 &";
            exec($command, $output, $returnVar);

            echo json_encode([
                'success' => true,
                'message' => 'Video processing started in background'
            ]);
            break;

        default:
            throw new Exception('Invalid action');
    }

} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'error' => true,
        'message' => $e->getMessage()
    ]);
}
