<?php
require_once '../../config/cors.php';
require_once '../../config/db.php';
require_once '../../config/r2.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();

$id = isset($_GET['id']) ? intval($_GET['id']) : null;

if (!$id) {
    sendError('Stream ID required', 400);
}

// PUT - Update stream
if ($method === 'PUT') {
    $isMultipart = !empty($_FILES);
    
    if ($isMultipart) {
        $title = $_POST['title'] ?? null;
        $description = $_POST['description'] ?? null;
        $scheduled_start = $_POST['scheduled_start'] ?? null;
        $chat_enabled = isset($_POST['chat_enabled']) ? ($_POST['chat_enabled'] ? 1 : 0) : null;
        $thumbnail = null;
        
        $updates = [];
        $params = [':id' => $id];
        
        if ($title !== null) {
            $updates[] = "title = :title";
            $params[':title'] = $title;
        }
        if ($description !== null) {
            $updates[] = "description = :description";
            $params[':description'] = $description;
        }
        if ($scheduled_start !== null) {
            $updates[] = "scheduled_start = :scheduled_start";
            $params[':scheduled_start'] = $scheduled_start;
        }
        if ($chat_enabled !== null) {
            $updates[] = "chat_enabled = :chat_enabled";
            $params[':chat_enabled'] = $chat_enabled;
        }
        
        // 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)) {
                // Delete old thumbnail if exists
                $oldStmt = $pdo->prepare("SELECT thumbnail FROM live_streams WHERE id = ?");
                $oldStmt->execute([$id]);
                $oldThumbnail = $oldStmt->fetchColumn();
                if ($oldThumbnail) {
                    deleteFromR2($oldThumbnail);
                }
                
                $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;
                    $updates[] = "thumbnail = :thumbnail";
                    $params[':thumbnail'] = $thumbnail;
                }
            }
        }
        
        if (empty($updates)) {
            sendError('No fields to update', 400);
        }
        
        $sql = "UPDATE live_streams SET " . implode(', ', $updates) . " WHERE id = :id";
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        
        sendSuccess(null, 'Stream updated');
        
    } else {
        // JSON data
        $data = json_decode(file_get_contents('php://input'), true);
        
        $updates = [];
        $params = [':id' => $id];
        
        if (isset($data['title'])) {
            $updates[] = "title = :title";
            $params[':title'] = $data['title'];
        }
        if (isset($data['description'])) {
            $updates[] = "description = :description";
            $params[':description'] = $data['description'];
        }
        if (isset($data['scheduled_start'])) {
            $updates[] = "scheduled_start = :scheduled_start";
            $params[':scheduled_start'] = $data['scheduled_start'];
        }
        if (isset($data['chat_enabled'])) {
            $updates[] = "chat_enabled = :chat_enabled";
            $params[':chat_enabled'] = $data['chat_enabled'] ? 1 : 0;
        }
        
        if (empty($updates)) {
            sendError('No fields to update', 400);
        }
        
        $sql = "UPDATE live_streams SET " . implode(', ', $updates) . " WHERE id = :id";
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        
        sendSuccess(null, 'Stream updated');
    }
}

// DELETE - Remove stream
elseif ($method === 'DELETE') {
    try {
        // Get thumbnail to delete from R2
        $stmt = $pdo->prepare("SELECT thumbnail FROM live_streams WHERE id = ?");
        $stmt->execute([$id]);
        $thumbnail = $stmt->fetchColumn();
        
        if ($thumbnail) {
            deleteFromR2($thumbnail);
        }
        
        $stmt = $pdo->prepare("DELETE FROM live_streams WHERE id = ?");
        $stmt->execute([$id]);
        
        sendSuccess(null, 'Stream deleted');
        
    } catch (PDOException $e) {
        sendError('Database error: ' . $e->getMessage(), 500);
    }
}

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