<?php
/*******************************************************************************************************************
| Software Name        : EasyStream
| Software Description : High End YouTube Clone Script with Videos, Shorts, Streams, Images, Audio, Documents, Blogs
| Software Author      : (c) Sami Ahmed
|*******************************************************************************************************************
|
|*******************************************************************************************************************
| This source file is subject to the EasyStream Proprietary License Agreement.
|
| By using this software, you acknowledge having read this Agreement and agree to be bound thereby.
|*******************************************************************************************************************
| Copyright (c) 2025 Sami Ahmed. All rights reserved.
|*******************************************************************************************************************/

/**
 * Creator Studio / Analytics Dashboard
 *
 * YouTube Studio-style creator dashboard with:
 * - Content management
 * - Analytics and insights
 * - Revenue reports
 * - Subscriber statistics
 * - Performance metrics
 *
 * URL: /studio.php or /studio
 */

define('_ISVALID', true);

include_once 'f_core/config.core.php';

// Check if user is logged in
if (!isset($_SESSION['USER_ID']) || $_SESSION['USER_ID'] == 0) {
    header('Location: ' . $cfg['main_url'] . '/login.php?redirect=' . urlencode('/studio.php'));
    exit;
}

include_once $class_language->setLanguageFile('frontend', 'language.global');
include_once $class_language->setLanguageFile('frontend', 'language.files');

$usr_id = (int) $_SESSION['USER_ID'];
$error_message = null;
$notice_message = null;

// Get configuration
$cfg = $class_database->getConfigurations('video_module,short_module,live_module,image_module,audio_module,document_module,blog_module,user_subscriptions,affiliate_module,paid_memberships');

// Get current view/section
$section = isset($_GET['section']) ? VSecurity::getParam('section', 'string') : 'dashboard';

// Valid sections
$valid_sections = ['dashboard', 'content', 'analytics', 'comments', 'subscribers', 'earnings', 'settings'];
if (!in_array($section, $valid_sections)) {
    $section = 'dashboard';
}

// Get date range for analytics
$date_range = isset($_GET['range']) ? VSecurity::getParam('range', 'string') : '28days';
$valid_ranges = ['7days', '28days', '90days', '365days', 'all'];
if (!in_array($date_range, $valid_ranges)) {
    $date_range = '28days';
}

// Calculate date range
$range_days = [
    '7days' => 7,
    '28days' => 28,
    '90days' => 90,
    '365days' => 365,
    'all' => 365 * 10 // 10 years
];

$days = $range_days[$date_range];
$start_date = date('Y-m-d', strtotime("-$days days"));
$end_date = date('Y-m-d');

// Get creator statistics
$stats = getCreatorStats($usr_id, $start_date, $end_date);

// Get content counts
$content_counts = getContentCounts($usr_id);

// Get recent uploads
$recent_uploads = getRecentUploads($usr_id, 10);

// Get top performing content
$top_content = getTopContent($usr_id, $start_date, $end_date, 10);

// Get subscriber growth
$subscriber_growth = getSubscriberGrowth($usr_id, $start_date, $end_date);

// Get revenue data (if applicable)
$revenue_data = null;
if ($cfg['affiliate_module'] == 1 || $cfg['paid_memberships'] == 1) {
    $revenue_data = getRevenueData($usr_id, $start_date, $end_date);
}

// Assign to Smarty
$smarty->assign('section', $section);
$smarty->assign('date_range', $date_range);
$smarty->assign('stats', $stats);
$smarty->assign('content_counts', $content_counts);
$smarty->assign('recent_uploads', $recent_uploads);
$smarty->assign('top_content', $top_content);
$smarty->assign('subscriber_growth', $subscriber_growth);
$smarty->assign('revenue_data', $revenue_data);
$smarty->assign('start_date', $start_date);
$smarty->assign('end_date', $end_date);

// Display the studio page
echo $class_smarty->displayPage('frontend', 'tpl_studio', $error_message, $notice_message);

/**
 * Get creator statistics
 */
function getCreatorStats($usr_id, $start_date, $end_date)
{
    global $class_database;

    // Total views
    $sql = "SELECT SUM(file_views) as total_views
            FROM (
                SELECT file_views FROM db_videofiles WHERE usr_id = %d AND upload_date >= '%s' AND upload_date <= '%s'
                UNION ALL
                SELECT file_views FROM db_shortfiles WHERE usr_id = %d AND upload_date >= '%s' AND upload_date <= '%s'
                UNION ALL
                SELECT file_views FROM db_livefiles WHERE usr_id = %d AND upload_date >= '%s' AND upload_date <= '%s'
            ) as combined";

    $result = $class_database->doQuery($sql,
        $usr_id, $start_date, $end_date,
        $usr_id, $start_date, $end_date,
        $usr_id, $start_date, $end_date
    );
    $row = $result->fetch_assoc();
    $total_views = (int) $row['total_views'];

    // Subscriber count
    $sql = "SELECT COUNT(*) as subscribers FROM db_subscribers WHERE subscriber_id = %d";
    $result = $class_database->doQuery($sql, $usr_id);
    $row = $result->fetch_assoc();
    $subscribers = (int) $row['subscribers'];

    // Total likes
    $sql = "SELECT SUM(file_like) as total_likes
            FROM (
                SELECT file_like FROM db_videofiles WHERE usr_id = %d
                UNION ALL
                SELECT file_like FROM db_shortfiles WHERE usr_id = %d
                UNION ALL
                SELECT file_like FROM db_livefiles WHERE usr_id = %d
            ) as combined";

    $result = $class_database->doQuery($sql, $usr_id, $usr_id, $usr_id);
    $row = $result->fetch_assoc();
    $total_likes = (int) $row['total_likes'];

    // Total comments
    $sql = "SELECT COUNT(*) as total_comments FROM db_comments WHERE file_usr_id = %d";
    $result = $class_database->doQuery($sql, $usr_id);
    $row = $result->fetch_assoc();
    $total_comments = (int) $row['total_comments'];

    return [
        'total_views' => $total_views,
        'subscribers' => $subscribers,
        'total_likes' => $total_likes,
        'total_comments' => $total_comments
    ];
}

