<?php
require_once '../../config/cors.php';
require_once '../../config/db.php';
require_once '../../config/r2.php';
require_once '../cloudflare.php';
require_once '../../helpers/response.php';
require_once '../../helpers/request.php';
require_once '../../helpers/auth.php';

$method = getRequestMethod();

if ($method === 'OPTIONS') {
    http_response_code(200);
    exit;
}

$admin = requireAdmin();

// GET - List all streams
if ($method === 'GET') {
    try {
        $stmt = $pdo->query("
            SELECT ls.*, li.name as input_name, li.cloudflare_input_id
            FROM live_streams ls
            LEFT JOIN live_inputs li ON li.id = ls.live_input_id
            ORDER BY ls.created_at DESC
        ");
        $streams = $stmt->fetchAll();
        
        foreach ($streams as &$stream) {
            if ($stream['thumbnail']) {
                $stream['thumbnail_url'] = R2_PUBLIC_URL . '/' . $stream['thumbnail'];
            } else {
                $stream['thumbnail_url'] = null;
            }
            $stream['is_live'] = ($stream['status'] === 'live');
        }
        
        sendSuccess($streams);
        
    } catch (PDOException $e) {
        sendError('Database error: ' . $e->getMessage(), 500);
    }
}

// POST - Create new stream
elseif ($method === 'POST') {
    // Check if multipart/form-data (for thumbnail) or JSON
    $isMultipart = !empty($_FILES);
    
    if ($isMultipart) {
        // Handle form data with file upload
        $title = $_POST['title'] ?? '';
        $description = $_POST['description'] ?? '';
        $scheduled_start = $_POST['scheduled_start'] ?? null;
        $chat_enabled = isset($_POST['chat_enabled']) ? ($_POST['chat_enabled'] ? 1 : 0) : 1;
        $live_input_id = $_POST['live_input_id'] ?? null;
        $thumbnail = null;
        
        if (!$title || !$live_input_id) {
            sendError('Title and Live Input are required', 400);
        }
        
        // Handle thumbnail upload
        if (isset($_FILES['thumbnail']) && $_FILES['thumbnail']['error'] === UPLOAD_ERR_OK) {
            $file = $_FILES['thumbnail'];
            $allowedTypes = ['image/jpeg', 'image/png', 'image/webp', 'image/jpg'];
            $finfo = finfo_open(FILEINFO_MIME_TYPE);
            $mime_type = finfo_file($finfo, $file['tmp_name']);
            finfo_close($finfo);
            
            if (in_array($mime_type, $allowedTypes)) {
                $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
                $safeTitle = preg_replace('/[^a-zA-Z0-9_-]/', '_', pathinfo($file['name'], PATHINFO_FILENAME));
                $thumbnail_key = 'thumbnails/streams/' . $safeTitle . '_' . time() . '_' . uniqid() . '.' . $extension;
                
                $uploadResult = uploadToR2($file['tmp_name'], $thumbnail_key, $mime_type);
                if ($uploadResult['success']) {
                    $thumbnail = $thumbnail_key;
                }
            }
        }
        
        // Status is always 'scheduled' when created
        $status = 'scheduled';
        
        $stmt = $pdo->prepare("
            INSERT INTO live_streams (title, description, scheduled_start, chat_enabled, live_input_id, status, thumbnail)
            VALUES (?, ?, ?, ?, ?, ?, ?)
        ");
        $stmt->execute([$title, $description, $scheduled_start, $chat_enabled, $live_input_id, $status, $thumbnail]);
        
        sendSuccess(['id' => $pdo->lastInsertId()], 'Stream created');
        
    } else {
        // Handle JSON data (original way)
        $data = json_decode(file_get_contents('php://input'), true);
        
        $title = $data['title'] ?? '';
        $description = $data['description'] ?? '';
        $scheduled_start = $data['scheduled_start'] ?? null;
        $chat_enabled = isset($data['chat_enabled']) ? ($data['chat_enabled'] ? 1 : 0) : 1;
        $live_input_id = $data['live_input_id'] ?? null;
        
        if (!$title || !$live_input_id) {
            sendError('Title and Live Input are required', 400);
        }
        
        $status = 'scheduled';
        
        $stmt = $pdo->prepare("
            INSERT INTO live_streams (title, description, scheduled_start, chat_enabled, live_input_id, status)
            VALUES (?, ?, ?, ?, ?, ?)
        ");
        $stmt->execute([$title, $description, $scheduled_start, $chat_enabled, $live_input_id, $status]);
        
        sendSuccess(['id' => $pdo->lastInsertId()], 'Stream created');
    }
}

else {
    sendError('Method not allowed', 405);
}
?>