<?php
// backend/APIEndpoint/index.php

require_once __DIR__ . '/config.php';



require_once __DIR__ . '/../inc/con.php'; // Path to backend/inc/con.php

// 1. Security Check
validateApiRequest();

// 2. Routing
$action = $_GET['action'] ?? '';

try {
    switch ($action) {
        case 'get_sources':
            getSources($db);
            break;

        case 'get_content':
            getContent($db);
            break;

        case 'get_config':
            getConfig();
            break;

        default:
            throw new Exception('Invalid Action');
    }
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode(['error' => $e->getMessage()]);
}

/**
 * Endpoint: Get Active Sources
 */
function getSources($db)
{
    try {
        $stmt = $db->prepare("
            SELECT id, name, json_feed, link_url, last_fetch_time 
            FROM cat_sources 
            WHERE status = 1 
            ORDER BY id ASC
        ");
        $stmt->execute();
        $sources = $stmt->fetchAll(PDO::FETCH_ASSOC);

        echo json_encode([
            'success' => true,
            'count' => count($sources),
            'data' => $sources
        ]);
    } catch (PDOException $e) {
        throw new Exception('Database Error: ' . $e->getMessage());
    }
}


/**
 * Endpoint: Get Configuration
 */
function getConfig()
{
    echo json_encode([
        'success' => true,
        'data' => [
            'pagination_mode' => PAGINATION_MODE,
            // Add other frontend configs here if needed
        ]
    ]);
}

/**
 * Endpoint: Get Content
 * Supports: Pagination (Page/LastID), Filtering (Source, Type, Cat)
 */
function getContent($db)
{
    // Parameters
    $limit = isset($_GET['limit']) ? min((int) $_GET['limit'], 50) : 20; // Max 50 per request
    $page = isset($_GET['page']) ? (int) $_GET['page'] : 1;

    // Filters
    $sourceId = isset($_GET['source_id']) ? (int) $_GET['source_id'] : null;
    $contentType = isset($_GET['content_type']) ? $_GET['content_type'] : null; // Changed to mixed (string or int)
    $catId = isset($_GET['cat_id']) ? (int) $_GET['cat_id'] : null;

    // Cursor Pagination (Load More)
    $lastId = isset($_GET['last_id']) ? (int) $_GET['last_id'] : null;

    // Build Query
    $where = ["smc.status = 1"]; // Only active content
    $params = [];

    if ($sourceId) {
        $where[] = "smc.cat_sources = ?";
        $params[] = $sourceId;
    }

    if ($contentType) {
        if ($contentType === 'video') {
            // Group all video types
            $where[] = "smc.content_type IN (2, 10, 21)";
        } else {
            // Specific ID
            $where[] = "smc.content_type = ?";
            $params[] = (int) $contentType;
        }
    }

    if ($catId) {
        $where[] = "smc.cat_id = ?";
        $params[] = $catId;
    }

    // Pagination Logic
    if ($lastId) {
        // Cursor based (efficient for scrolling)
        $where[] = "smc.id < ?";
        $params[] = $lastId;
    } else {
        // Offset based (standard pagination)
        // Only use offset if last_id is NOT provided
        $offset = ($page - 1) * $limit;
    }

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

    $sql = "
        SELECT 
            smc.id, smc.post_id, smc.title, smc.content_text, smc.content_html, 
            smc.photo, smc.video_url, smc.content_type, smc.cat_sources as source_id,
            smc.create_date, smc.publish_date, smc.video_processing,
            cs.name as source_name, cs.link_url as source_url
        FROM social_media_content smc
        LEFT JOIN cat_sources cs ON smc.cat_sources = cs.id
        WHERE $whereSql
        ORDER BY smc.id DESC
        LIMIT $limit
    ";

    // Add OFFSET only if not using Cursor pagination
    if (!$lastId) {
        $sql .= " OFFSET $offset";
    }

    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    $items = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Type Map
    $contentTypeNames = [
        1 => 'صورة',
        2 => 'يوتيوب',
        3 => 'عاجل/خاص',
        6 => 'صور متعددة',
        10 => 'فيديو عام',
        15 => 'نص فقط',
        21 => 'فيديو تويتر'
    ];

    // Format Data (URLs, Videos, etc.)
    $formattedItems = array_map(function ($item) use ($contentTypeNames) {
        // Human Readable Type
        $item['type_label'] = $contentTypeNames[$item['content_type']] ?? 'غير معروف';

        // 1. Format Photo URL
        if (!empty($item['photo'])) {
            // Check if already absolute
            if (!preg_match('/^http/', $item['photo'])) {
                $item['photo_url'] = IMAGE_BASE_URL . $item['photo'];
            } else {
                $item['photo_url'] = $item['photo'];
            }
        } else {
            $item['photo_url'] = null;
        }

        // 2. Format Video URL
        $item['video_data'] = null;
        if (in_array($item['content_type'], [2, 10, 21]) && !empty($item['video_url'])) {
            $videoData = [
                'original_url' => $item['video_url'],
                'processed' => false,
                'hls_url' => null,
                'poster' => $item['photo_url']
            ];

            if ($item['video_processing'] == 2) {
                // Use VIDEO_BASE_URL constant
                $videoData['processed'] = true;
                $videoData['hls_url'] = VIDEO_BASE_URL . $item['id'] . '/master.m3u8';
            } else {
                $videoData['status_message'] = 'Video processing pending or failed';
            }

            $item['video_data'] = $videoData;
        }

        return $item;
    }, $items);

    echo json_encode([
        'success' => true,
        'count' => count($formattedItems),
        'page' => $page,
        'limit' => $limit,
        'data' => $formattedItems
    ]);
}
