<?php
require_once __DIR__ . '/../../../includes/config.php';

if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    http_response_code(400);
    exit('Invalid ID');
}

$sheetId = intval($_GET['id']);

try {
    // Get costing sheet
    $stmt = $pdo->prepare("SELECT * FROM costing_sheets WHERE id = ?");
    $stmt->execute([$sheetId]);
    $sheet = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$sheet) {
        http_response_code(404);
        exit('Costing sheet not found');
    }

    // Get costing lines
    $stmt = $pdo->prepare("SELECT * FROM costing_lines WHERE costing_sheet_id = ?");
    $stmt->execute([$sheetId]);
    $lines = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Create CSV content (Excel compatible)
    $filename = "costing_sheet_{$sheetId}_" . date('Y-m-d') . ".csv";
    
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    
    $output = fopen('php://output', 'w');
    
    // Add headers
    fputcsv($output, ['Recipe Costing Sheet']);
    fputcsv($output, []);
    fputcsv($output, ['Recipe Name:', $sheet['name']]);
    fputcsv($output, ['Category:', $sheet['category']]);
    fputcsv($output, ['Yield Portions:', $sheet['yield_portions']]);
    fputcsv($output, []);
    
    // Add ingredients table
    fputcsv($output, ['Ingredients', 'Quantity', 'Unit Cost', 'Line Cost']);
    foreach ($lines as $line) {
        fputcsv($output, [
            $line['ingredient_name'],
            $line['quantity'],
            'R ' . number_format($line['unit_cost'], 2),
            'R ' . number_format($line['line_cost'], 2)
        ]);
    }
    
    fputcsv($output, []);
    fputcsv($output, ['Total Recipe Cost:', 'R ' . number_format($sheet['total_cost'], 2)]);
    fputcsv($output, ['Cost per Portion:', 'R ' . number_format($sheet['cost_per_portion'], 2)]);
    fputcsv($output, []);
    
    // Add preparation steps
    if (!empty($sheet['prep_steps'])) {
        fputcsv($output, ['Preparation Steps:']);
        $steps = explode("\n", $sheet['prep_steps']);
        foreach ($steps as $step) {
            fputcsv($output, [trim($step)]);
        }
    }
    
    fclose($output);

} catch (Exception $e) {
    http_response_code(500);
    echo 'Error generating file: ' . $e->getMessage();
}
?>