<?php
require_once __DIR__ . '/../../includes/config.php';
header('Content-Type: application/json');

try {
    if (isset($pdo)) {
        $stmt = $pdo->query("
            SELECT cs.*, COUNT(cl.id) as ingredient_count 
            FROM costing_sheets cs 
            LEFT JOIN costing_lines cl ON cs.id = cl.costing_sheet_id 
            GROUP BY cs.id 
            ORDER BY cs.created_at DESC
        ");
        $sheets = $stmt->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode(['success' => true, 'sheets' => $sheets]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Database connection failed']);
    }
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
?>