/**
 * Get content counts by type
 */
function getContentCounts($usr_id)
{
    global $class_database;

    $counts = [];

    $types = [
        'video' => 'db_videofiles',
        'short' => 'db_shortfiles',
        'live' => 'db_livefiles',
        'image' => 'db_imagefiles',
        'audio' => 'db_audiofiles',
        'document' => 'db_documentfiles',
        'blog' => 'db_blogfiles'
    ];

    foreach ($types as $type => $table) {
        $sql = "SELECT COUNT(*) as count FROM `{$table}` WHERE usr_id = %d AND active = 1 AND deleted = 0";
        $result = $class_database->doQuery($sql, $usr_id);
        $row = $result->fetch_assoc();
        $counts[$type] = (int) $row['count'];
    }

    return $counts;
}

/**
 * Get recent uploads
 */
function getRecentUploads($usr_id, $limit = 10)
{
    global $class_database;

    $sql = "SELECT 'video' as type, file_key, file_title, file_views, file_like, file_comments, upload_date, privacy, approved
            FROM db_videofiles
            WHERE usr_id = %d AND deleted = 0
            UNION ALL
            SELECT 'short' as type, file_key, file_title, file_views, file_like, file_comments, upload_date, privacy, approved
            FROM db_shortfiles
            WHERE usr_id = %d AND deleted = 0
            ORDER BY upload_date DESC
            LIMIT %d";

    $result = $class_database->doQuery($sql, $usr_id, $usr_id, $limit);

    $uploads = [];
    while ($row = $result->fetch_assoc()) {
        $uploads[] = $row;
    }

    return $uploads;
}

/**
 * Get top performing content
 */
function getTopContent($usr_id, $start_date, $end_date, $limit = 10)
{
    global $class_database;

    $sql = "SELECT 'video' as type, file_key, file_title, file_views, file_like, file_comments, upload_date
            FROM db_videofiles
            WHERE usr_id = %d AND upload_date >= '%s' AND upload_date <= '%s' AND deleted = 0
            UNION ALL
            SELECT 'short' as type, file_key, file_title, file_views, file_like, file_comments, upload_date
            FROM db_shortfiles
            WHERE usr_id = %d AND upload_date >= '%s' AND upload_date <= '%s' AND deleted = 0
            ORDER BY file_views DESC
            LIMIT %d";

    $result = $class_database->doQuery($sql,
        $usr_id, $start_date, $end_date,
        $usr_id, $start_date, $end_date,
        $limit
    );

    $content = [];
    while ($row = $result->fetch_assoc()) {
        $content[] = $row;
    }

    return $content;
}

/**
 * Get subscriber growth
 */
function getSubscriberGrowth($usr_id, $start_date, $end_date)
{
    global $class_database;

    $sql = "SELECT DATE(sub_date) as date, COUNT(*) as count
            FROM db_subscribers
            WHERE subscriber_id = %d AND sub_date >= '%s' AND sub_date <= '%s'
            GROUP BY DATE(sub_date)
            ORDER BY date ASC";

    $result = $class_database->doQuery($sql, $usr_id, $start_date, $end_date);

    $growth = [];
    while ($row = $result->fetch_assoc()) {
        $growth[] = [
            'date' => $row['date'],
            'count' => (int) $row['count']
        ];
    }

    return $growth;
}

/**
 * Get revenue data
 */
function getRevenueData($usr_id, $start_date, $end_date)
{
    global $class_database;

    // This is a simplified version - adjust based on your payment structure
    $sql = "SELECT
                SUM(amount) as total_revenue,
                COUNT(*) as transaction_count
            FROM db_payments
            WHERE usr_id = %d AND payment_date >= '%s' AND payment_date <= '%s' AND status = 'completed'";

    $result = $class_database->doQuery($sql, $usr_id, $start_date, $end_date);
    $row = $result->fetch_assoc();

    return [
        'total_revenue' => (float) ($row['total_revenue'] ?? 0),
        'transaction_count' => (int) ($row['transaction_count'] ?? 0)
    ];
}
?>
