<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Rentsum; // Corrected Model Name
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;
use Carbon\Carbon;

class RentsumController extends Controller
{
    public function RentSummaryReport(Request $request)
    {
        // Validate the incoming request
        $request->validate([
            'from_date' => 'required|date',
            'to_date' => 'required|date',
            'report_type' => 'required|in:summary,detailed',
        ]);

        // Format the dates
        $fromDate = Carbon::parse($request->from_date)->startOfDay();
        $toDate = Carbon::parse($request->to_date)->endOfDay();

        // **Ensure these variables are always defined**
        $summaryData = collect();
        $detailedData = collect();
        $grandTotal = 0; // Initialize the grand total variable

        // Fetch data based on report type
        if ($request->report_type === 'summary') {
            // Fetch summary data
            $summaryData = Rentsum::fetchSummaryData($fromDate, $toDate);

            // Calculate the grand total for the summary data by summing the 'total' field
            $grandTotal = $summaryData->sum('total'); // Summing 'total' field from the fetched data
        } elseif ($request->report_type === 'detailed') {
            // Fetch detailed data
            $detailedData = Rentsum::fetchDetailedData($fromDate, $toDate);
        }

        // Log the fetched detailed data (if any)
        \Log::info('Detailed data passed to view:', $detailedData->toArray());

        // Return the view with the necessary data, including grand total
        return view('Rentsummary', [
            'summaryData' => $summaryData,
            'detailedData' => $detailedData,
            'fromDate' => $fromDate->format('Y-m-d'),
            'toDate' => $toDate->format('Y-m-d'),
            'grandTotal' => $grandTotal, // Pass the grand total to the view
        ]);
    }



}
