<?php

function get_menu_items($branch){
    global $pdo;

    // 1) منيو مستقل = separate
    if ($branch['menu_type'] === 'separate'){
        $q = $pdo->prepare("
            SELECT bi.*, i.name, i.description, i.image
            FROM branch_items bi
            JOIN items i ON i.id = bi.item_id
            WHERE bi.branch_id=? AND bi.active=1
            ORDER BY bi.ordering
        ");
        $q->execute([$branch['id']]);
        return $q->fetchAll();
    }

    // 2) منيو مشترك (نفس الأسعار)
    if ($branch['menu_type'] === 'shared'){
        $q = $pdo->prepare("
            SELECT *
            FROM items
            WHERE restaurant_id=? AND active=1
            ORDER BY ordering
        ");
        $q->execute([$branch['restaurant_id']]);
        return $q->fetchAll();
    }

    // 3) منيو مشترك + أسعار مختلفة
    if ($branch['menu_type'] === 'shared_with_branch_prices'){
        $q = $pdo->prepare("
            SELECT 
                i.id,
                i.name,
                i.description,
                i.image,
                COALESCE(bp.price, i.base_price) AS price,
                COALESCE(bp.old_price, i.old_price) AS old_price
            FROM items i
            LEFT JOIN branch_items bp ON bp.item_id = i.id AND bp.branch_id = ?
            WHERE i.restaurant_id=? AND i.active=1
            ORDER BY COALESCE(bp.ordering, i.ordering)
        ");
        $q->execute([$branch['id'], $branch['restaurant_id']]);
        return $q->fetchAll();
    }
}
