<?php

namespace App\Http\Controllers;

use App\Exports\StockReportExport;
use App\Models\Product;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

class StockReportController extends Controller
{
    public function export(Request $request)
    {
        $validated = $request->validate([
            'export_format' => ['required', 'in:csv,excel,pdf'],
            'export_stock_status' => ['nullable', 'in:all,in_stock,low_stock,out_of_stock'],
        ]);

        $stockStatus = $validated['export_stock_status'] ?? 'all';
        $format = $validated['export_format'];

        $export = new StockReportExport($stockStatus);

        $filename = 'stock_report_'.now()->format('Y-m-d_H-i-s');

        return match ($format) {
            'csv' => Excel::download($export, $filename.'.csv', \Maatwebsite\Excel\Excel::CSV),
            'excel' => Excel::download($export, $filename.'.xlsx', \Maatwebsite\Excel\Excel::XLSX),
            'pdf' => Excel::download($export, $filename.'.pdf', \Maatwebsite\Excel\Excel::DOMPDF),
            default => back()->with('error', 'Format d\'export invalide'),
        };
    }

    public function print(Request $request)
    {
        $validated = $request->validate([
            'print_stock_status' => ['nullable', 'in:all,in_stock,low_stock,out_of_stock'],
        ]);

        $stockStatus = $validated['print_stock_status'] ?? 'all';

        // Get filtered products
        $query = Product::with(['saleUnit', 'purchaseUnit'])
            ->where('status', Product::STATUS_ACTIVE);

        if ($stockStatus === 'in_stock') {
            $query->where('current_stock', '>', 0);
        } elseif ($stockStatus === 'low_stock') {
            $query->whereColumn('current_stock', '<=', 'reorder_level')
                ->where('current_stock', '>', 0);
        } elseif ($stockStatus === 'out_of_stock') {
            $query->where('current_stock', '<=', 0);
        }

        $products = $query->orderBy('name')->get();

        // Calculate summary
        $totalProducts = $products->count();
        $totalStockValue = $products->sum(function ($product) {
            return $product->current_stock * ($product->purchase_price ?? 0);
        });
        $totalStockQuantity = $products->sum('current_stock');

        return view('livewire.reports.stock.print', compact(
            'products',
            'totalProducts',
            'totalStockValue',
            'totalStockQuantity',
            'stockStatus'
        ));
    }
}
