<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Bill;
use App\Models\BillItem;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Carbon;
use App\Models\BillCounter;
class BillController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $bills = Bill::with([
            'items.product',
            'items.product.category',
            'items.product.brand',
            'items.product.style',
            'items.product.size',
            'items.product.color',
            'customer' // Include customer relationship
        ])->get();
        return response()->json($bills);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        DB::beginTransaction();
        try {
            $request->validate([
                'bill_date' => 'required|date',
                'discount' => 'nullable|numeric|min:0',
                'tax_percentage' => 'nullable|numeric|min:0|max:100',
                'final_amount' => 'nullable|numeric|min:0',
                'items' => 'required|array|min:1', // A new bill should typically have at least one sale item
                'items.*.product_id' => 'required|exists:products,product_id',
                'items.*.qty' => 'required|integer|min:1',
                'bill_no' => 'nullable|string|unique:bills,bill_no', // Allow frontend to send, but backend will generate if null
                 'return_items' => 'nullable|array',
                'return_items.*.product_id' => 'required_with:return_items|exists:products,product_id',
                'return_items.*.qty' => 'required_with:return_items|integer|min:1',
            ]);

            $totalQty = 0;
            $totalAmount = 0;
            $billItemsData = [];
            $productsToUpdateStock = []; // To store products and their net stock changes

            // --- Process Sale Items (Decrement Stock) ---
            if ($request->has('items')) {
            foreach ($request->items as $item) {
                $product = Product::find($item['product_id']);

                if (!$product) {
                    throw new \Exception("Product with ID {$item['product_id']} not found.");
                }

                $itemQty = $item['qty'];

                // Stock Management: Check and Prepare for Decrement
                if ($product->product_quantity < $itemQty) {
                    throw new \Exception("Insufficient stock for product: {$product->product_code}. Available: {$product->product_quantity}, Requested: {$itemQty}");
                }
                $productsToUpdateStock[$product->product_id] = ($productsToUpdateStock[$product->product_id] ?? 0) - $itemQty;

                $itemPrice = $product->product_mrp; // Original price
                $itemOurPrice = $product->product_price; // Selling price
                $itemAmount = $itemOurPrice * $itemQty;

                $totalQty += $itemQty;
                $totalAmount += $itemAmount;

                $billItemsData[] = [
                    'product_id' => $product->product_id,
                    'product_description' => $product->product_code . ' - ' . ($product->product_name ?? 'N/A'),
                    'price' => $itemPrice,
                    'our_price' => $itemOurPrice,
                    'qty' => $itemQty,
                    'amount' => $itemAmount,
                ];
            }
        }

         // --- Process Return Items (negative qty & amount) ---
        if ($request->has('return_items')) {
            foreach ($request->return_items as $rItem) {
                $product = Product::find($rItem['product_id']);
                $returnQty = $rItem['qty'];

                // Returns → increase stock
                $productsToUpdateStock[$product->product_id] = ($productsToUpdateStock[$product->product_id] ?? 0) + $returnQty;

                $itemPrice = $product->product_mrp;
                $itemOurPrice = $product->product_price;
                $itemAmount = $itemOurPrice * $returnQty;

                // Store as negative values
                $totalQty -= $returnQty;
                $totalAmount -= $itemAmount;

                $billItemsData[] = [
                    'product_id' => $product->product_id,
                    'product_description' => $product->product_code,
                    'price' => $itemPrice,
                    'our_price' => $itemOurPrice,
                    'qty' => -$returnQty, // negative qty
                    'amount' => -$itemAmount, // negative amount
                ];
            }
        }

            // --- Apply all Net Stock Changes (only from sales in this method) ---
            foreach ($productsToUpdateStock as $productId => $change) {
                $product = Product::find($productId);
                if ($product) {
                    $product->increment('product_quantity', $change); // $change is negative for sales
                }
            }

            $discount = $request->input('discount', 0);
            $taxPercentage = $request->input('tax_percentage', 0);

            $finalAmount = $request->input('final_amount',0);
            // $finalAmount += ($finalAmount * ($taxPercentage / 100));

             $lastBillId = Bill::max('id');
            $nextId = $lastBillId ? $lastBillId + 1 : 1;
            // $generatedBillNo = 'MFLBILL' . str_pad($nextId, 5, '0', STR_PAD_LEFT);

            $currentMonth = date('n'); // 1 to 12
            $currentYear = date('y'); // last two digits

            if ($currentMonth >= 4) {
                // April to December
                $fyStart = $currentYear;
                $fyEnd = $currentYear + 1;
            } else {
                // January to March
                $fyStart = $currentYear - 1;
                $fyEnd = $currentYear;
            }

            $financialYear = $fyStart . '-' . $fyEnd;
            $generatedBillNo1 = 'MFL/' . $financialYear . '/' . str_pad($nextId, 5, '0', STR_PAD_LEFT);

            
            $bill = Bill::create([
                'bill_date' => $request->bill_date,
                'total_qty' => $totalQty,
                'total_amount' => $totalAmount,
                'discount' => $discount,
                'tax_percentage' => $taxPercentage,
                'final_amount' => $request->input('final_amount', $finalAmount), // Allow frontend to send, but backend will calculate if not provided
                'customer_id' => $request->input('customer_id', 0) // Default to 0 if not provided
            ]);

            $generatedBillNo = $request->input('bill_no') ?? $generatedBillNo1;
            $bill->update(['bill_no' => $generatedBillNo]);

            // Create Bill Items for Sale Items only
            foreach ($billItemsData as $itemData) {
                $bill->items()->create($itemData);
            }

            DB::commit();
            return response()->json($bill->load('items.product'), 201);

        } catch (ValidationException $e) {
            DB::rollBack();
            return response()->json(['errors' => $e->errors()], 422);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['message' => 'Error creating bill', 'error' => $e->getMessage()], 500);
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(Bill $bill)
    {
        return response()->json($bill->load('items.product',
            'items.product.category',
            'items.product.brand',
            'items.product.style',
            'items.product.size',
            'items.product.color',  
            'customer' // Include customer relationship
            ));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Bill $bill)
    {
        DB::beginTransaction();
        try {
            $request->validate([
                'bill_date' => 'sometimes|required|date',
                'discount' => 'nullable|numeric|min:0',
                'tax_percentage' => 'nullable|numeric|min:0|max:100',
                'final_amount' => 'nullable|numeric|min:0',
                'items' => 'required|array|min:1',
                'items.*.id' => 'nullable|exists:bill_items,id', // For existing items
                'items.*.product_id' => 'required|exists:products,product_id',
                'items.*.qty' => 'required|integer|min:1',
            ]);

            $totalQty = 0;
            $totalAmount = 0;
            $existingItemIds = [];
            $productsToUpdateStock = []; // To track net stock changes for each product

            // Map existing bill items for easy lookup of old quantities
            $oldBillItems = $bill->items->keyBy('id');
            $oldProductQuantities = []; // Store product_id => old_qty for removed items
            foreach ($oldBillItems as $oldItem) {
                $oldProductQuantities[$oldItem->product_id] = ($oldProductQuantities[$oldItem->product_id] ?? 0) + $oldItem->qty;
            }

            foreach ($request->items as $item) {
                $product = Product::find($item['product_id']);

                if (!$product) {
                    throw new \Exception("Product with ID {$item['product_id']} not found.");
                }

                $itemQty = $item['qty'];
                $oldQty = 0;

                if (isset($item['id']) && $item['id'] && $oldBillItems->has($item['id'])) {
                    // This is an existing item being updated
                    $oldItem = $oldBillItems->pull($item['id']); // Remove from old items map
                    $oldQty = $oldItem->qty;
                    // Remove this product's old quantity from the tracking for removed items
                    $oldProductQuantities[$product->product_id] -= $oldQty;
                }

                $qtyChange = $itemQty - $oldQty; // Positive if quantity increased, negative if decreased

                // Stock Management: Check and Prepare for Decrement/Increment
                if ($qtyChange > 0) { // If quantity increased, check if enough stock is available
                    if ($product->product_quantity < $qtyChange) {
                        throw new \Exception("Insufficient stock for product: {$product->product_code}. Available: {$product->product_quantity}, Needed: {$qtyChange}");
                    }
                }
                $productsToUpdateStock[$product->product_id] = ($productsToUpdateStock[$product->product_id] ?? 0) - $qtyChange;

                $itemPrice = $product->product_mrp;
                $itemOurPrice = $product->product_price;
                $itemAmount = $itemOurPrice * $itemQty;

                $totalQty += $itemQty;
                $totalAmount += $itemAmount;

                $itemData = [
                    'product_id' => $product->product_id,
                    'product_description' => $product->product_code . ' - ' . ($product->product_name ?? 'N/A'),
                    'price' => $itemPrice,
                    'our_price' => $itemOurPrice,
                    'qty' => $itemQty,
                    'amount' => $itemAmount,
                ];

                if (isset($item['id']) && $item['id']) {
                    $billItem = BillItem::find($item['id']);
                    if ($billItem && $billItem->bill_id === $bill->id) {
                        $billItem->update($itemData);
                        $existingItemIds[] = $billItem->id;
                    } else {
                        throw new \Exception("Bill item with ID {$item['id']} not found or does not belong to this bill.");
                    }
                } else {
                    $newItem = $bill->items()->create($itemData);
                    $existingItemIds[] = $newItem->id;
                }
            }

            // Stock Management: Handle removed items (return stock)
            foreach ($oldBillItems as $removedItem) {
                $productsToUpdateStock[$removedItem->product_id] = ($productsToUpdateStock[$removedItem->product_id] ?? 0) + $removedItem->qty;
            }

            // Delete items that were removed from the request
            $bill->items()->whereNotIn('id', $existingItemIds)->delete();

            // Apply all net changes
            foreach ($productsToUpdateStock as $productId => $change) {
                $product = Product::find($productId);
                if ($product) {
                    $product->increment('product_quantity', $change);
                }
            }

            $discount = $request->input('discount', 0);
            $taxPercentage = $request->input('tax_percentage', 0);

            // $finalAmount = $totalAmount - $discount;
            // $finalAmount += ($finalAmount * ($taxPercentage / 100));
            $finalAmount = $request->input('final_amount',0);

            $bill->update([
                'bill_date' => $request->bill_date ?? $bill->bill_date,
                'total_qty' => $totalQty,
                'total_amount' => $totalAmount,
                'customer_id' => $request->input('customer_id', $bill->customer_id), // Update customer_id if provided
                'discount' => $discount,
                'tax_percentage' => $taxPercentage,
                'final_amount' => $request->input('final_amount', $finalAmount) // Allow frontend to send, but backend will calculate if not provided
            ]);

            DB::commit();
            return response()->json($bill->load('items.product'));

        } catch (ValidationException $e) {
            DB::rollBack();
            return response()->json(['errors' => $e->errors()], 422);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['message' => 'Error updating bill', 'error' => $e->getMessage()], 500);
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Bill $bill)
    {
        DB::beginTransaction();
        try {
            // Stock Management: Return stock for deleted bill items
            foreach ($bill->items as $item) {
                $product = Product::find($item->product_id);
                if ($product) {
                    $product->increment('product_quantity', $item->qty);
                }
            }

            $bill->delete();
            DB::commit();
            return response()->json(['message' => 'Bill deleted successfully'], 204);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['message' => 'Error deleting bill', 'error' => $e->getMessage()], 500);
        }
    }

    /**
     * Generate the next available bill number.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    // public function generateNextBillNumber()
    // {
    //     try {
    //         $lastBillId = Bill::max('id');
    //         $nextId = $lastBillId ? $lastBillId + 1 : 1;
    //         // $generatedBillNo = 'MFLBILL' . str_pad($nextId, 5, '0', STR_PAD_LEFT);

    //         $currentMonth = date('n'); // 1 to 12
    //         $currentYear = date('y'); // last two digits

    //         if ($currentMonth >= 4) {
    //             // April to December
    //             $fyStart = $currentYear;
    //             $fyEnd = $currentYear + 1;
    //         } else {
    //             // January to March
    //             $fyStart = $currentYear - 1;
    //             $fyEnd = $currentYear;
    //         }

    //         $financialYear = $fyStart . '-' . $fyEnd;
    //         $generatedBillNo = 'MFL/' . $financialYear . '/' . str_pad($nextId, 5, '0', STR_PAD_LEFT);

    //         return response()->json([
    //             'success' => true,
    //             'next_bill_no' => $generatedBillNo
    //         ]);
    //     } catch (\Exception $e) {
    //         return response()->json(['message' => 'Error generating bill number', 'error' => $e->getMessage()], 500);
    //     }
    // }

    // public function generateNextBillNumber()
    //     {
    //         try {
    //             DB::beginTransaction();
                
    //             // Calculate financial year
    //             $currentMonth = date('n');
    //             $currentYear = date('y');

    //             if ($currentMonth >= 4) {
    //                 $fyStart = $currentYear;
    //                 $fyEnd = $currentYear + 1;
    //             } else {
    //                 $fyStart = $currentYear - 1;
    //                 $fyEnd = $currentYear;
    //             }

    //             $financialYear = $fyStart . '-' . $fyEnd;
                
    //             // Get or create counter with lock
    //             $counter = BillCounter::lockForUpdate()
    //                 ->where('financial_year', $financialYear)
    //                 ->first();
                
    //             if (!$counter) {
    //                 $counter = BillCounter::create([
    //                     'financial_year' => $financialYear,
    //                     'counter' => 1
    //                 ]);
    //                 $nextNumber = 1;
    //             } else {
    //                 $nextNumber = $counter->counter + 1;
    //                 $counter->update(['counter' => $nextNumber]);
    //             }
                
    //             $generatedBillNo = 'MFL/' . $financialYear . '/' . str_pad($nextNumber, 5, '0', STR_PAD_LEFT);
                
    //             DB::commit();
                
    //             return response()->json([
    //                 'success' => true,
    //                 'next_bill_no' => $generatedBillNo
    //             ]);
                
    //         } catch (\Exception $e) {
    //             DB::rollBack();
    //             return response()->json([
    //                 'message' => 'Error generating bill number', 
    //                 'error' => $e->getMessage()
    //             ], 500);
    //         }
    //     }


    public function generateNextBillNumber()
{
    try {
        DB::beginTransaction();
        
        // Calculate financial year
        $currentMonth = date('n');
        $currentYear = date('y');

        if ($currentMonth >= 4) {
            $fyStart = $currentYear;
            $fyEnd = $currentYear + 1;
        } else {
            $fyStart = $currentYear - 1;
            $fyEnd = $currentYear;
        }

        $financialYear = $fyStart . '-' . $fyEnd;
        
        // Get or create counter with lock
        $billCounter = DB::table('bill_counters')
            ->where('financial_year', $financialYear)
            ->lockForUpdate()
            ->first();
        
        if (!$billCounter) {
            // First bill of the financial year
            $nextNumber = 1;
            $generatedBillNo = 'MFL/' . $financialYear . '/' . str_pad($nextNumber, 5, '0', STR_PAD_LEFT);
            
            DB::table('bill_counters')->insert([
                'financial_year' => $financialYear,
                'last_bill_number' => $generatedBillNo,
                'created_at' => now(),
                'updated_at' => now()
            ]);
        } else {
            // Extract number from last bill number
            // Example: MFL/24-25/00005 -> 5
            $lastBillNo = $billCounter->last_bill_number;
            $parts = explode('/', $lastBillNo);
            $lastNumber = (int) $parts[2]; // Get the numeric part
            
            $nextNumber = $lastNumber + 1;
            $generatedBillNo = 'MFL/' . $financialYear . '/' . str_pad($nextNumber, 5, '0', STR_PAD_LEFT);
            
            DB::table('bill_counters')
                ->where('financial_year', $financialYear)
                ->update([
                    'last_bill_number' => $generatedBillNo,
                    'updated_at' => now()
                ]);
        }
        
        DB::commit();
        
        return response()->json([
            'success' => true,
            'next_bill_no' => $generatedBillNo
        ]);
        
    } catch (\Exception $e) {
        DB::rollBack();
        return response()->json([
            'message' => 'Error generating bill number', 
            'error' => $e->getMessage()
        ], 500);
    }
}


    /**
     * Process product returns.
     * This method handles stock increments for returned items.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function processReturns(Request $request)
    {
        DB::beginTransaction();
        try {
            $request->validate([
                'return_date' => 'required|date',
                'return_items' => 'required|array|min:1',
                'return_items.*.product_id' => 'required|exists:products,product_id',
                'return_items.*.qty' => 'required|integer|min:1',
                // Optional: 'original_bill_id' => 'nullable|exists:bills,id',
                // Optional: 'reason' => 'nullable|string|max:255',
            ]);

            $productsToUpdateStock = [];

            foreach ($request->return_items as $returnItem) {
                $product = Product::find($returnItem['product_id']);

                if (!$product) {
                    throw new \Exception("Returned product with ID {$returnItem['product_id']} not found.");
                }

                $returnQty = $returnItem['qty'];
                $productsToUpdateStock[$product->product_id] = ($productsToUpdateStock[$product->product_id] ?? 0) + $returnQty;
            }

            // Apply all stock increments for returns
            foreach ($productsToUpdateStock as $productId => $change) {
                $product = Product::find($productId);
                if ($product) {
                    $product->increment('product_quantity', $change);
                }
            }

            // You might want to log this return transaction in a separate 'returns' table
            // For example:
            // \App\Models\ReturnTransaction::create([
            //     'return_date' => $request->return_date,
            //     'total_qty' => array_sum(array_column($request->return_items, 'qty')),
            //     'original_bill_id' => $request->original_bill_id ?? null,
            //     'reason' => $request->reason ?? null,
            // ]);

            DB::commit();
            return response()->json(['message' => 'Return items processed successfully and stock updated.'], 200);

        } catch (ValidationException $e) {
            DB::rollBack();
            return response()->json(['errors' => $e->errors()], 422);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['message' => 'Error processing returns', 'error' => $e->getMessage()], 500);
        }
    }

    /**
     * Get list of financial years based on bills.
     * Financial year typically runs from April 1st to March 31st.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function getFinancialYears()
    {
        try {
            // Get all unique bill dates
            $billDates = Bill::select('bill_date')
                ->distinct()
                ->orderBy('bill_date', 'asc')
                ->pluck('bill_date');

            if ($billDates->isEmpty()) {
                return response()->json([
                    'success' => true,
                    'financial_years' => [],
                    'message' => 'No bills found'
                ]);
            }

            $financialYears = [];
            $processedYears = [];

            foreach ($billDates as $billDate) {
                $date = Carbon::parse($billDate);
                
                // Determine financial year
                // If month is April (4) or later, FY starts from current year
                // If month is before April, FY started from previous year
                if ($date->month >= 4) {
                    $fyStart = $date->year;
                    $fyEnd = $date->year + 1;
                } else {
                    $fyStart = $date->year - 1;
                    $fyEnd = $date->year;
                }

                $fyKey = $fyStart . '-' . $fyEnd;
                
                // Avoid duplicates
                if (!in_array($fyKey, $processedYears)) {
                    $processedYears[] = $fyKey;
                    
                    // Count bills in this financial year
                    $startDate = Carbon::create($fyStart, 4, 1); // April 1st
                    $endDate = Carbon::create($fyEnd, 3, 31);   // March 31st
                    
                    $billCount = Bill::whereBetween('bill_date', [$startDate, $endDate])->count();
                    $totalAmount = Bill::whereBetween('bill_date', [$startDate, $endDate])->sum('total_amount');

                    $financialYears[] = [
                        'financial_year' => $fyKey,
                        'start_date' => $startDate->format('Y-m-d'),
                        'end_date' => $endDate->format('Y-m-d'),
                        'bill_count' => $billCount,
                        'total_amount' => number_format($totalAmount, 2, '.', '')
                    ];
                }
            }

            // Sort by financial year (descending - most recent first)
            usort($financialYears, function($a, $b) {
                return strcmp($b['financial_year'], $a['financial_year']);
            });

            return response()->json([
                'success' => true,
                'financial_years' => $financialYears
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'message' => 'Error fetching financial years',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get bills for a specific financial year.
     *
     * @param  string  $financialYear (format: 2023-2024)
     * @return \Illuminate\Http\JsonResponse
     */
    public function getBillsByFinancialYear($financialYear)
    {
        try {
            // Validate financial year format
            if (!preg_match('/^\d{4}-\d{4}$/', $financialYear)) {
                return response()->json([
                    'message' => 'Invalid financial year format. Expected format: YYYY-YYYY (e.g., 2023-2024)'
                ], 400);
            }

            // Extract start and end years
            list($startYear, $endYear) = explode('-', $financialYear);
            
            // Validate that end year is start year + 1
            if ((int)$endYear !== (int)$startYear + 1) {
                return response()->json([
                    'message' => 'Invalid financial year. End year must be start year + 1'
                ], 400);
            }

            // Create date range for the financial year
            $startDate = Carbon::create($startYear, 4, 1); // April 1st
            $endDate = Carbon::create($endYear, 3, 31);   // March 31st

            // Get bills within the financial year with all relationships
            $bills = Bill::with([
                'items.product',
                'items.product.category',
                'items.product.brand',
                'items.product.style',
                'items.product.size',
                'items.product.color'
            ])
            ->whereBetween('bill_date', [$startDate, $endDate])
            ->orderBy('bill_date', 'desc')
            ->orderBy('id', 'desc')
            ->get();

                 // Calculate tax amounts for each bill item and add to response
            $totalTaxAmount = 0;
            $processedBills = $bills->map(function ($bill) use (&$totalTaxAmount) {
                $billTaxAmount = 0;
                
                $processedItems = $bill->items->map(function ($item) use (&$billTaxAmount, &$totalTaxAmount) {
                    $product = $item->product;
                    $totalAmount = (float)$item->amount; // This is our_price * qty (total including tax)
                    
                    // Calculate tax amount for this item using product's tax percentage
                     // Calculate tax amount for this item using product's tax percentage
                    // Tax is stored as decimal (e.g., "12.00" for 12%)
                    $productTaxPercentage = $product ? (float)$product->tax : 0;
                     if ($productTaxPercentage > 0) {
                        // Reverse calculation: if total is 210 and tax is 5%
                        // Base amount = 210 / (1 + 5/100) = 210 / 1.05 = 200
                        // Tax amount = 210 - 200 = 10
                        $baseAmount = $totalAmount / (1 + ($productTaxPercentage / 100));
                        $itemTaxAmount = $totalAmount - $baseAmount;
                    } else {
                        $baseAmount = $totalAmount;
                        $itemTaxAmount = 0;
                    }
                    
                    $billTaxAmount += $itemTaxAmount;
                    $totalTaxAmount += $itemTaxAmount;
                    
                    // Add calculated tax information to the item
                    $itemArray = $item->toArray();
                      $itemArray['product_tax_percentage'] = number_format($productTaxPercentage, 2, '.', '');
                    $itemArray['tax_amount'] = number_format($itemTaxAmount, 2, '.', '');
                    $itemArray['amount_with_tax'] = number_format($totalAmount);
                    
                    return $itemArray;
                });
                
                // Add tax information to the bill
                $billArray = $bill->toArray();
                $billArray['items'] = $processedItems;
                $billArray['bill_tax_amount'] = number_format($billTaxAmount, 2, '.', '');
                $billArray['bill_total_with_tax'] = number_format($bill->final_amount + $billTaxAmount, 2, '.', '');
                
                return $billArray;
            });

            // Calculate summary statistics
            $summary = [
                'financial_year' => $financialYear,
                'start_date' => $startDate->format('Y-m-d'),
                'end_date' => $endDate->format('Y-m-d'),
                'total_bills' => $bills->count(),
                'total_amount' => $bills->sum('total_amount'),
                'total_discount' => $bills->sum('discount'),
                'total_final_amount' => $bills->sum('final_amount'),
                'total_tax_amount' => number_format($totalTaxAmount, 2, '.', ''),
                'total_amount_with_tax' => number_format($bills->sum('final_amount') + $totalTaxAmount, 2, '.', ''),
                'total_quantity' => $bills->sum('total_qty'),
                'average_bill_amount' => $bills->count() > 0 ? $bills->avg('total_amount') : 0,
                 'average_tax_per_bill' => $bills->count() > 0 ? ($totalTaxAmount / $bills->count()) : 0
            ];

            return response()->json([
                'success' => true,
                'summary' => $summary,
                'bills' => $processedBills
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'message' => 'Error fetching bills for financial year',
                'error' => $e->getMessage()
            ], 500);
        }
    }
}
