<?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'] ?? 'all'; // Accept string status
            $limit = $_GET['limit'] ?? 20;
            $page = $_GET['page'] ?? 1;
            $offset = ($page - 1) * $limit;

            $where = ["smc.video_url IS NOT NULL", "smc.video_url != ''"];
            $params = [];

            // Status Logic
            if ($status === 'youtube') {
                $where[] = "smc.content_type = 2";
            } else {
                // For all other tabs, EXCLUDE YouTube
                $where[] = "smc.content_type != 2";

                if ($status === 'pending') {
                    $where[] = "(smc.video_processing = 0 OR smc.video_processing IS NULL)";
                } elseif ($status === 'processing') {
                    $where[] = "smc.video_processing = 1";
                } elseif ($status === 'completed') {
                    $where[] = "smc.video_processing = 2";
                } elseif ($status === 'failed') {
                    $where[] = "smc.video_processing = 3";
                }
                // 'all' case adds no extra filters beyond excluding YouTube
            }

            $whereSql = implode(" AND ", $where);

            $stmt = $db->prepare("
                SELECT smc.id, smc.post_id, smc.content_type, smc.video_url, smc.photo, smc.create_date, smc.video_processing, smc.title, cs.name as source_name
                FROM social_media_content smc
                LEFT JOIN cat_sources cs ON smc.cat_sources = cs.id
                WHERE $whereSql
                ORDER BY smc.create_date DESC
                LIMIT ? OFFSET ?
            ");

            $stmt->bindValue(1, (int) $limit, PDO::PARAM_INT);
            $stmt->bindValue(2, (int) $offset, PDO::PARAM_INT);
            $stmt->execute();
            $results = $stmt->fetchAll();

            echo json_encode($results);
            break;

        case 'get_day_details':
            $date = $_GET['date'] ?? '';
            if (!$date) {
                throw new Exception('Date is required');
            }

            $data = [];

            // Get content breakdown for the day
            $stmt = $db->prepare("
                SELECT smc.content_type, COUNT(*) as count
                FROM social_media_content smc
                WHERE DATE(smc.create_date) = ?
                GROUP BY smc.content_type
            ");
            $stmt->execute([$date]);
            $contentBreakdown = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
            $data['content_breakdown'] = $contentBreakdown;

            // Get video processing stats for the day
            $stmt = $db->prepare("
                SELECT COUNT(*) as count
                FROM social_media_content
                WHERE DATE(create_date) = ?
                AND video_url IS NOT NULL
                AND video_url != ''
                AND (video_processing = 0 OR video_processing IS NULL)
            ");
            $stmt->execute([$date]);
            $data['videos_pending'] = $stmt->fetch()['count'];

            $stmt = $db->prepare("
                SELECT COUNT(*) as count
                FROM social_media_content
                WHERE DATE(create_date) = ?
                AND video_url IS NOT NULL
                AND video_url != ''
                AND video_processing = 2
            ");
            $stmt->execute([$date]);
            $data['videos_completed'] = $stmt->fetch()['count'];

            echo json_encode([
                'success' => true,
                'data' => $data
            ]);
            break;

        case 'get_run_content':
            $runId = $_GET['run_id'] ?? 0;
            if (!$runId) {
                throw new Exception('Run ID is required');
            }

            // Get run date
            $stmt = $db->prepare("SELECT run_date FROM rss_logs WHERE id = ?");
            $stmt->execute([$runId]);
            $run = $stmt->fetch();

            if (!$run) {
                throw new Exception('Run not found');
            }

            $runDate = date('Y-m-d', strtotime($run['run_date']));
            $data = [];

            // Get content breakdown for the run
            $stmt = $db->prepare("
                SELECT 
                    content_type,
                    COUNT(*) as count,
                    SUM(CASE WHEN file_size IS NOT NULL THEN file_size ELSE 0 END) as total_size
                FROM social_media_content
                WHERE DATE(create_date) = ?
                GROUP BY content_type
            ");
            $stmt->execute([$runDate]);
            $contentBreakdown = [];
            while ($row = $stmt->fetch()) {
                $contentBreakdown[$row['content_type']] = [
                    'count' => $row['count'],
                    'total_size' => $row['total_size']
                ];
            }
            $data['content_breakdown'] = $contentBreakdown;

            // Get total counts
            $stmt = $db->prepare("
                SELECT COUNT(*) as total_items,
                       SUM(CASE WHEN file_size IS NOT NULL THEN file_size ELSE 0 END) as total_size
                FROM social_media_content
                WHERE DATE(create_date) = ?
            ");
            $stmt->execute([$runDate]);
            $totals = $stmt->fetch();
            $data['total_items'] = $totals['total_items'];
            $data['total_size'] = $totals['total_size'];

            echo json_encode([
                'success' => true,
                'data' => $data
            ]);
            break;

        case 'save_source':
            $sourceId = $_POST['source_id'] ?? 0;
            $name = $_POST['name'] ?? '';
            $jsonFeed = $_POST['json_feed'] ?? '';
            $linkUrl = $_POST['link_url'] ?? '';

            if (empty($name) || empty($jsonFeed)) {
                throw new Exception('Name and Feed URL are required');
            }

            if ($sourceId > 0) {
                // Update
                $stmt = $db->prepare("UPDATE cat_sources SET name = ?, json_feed = ?, link_url = ? WHERE id = ?");
                $success = $stmt->execute([$name, $jsonFeed, $linkUrl, $sourceId]);
            } else {
                // Insert
                $stmt = $db->prepare("INSERT INTO cat_sources (name, json_feed, link_url, status, create_date) VALUES (?, ?, ?, 1, NOW())");
                $success = $stmt->execute([$name, $jsonFeed, $linkUrl]);
            }

            echo json_encode(['success' => $success]);
            break;

        case 'get_source_details':
            $sourceId = $_GET['source_id'] ?? 0;
            if (!$sourceId) {
                throw new Exception('Source ID is required');
            }

            $stmt = $db->prepare("SELECT id, name, json_feed, link_url FROM cat_sources WHERE id = ?");
            $stmt->execute([$sourceId]);
            $source = $stmt->fetch();

            if (!$source) {
                throw new Exception('Source not found');
            }

            echo json_encode(['success' => true, 'data' => $source]);
            break;

        case 'toggle_source_status':
            $sourceId = $_POST['source_id'] ?? 0;
            $status = $_POST['status'] ?? 0; // 0=inactive, 1=active

            if (!$sourceId) {
                throw new Exception('Source ID is required');
            }

            $stmt = $db->prepare("UPDATE cat_sources SET status = ? WHERE id = ?");
            $success = $stmt->execute([$status, $sourceId]);

            echo json_encode(['success' => $success]);
            break;

        case 'toggle_content_status':
            $postId = $_POST['post_id'] ?? 0;
            $status = $_POST['status'] ?? 0; // 0=Hidden, 1=Published

            if (!$postId) {
                throw new Exception('Post ID is required');
            }

            $stmt = $db->prepare("UPDATE social_media_content SET status = ? WHERE id = ?");
            $success = $stmt->execute([$status, $postId]);

            echo json_encode(['success' => $success]);
            break;



        case 'get_all_content':
            $page = isset($_GET['page']) ? (int) $_GET['page'] : 1;
            $limit = isset($_GET['limit']) ? (int) $_GET['limit'] : 20;
            $offset = ($page - 1) * $limit;
            $type = isset($_GET['type']) && $_GET['type'] !== 'all' ? (int) $_GET['type'] : null;
            $search = isset($_GET['search']) ? trim($_GET['search']) : '';

            // Build query conditions
            $where = ["1=1"];
            $params = [];

            if ($type !== null) {
                $where[] = "smc.content_type = ?";
                $params[] = $type;
            }

            if (!empty($search)) {
                $where[] = "(smc.title LIKE ? OR cs.name LIKE ?)";
                $params[] = "%$search%";
                $params[] = "%$search%";
            }

            $whereSql = implode(" AND ", $where);

            // Get total count
            $countStmt = $db->prepare("
                SELECT COUNT(*) 
                FROM social_media_content smc
                LEFT JOIN cat_sources cs ON smc.cat_sources = cs.id
                WHERE $whereSql
            ");
            $countStmt->execute($params);
            $total = $countStmt->fetchColumn();

            // Get data
            $stmt = $db->prepare("
                SELECT smc.*, cs.name as source_name
                FROM social_media_content smc
                LEFT JOIN cat_sources cs ON smc.cat_sources = cs.id
                WHERE $whereSql
                ORDER BY smc.create_date DESC
                LIMIT $limit OFFSET $offset
            ");
            $stmt->execute($params);
            $data = $stmt->fetchAll(PDO::FETCH_ASSOC);

            echo json_encode([
                'success' => true,
                'data' => $data,
                'total' => $total,
                'page' => $page,
                'pages' => ceil($total / $limit)
            ]);
            break;

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

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

            // 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;

        case 'reset_video_status':
            $id = $_GET['id'] ?? 0;
            if (!$id) {
                throw new Exception('Video ID is required');
            }

            $stmt = $db->prepare("UPDATE social_media_content SET video_processing = 0, processing_percentage = 0 WHERE id = ?");
            $success = $stmt->execute([$id]);

            echo json_encode(['success' => $success]);
            break;

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

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