<?php
/**
 * Get Recipes API with User Isolation
 */
require_once '../guard.php';
require_once __DIR__ . '/../../includes/database.php';

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

try {
    $db = Database::getInstance();
    $conn = $db->getConnection();
    
    $user_id = $_SESSION['user_id'];
    
    if ($_SESSION['user_role'] === 'superuser') {
        // Superuser sees all recipes
        $stmt = $conn->prepare("
            SELECT r.*, u.full_name as creator_name 
            FROM recipes r 
            LEFT JOIN users u ON r.created_by = u.id 
            ORDER BY r.created_at DESC
        ");
        $stmt->execute();
    } else {
        // Regular users see only their recipes
        $stmt = $conn->prepare("
            SELECT r.*, u.full_name as creator_name 
            FROM recipes r 
            LEFT JOIN users u ON r.created_by = u.id 
            WHERE r.created_by = ? 
            ORDER BY r.created_at DESC
        ");
        $stmt->execute([$user_id]);
    }
    
    $recipes = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'success' => true, 
        'recipes' => $recipes,
        'count' => count($recipes)
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database error']);
}
?>