<?php

namespace App\Services;

use App\Models\JournalEntry;
use App\Models\Product;
use Illuminate\Support\Facades\Response;
use Symfony\Component\HttpFoundation\StreamedResponse;

class FinancialExportService
{
    public function exportProfitLoss(string $startDate, string $endDate): StreamedResponse
    {
        $headers = [
            'Content-Type' => 'text/csv',
            'Content-Disposition' => 'attachment; filename="profit_loss_' . $startDate . '_to_' . $endDate . '.csv"',
        ];

        $callback = function () use ($startDate, $endDate) {
            $file = fopen('php://output', 'w');
            fputcsv($file, ['Date', 'Description', 'Account', 'Debit', 'Credit']);

            // Fetch Journal Entries related to Income and Expense accounts
            // This is a simplified logic. In real ERP, we filter by Account Type.
            // Assuming Account Types: 4 (Income), 5 (Expense).
            
            $entries = JournalEntry::whereBetween('date', [$startDate, $endDate])
                ->with(['items.account'])
                ->get();

            foreach ($entries as $entry) {
                foreach ($entry->items as $item) {
                     // Check if account type is Income or Expense (mocked logic as Account model structure is unknown)
                     // Using mock check for now
                     if (in_array($item->account->type, ['INCOME', 'EXPENSE'])) {
                        fputcsv($file, [
                            $entry->date,
                            $entry->description,
                            $item->account->name,
                            $item->debit,
                            $item->credit
                        ]);
                     }
                }
            }
            fclose($file);
        };

        return Response::stream($callback, 200, $headers);
    }

    public function exportInventoryValuation(): StreamedResponse
    {
        $headers = [
            'Content-Type' => 'text/csv',
            'Content-Disposition' => 'attachment; filename="inventory_valuation_' . date('Y-m-d') . '.csv"',
        ];

        $callback = function () {
            $file = fopen('php://output', 'w');
            fputcsv($file, ['Product Name', 'SKU', 'Category', 'Quantity', 'Cost Price', 'Total Value', 'Bin Location']);

            Product::chunk(100, function ($products) use ($file) {
                foreach ($products as $product) {
                    fputcsv($file, [
                        $product->name,
                        $product->sku ?? 'N/A', // Assuming SKU exists or N/A
                        $product->category,
                        $product->quantity,
                        $product->cost_price,
                        $product->quantity * $product->cost_price,
                        $product->bin_location ?? 'N/A',
                    ]);
                }
            });
            fclose($file);
        };

        return Response::stream($callback, 200, $headers);
    }
}
