<?php
// api/streaming_config_save.php
require_once '../config/database.php';
require_once '../includes/functions.php';

session_start();
if (!hasRole('admin')) {
    die("Access Denied");
}

$action = $_POST['action'] ?? '';

try {
    if ($action === 'save_global') {
        $api_key = clean_input($_POST['youtube_api_key']);
        $frequency = (int)$_POST['youtube_update_frequency'];
        
        $pdo->beginTransaction();
        $stmt = $pdo->prepare("INSERT INTO settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)");
        $stmt->execute(['youtube_api_key', $api_key]);
        $stmt->execute(['youtube_update_frequency', $frequency]);
        $pdo->commit();
        
        header("Location: ../index.php?page=streaming_config&msg=Global settings saved.");
        exit;
        
    } elseif ($action === 'add_stream') {
        $name = clean_input($_POST['name']);
        $video_id = clean_input($_POST['video_id']);
        
        if (empty($name) || empty($video_id)) die("Name and Video ID required.");
        
        $stmt = $pdo->prepare("INSERT INTO youtube_streams (name, video_id) VALUES (?, ?)");
        $stmt->execute([$name, $video_id]);
        
        header("Location: ../index.php?page=streaming_config&msg=Stream added successfully.");
        exit;
        
    } elseif ($action === 'toggle_stream') {
        $id = (int)$_POST['id'];
        $pdo->query("UPDATE youtube_streams SET is_active = NOT is_active WHERE id = $id");
        header("Location: ../index.php?page=streaming_config&msg=Stream status updated.");
        exit;
        
    } elseif ($action === 'delete_stream') {
        $id = (int)$_POST['id'];
        $pdo->query("DELETE FROM youtube_streams WHERE id = $id");
        header("Location: ../index.php?page=streaming_config&msg=Stream deleted.");
        exit;
        
    }
} catch (PDOException $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    header("Location: ../index.php?page=streaming_config&error=" . urlencode("Error: " . $e->getMessage()));
    exit;
}
