<?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.
|*******************************************************************************************************************/

/**
 * Upload Progress API
 *
 * Provides real-time upload progress information
 * Tracks: Upload percentage, processing status, encoding status, completion
 */

define('_ISVALID', true);

$main_dir = realpath(dirname(__FILE__) . '/../../');
set_include_path($main_dir);

include_once 'f_core/config.core.php';

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');

$usr_id = isset($_SESSION['USER_ID']) ? (int) $_SESSION['USER_ID'] : 0;

if ($usr_id == 0) {
    echo json_encode(['error' => 'Not authenticated']);
    exit;
}

$action = isset($_GET['action']) ? $_GET['action'] : 'get_status';
$upload_id = isset($_GET['upload_id']) ? $_GET['upload_id'] : '';

switch ($action) {
    case 'get_status':
        echo json_encode(getUploadStatus($upload_id, $usr_id));
        break;

    case 'get_all':
        echo json_encode(getAllUploads($usr_id));
        break;

    case 'cancel':
        echo json_encode(cancelUpload($upload_id, $usr_id));
        break;

    default:
        echo json_encode(['error' => 'Invalid action']);
}

/**
 * Get upload status for a specific upload
 */
function getUploadStatus($upload_id, $usr_id)
{
    global $class_database;

    if (empty($upload_id)) {
        return ['error' => 'Upload ID required'];
    }

    $sql = "SELECT * FROM `db_upload_progress`
            WHERE `upload_id` = '%s' AND `usr_id` = %d
            LIMIT 1";

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

    if (!$row) {
        return ['error' => 'Upload not found'];
    }

    return [
        'upload_id' => $row['upload_id'],
        'filename' => $row['filename'],
        'file_type' => $row['file_type'],
        'file_size' => (int) $row['file_size'],
        'uploaded_bytes' => (int) $row['uploaded_bytes'],
        'upload_percent' => (float) $row['upload_percent'],
        'status' => $row['status'], // uploading, processing, encoding, completed, failed
        'processing_step' => $row['processing_step'],
        'error_message' => $row['error_message'],
        'file_key' => $row['file_key'],
        'started_at' => $row['started_at'],
        'completed_at' => $row['completed_at']
    ];
}

/**
 * Get all active uploads for user
 */
function getAllUploads($usr_id)
{
    global $class_database;

    $sql = "SELECT * FROM `db_upload_progress`
            WHERE `usr_id` = %d
            AND `status` IN ('uploading', 'processing', 'encoding')
            ORDER BY `started_at` DESC";

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

    $uploads = [];
    while ($row = $result->fetch_assoc()) {
        $uploads[] = [
            'upload_id' => $row['upload_id'],
            'filename' => $row['filename'],
            'file_type' => $row['file_type'],
            'file_size' => (int) $row['file_size'],
            'uploaded_bytes' => (int) $row['uploaded_bytes'],
            'upload_percent' => (float) $row['upload_percent'],
            'status' => $row['status'],
            'processing_step' => $row['processing_step'],
            'started_at' => $row['started_at']
        ];
    }

    return ['uploads' => $uploads];
}

/**
 * Cancel an upload
 */
function cancelUpload($upload_id, $usr_id)
{
    global $class_database;

    $sql = "UPDATE `db_upload_progress`
            SET `status` = 'cancelled'
            WHERE `upload_id` = '%s' AND `usr_id` = %d";

    $class_database->doQuery($sql, $upload_id, $usr_id);

    return ['success' => true, 'message' => 'Upload cancelled'];
}
