<?php
/**
 * 🔗 SHARE ACTION API
 * API für das Teilen von Schnellaktionen
 */

session_start();
require_once '../../config/database_optimized.php';

// Set JSON header
header('Content-Type: application/json');

// Check if user is logged in
if (!isset($_SESSION['admin_logged_in']) || !$_SESSION['admin_logged_in']) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

$db = DatabaseOptimized::getInstance();
$conn = $db->getConnection();
$current_user_id = $_SESSION['admin_user_id'] ?? null;

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    // Get shared action by token
    $share_token = $_GET['token'] ?? '';
    
    if (empty($share_token)) {
        http_response_code(400);
        echo json_encode(['error' => 'Token required']);
        exit;
    }
    
    try {
        $stmt = $conn->prepare("
            SELECT id, title, description, url, icon, background_color, text_color, target, created_at
            FROM quick_actions 
            WHERE share_token = ? AND is_active = 1
        ");
        $stmt->execute([$share_token]);
        $action = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($action) {
            echo json_encode([
                'success' => true,
                'action' => $action
            ]);
        } else {
            http_response_code(404);
            echo json_encode(['error' => 'Action not found']);
        }
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => 'Database error']);
    }
    
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Generate share token for action
    $action_id = $_POST['action_id'] ?? '';
    
    if (empty($action_id)) {
        http_response_code(400);
        echo json_encode(['error' => 'Action ID required']);
        exit;
    }
    
    try {
        // Verify ownership
        $stmt = $conn->prepare("
            SELECT id FROM quick_actions 
            WHERE id = ? AND user_id = ?
        ");
        $stmt->execute([$action_id, $current_user_id]);
        
        if ($stmt->rowCount() === 0) {
            http_response_code(403);
            echo json_encode(['error' => 'Action not found or not owned by user']);
            exit;
        }
        
        // Generate new share token
        $share_token = bin2hex(random_bytes(16));
        
        $stmt = $conn->prepare("
            UPDATE quick_actions 
            SET share_token = ?, updated_at = NOW() 
            WHERE id = ? AND user_id = ?
        ");
        $stmt->execute([$share_token, $action_id, $current_user_id]);
        
        $share_url = "https://" . $_SERVER['HTTP_HOST'] . dirname(dirname($_SERVER['REQUEST_URI'])) . "/admin/share_action.php?token=" . $share_token;
        
        echo json_encode([
            'success' => true,
            'share_token' => $share_token,
            'share_url' => $share_url
        ]);
        
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => 'Database error']);
    }
    
} else {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
}
?>
