<?php

namespace App\Http\Controllers;
use App\Models\modelStatements;
use Illuminate\Http\Request;
use App\Models\modelTenants;
use App\Models\Rentsum;
use Carbon\Carbon;  // Add this lin
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;
class StatementsController extends Controller
{
    public function index($Type)
    {
            try
            {
                $currencys=modelStatements::selectcurrency(Session::get('PropertyCode'));
                $Accounts=modelStatements::selectTenants(Session::get('PropertyCode'));
                if($Type=="Tenant")
            {
                $Accounts=modelStatements::selectTenants(Session::get('PropertyCode'));
                $floors = modelTenants::selectFloors(Session::get('PropertyCode'));

            }
            else   if($Type=="Customer")
            {

                $Accounts=modelStatements::selectCustomer(Session::get('PropertyCode'));
                $floors = [];

            }
            else  if($Type=="Supplier")
            {
                $Accounts=modelStatements::selectSupplier(Session::get('PropertyCode'));
                $floors = [];

            }
            $name=  $Type;
            $code=  "0000";
            $openingBalance=0;
            $from="";
            $to="";
            $currnames="";
                $trans=modelStatements::selectTrans1(Session::get('PropertyCode'));
                $cst=modelStatements::selectInvoiceCustomer(Session::get('PropertyCode'),$Type,"");
                $pdetails=modelStatements::selectInvoiceProperty(Session::get('PropertyCode'),Session::get('RegNo'));
                return view('/Statements', compact('Accounts','Type','trans','name','code','currencys','from','to','currnames','openingBalance','cst','pdetails', 'floors'));

        } catch (\Exception $e) {

            return redirect()->route('otheraccounts')->withErrors(['error' => 'An error occurred!!' . $e->getMessage()]);
        }

        }
        public function fetchAllTransactions(Request $request)

        {
            $request->validate([
                'from' => 'required|string',
                'to' => 'required|string',
                'curr' => 'required|string',
                'Type' => 'required|string', // Must always be "Tenant" for this function
            ]);

            $from = $request->input('from');
            $to = $request->input('to');
            $curr = $request->input('curr');
            $Type = $request->input('Type');
            $contraCode = $request->input('statement_type', 'both'); // Default to 'both' if not provided

            if ($Type !== 'Tenant') {
                return redirect()->route('statements')->withErrors(['error' => 'This function only supports tenant transactions']);
            }

            // Fetch currency details
            $currname = modelStatements::selectcurrencyName(Session::get('PropertyCode'), $curr);
            $currnames = $currname[0]->Name;

            // Fetch all tenants for the property
            $Accounts = modelStatements::selectTenants(Session::get('PropertyCode'));
            $allTransactions = []; // Store all tenant transactions

            foreach ($Accounts as $tenant) {
                $AccCode = $tenant->AccCode;
                $AccSubCode = $tenant->AccSubCode;

                // Fetch tenant-specific transactions
                $transactions = modelStatements::selectHomeTrans2(
                    Session::get('PropertyCode'),
                    $AccCode,
                    $AccSubCode,
                    $curr,
                    $from,
                    $to,
                    $Type,
                    $contraCode
                );

                // Fetch additional customer-specific information
                $customerInfo = modelStatements::selectInvoiceCustomer(Session::get('PropertyCode'), $Type, $AccSubCode);

                // Store transactions indexed by tenant account subcode
                $allTransactions[$tenant->AccSubCode] = [
                    'name' => $tenant->AccName,
                    'transactions' => $transactions,
                    'customerInfo' => $customerInfo,
                ];
            }

            // Fetch property details
            $propertyDetails = modelStatements::selectInvoiceProperty(Session::get('PropertyCode'), Session::get('RegNo'));

            return view('/allTenantsStatements', compact(
                'Accounts',
                'allTransactions',
                'currnames',
                'from',
                'to',
                'propertyDetails'
            ));
        }

        public function fetchTransactions(Request $request)
        {
            $request->validate([
                'Type' => 'required|string',
                'from' => 'required|string',
                'to' => 'required|string',
                'curr' => 'required|string',
                'statement_type' => 'string',
            ]);
            $Rate = 1;
            $accounts = $request->input('account');
            $from = $request->input('from');
            $to = $request->input('to');
            $curr = $request->input('curr');
            $Type = $request->input('Type');
            $from_floor = $request->input("floor_from");
            $to_floor = $request->input("floor_to");
            $ContraCode = $request->input('statement_type');

            $currname = modelStatements::selectcurrencyName(Session::get('PropertyCode'), $curr);
            $currnames = $currname[0]->Name;

            $Accounts = [];
            $allTransactions = []; // To store transactions for all tenants
            $trans = []; // Transactions for a single tenant (will remain empty if $accounts == "all")
            if ($accounts == "all") {
                // Fetch all tenants
                $Accounts = modelStatements::selectTenantsByFloor(Session::get('PropertyCode'), $from_floor, $to_floor);

                // Loop through each tenant and fetch their transactions
                foreach ($Accounts as $tenant) {
                    $AccCode = $tenant->AccCode;
                    $AccSubCode = $tenant->AccSubCode;
                    // Fetch transactions using selectHomeTrans2
                    if ($ContraCode == "both") {
                        $transactions = modelStatements::selectHomeTrans(Session::get('PropertyCode'), $AccCode, $AccSubCode, $curr, $from, $to, $Type);
                        $transOpening = modelStatements::selectHomeTransOpening(Session::get('PropertyCode'), $AccCode, $AccSubCode, $curr, $from, $to, $Type);

                    } else {

                    $transactions = modelStatements::selectHomeTrans2(
                        Session::get('PropertyCode'),
                        $AccCode,
                        $AccSubCode,
                        $curr,
                        $from,
                        $to,
                        $Type,
                        $ContraCode
                    );
                    $transOpening = modelStatements::selectHomeTransOpening2(Session::get('PropertyCode'), $AccCode, $AccSubCode, $curr, $from, $to, $Type, $ContraCode);

                }
                    // Store transactions indexed by tenant
                    $allTransactions[$tenant->AccSubCode] = [
                        'name' => $tenant->AccName,
                        'code' => $tenant->AccSubCode,
                        'address' => $tenant->Address,
                        'email' => $tenant->Email,
                        'contact' => $tenant->Contact,
                        'floor' => $tenant->Floor,
                        'rooms' => $tenant->Rooms,
                        'space' => $tenant->Space,
                        'transactions' => $transactions,
                        "openingBalance"=>$transOpening,
                    ];

                }
                $currencys = modelStatements::selectcurrency(Session::get('PropertyCode'));
                $openingBalance = 0;
            } else {
                // Handle single tenant logic
                $accounts = explode(':', $accounts);
                $AccCode = $accounts[0];
                $AccSubCode = isset($accounts[1]) ? $accounts[1] : '0';
                if ($Type == "Tenant") {
                    $Accounts = modelStatements::selectTenants1(Session::get('PropertyCode'), $AccSubCode);
                    $floors = modelTenants::selectFloors(Session::get('PropertyCode'));
                } elseif ($Type == "Customer") {
                    $Accounts = modelStatements::selectCustomer1(Session::get('PropertyCode'), $AccSubCode);
                } elseif ($Type == "Supplier") {
                    $Accounts = modelStatements::selectSupplier1(Session::get('PropertyCode'), $AccSubCode);
                }
                $name = $Accounts[0]->AccName;
                $code = $Accounts[0]->AccSubCode;
                $currencys = modelStatements::selectcurrency(Session::get('PropertyCode'));
                $openingBalance = 0;
                $trans = modelStatements::selectTrans(Session::get('PropertyCode'), $AccCode, $AccSubCode, $curr, $from, $to, $Type);
                $transOpening = $trans;
                $selectHomeCurrency = modelStatements::selectHomeCurrency(Session::get('PropertyCode'));
                if (count($selectHomeCurrency) > 0) {
                    $homeCurrency = $selectHomeCurrency[0]->Currency;
                    if ($curr == $homeCurrency) {
                        if ($ContraCode == "both") {
                            $trans = modelStatements::selectHomeTrans(Session::get('PropertyCode'), $AccCode, $AccSubCode, $curr, $from, $to, $Type);
                            $transOpening = modelStatements::selectHomeTransOpening(Session::get('PropertyCode'), $AccCode, $AccSubCode, $curr, $from, $to, $Type);

                        } else {
                            $trans = modelStatements::selectHomeTrans2(Session::get('PropertyCode'), $AccCode, $AccSubCode, $curr, $from, $to, $Type, $ContraCode);
                            $transOpening = modelStatements::selectHomeTransOpening2(Session::get('PropertyCode'), $AccCode, $AccSubCode, $curr, $from, $to, $Type, $ContraCode);
                         // Check if transOpening is not empty and has a total
        if (!empty($transOpening) && isset($transOpening[0]->total)) {
            $openingBalance = $transOpening[0]->total;
        } else {
            $openingBalance = 0; // Default value if no transactions found
        }
                        }

                    } else {
                        $myRateValidation = modelStatements::selectRate(Session::get('PropertyCode'), $curr, $AccCode, $AccSubCode, $from, $to);

                        if (count($myRateValidation) == 0) {
                            return redirect()->route('statements', ['Type' => $Type])->withErrors(['error' => 'Cannot Run This Report With The Selected Currency']);
                        } else {
                            $trans = modelStatements::selectTrans(Session::get('PropertyCode'), $AccCode, $AccSubCode, $curr, $from, $to, $Type);
                            $transOpening = modelStatements::selectTransOpeningBalance(Session::get('PropertyCode'), $AccCode, $AccSubCode, $curr, $from, $to, $Type);
                             // Check if transOpening is not empty and has a total
        if (!empty($transOpening) && isset($transOpening[0]->total)) {
            $openingBalance = $transOpening[0]->total;
        } else {
            $openingBalance = 0; // Default value if no transactions found
        }

                        }
                    }
                } else {
                    return redirect()->route('statements', ['Type' => $Type])->withErrors(['error' => 'Home Currency Not Found']);
                }
            }
            $floors = modelTenants::selectFloors(Session::get('PropertyCode'));

            $pdetails=modelStatements::selectInvoiceProperty(Session::get('PropertyCode'),Session::get('RegNo'));
            $cst=modelStatements::selectInvoiceCustomer(Session::get('PropertyCode'),$Type,$AccSubCode);

            if(!empty($trans)){
                return view('/Statements', compact('Accounts', 'Type', 'trans', 'allTransactions', 'name', 'code', 'currencys', 'from', 'to', 'currnames', 'openingBalance', 'floors', 'pdetails', 'cst'));

            }
            else{
                return view('/Statements', compact('Accounts', 'Type', 'trans', 'allTransactions', 'currencys', 'from', 'to', 'currnames', 'openingBalance', 'floors', 'pdetails', 'cst'));

            }
        }

        public function indexGeneralLedger()
        {

                try
                {
                    $currencys=modelStatements::selectcurrency(Session::get('PropertyCode'));

                    $Accounts=modelStatements::selectgl(Session::get('PropertyCode'));

                $name=  "";
                $code=  "0000";
                $openingBalance=0;
                $from="";
                $to="";
                $currnames="";

                    $trans=modelStatements::selectTrans1(Session::get('PropertyCode'));

                    return view('/GLReport', compact('Accounts','trans','name','code','currencys','from','to','currnames','openingBalance'));

            } catch (\Exception $e) {

                return redirect()->route('otheraccounts')->withErrors(['error' => 'An error occurred!!' . $e->getMessage()]);
            }

            }

            public function fetchGeneralLedger(Request $request)
            {

                $request->validate([

                     'from' => 'required|string',
                      'to' => 'required|string',
                      'curr' => 'required|string'

                ]);
                $Rate=1;
                $accounts = $request->input('account');
                $from = $request->input('from');
                $to = $request->input('to');
                $curr = $request->input('curr');
                $accounts = explode(':', $accounts);
                $AccCode = $accounts[0];
                $AccSubCode = isset($accounts[1]) ? $accounts[1] : '0';
                $Type = "GL";
                $currname=modelStatements::selectcurrencyName(Session::get('PropertyCode'),$curr);
                $currnames=$currname[0]->Name;
                if($AccSubCode=="0")
                {
                    $Accounts=modelStatements::selectglByCode(Session::get('PropertyCode'),$AccCode);
                    $name=  $Accounts[0]->AccName;
                    $code=  $Accounts[0]->AccCode;

                }
                else
                {
                    $Accounts=modelStatements::selectglByCode1(Session::get('PropertyCode'),$AccCode,$AccSubCode );
                    $name=  $Accounts[0]->AccName;
                    $code=  $Accounts[0]->AccCode;
                }
                $Accounts=modelStatements::selectgl(Session::get('PropertyCode'));

                $currencys=modelStatements::selectcurrency(Session::get('PropertyCode'));
                $openingBalance=0;

                $trans=modelStatements::selectTrans(Session::get('PropertyCode'),$AccCode,$AccSubCode,$curr, $from , $to, $Type);
                $transOpening=$trans;

                $selectHomeCurrency=modelStatements::selectHomeCurrency(Session::get('PropertyCode'));

                if(count($selectHomeCurrency)>0)
                {
                    $homeCurrency=$selectHomeCurrency[0]->Currency;
                    if($curr==$homeCurrency)
                    {


                        $trans=modelStatements::selectHomeTrans(Session::get('PropertyCode'),$AccCode,$AccSubCode,$curr, $from , $to, $Type);

                    }
                    else
                    {
                        $myRateValidation=modelStatements::selectRate(Session::get('PropertyCode'),$curr,$AccCode,$AccSubCode, $from, $to);

                        if(count($myRateValidation)==0)
                        {
                            return redirect()->route('statements',['Type'=>$Type])->withErrors(['error' => 'Cannot Run This Report With The Selected Currency' ]);
                        }
                        else
                        {

                        $trans=modelStatements::selectTrans(Session::get('PropertyCode'),$AccCode,$AccSubCode,$curr, $from , $to, $Type);


                    }

                    }

                }
                else
                {
                    return redirect()->route('GLReport',['Type'=>$Type])->withErrors(['error' => 'Home Currency Not Found' ]);

                }


                return view('/GLReport', compact('Accounts','trans','name','code','currencys','from','to','currnames','openingBalance'));

            }

        public function PrintChartOfAccounts()
    {
            try
            {

                $Accs=modelStatements::selectgl(Session::get('PropertyCode'));
                $Accounts=modelStatements::selectAccountsTypes(Session::get('PropertyCode'));
                $type="All";

                return view('/ChartOfAccountsReport', compact('Accounts','Accs','type'));



        } catch (\Exception $e) {

            return redirect()->route('otheraccounts')->withErrors(['error' => 'An error occurred!!' . $e->getMessage()]);
        }

        }

        public function fetchAccountsByType(Request $request)
        {

            $request->validate([
                'account' => 'required|string'

            ]);

            $accounts = $request->input('account');

            if($accounts=="All")
            {

                $Accs=modelStatements::selectgl(Session::get('PropertyCode'));
                $Accounts=modelStatements::selectAccountsTypes(Session::get('PropertyCode'));
                $type="All";

                return view('/ChartOfAccountsReport', compact('Accounts','Accs','type'));

            }
            else
            {
                $Accs=modelStatements::selectglByType(Session::get('PropertyCode'),$accounts);
                $Accounts=modelStatements::selectAccountsTypes(Session::get('PropertyCode'));
                $types=modelStatements::selectAccountsTypesBYID(Session::get('PropertyCode'),$accounts);
                $type=$types[0]->Name;

                return view('/ChartOfAccountsReport', compact('Accounts','Accs','type'));

            }

        }

        public function indexCashBook()
        {
                try
                {
                    $currencys=modelStatements::selectcurrency(Session::get('PropertyCode'));
                    $Accounts=modelStatements::selectglCashBook(Session::get('PropertyCode'));

                $code=  "0000";
                $from="";
                $to="";
                $currnames="";
                $name="Tenant";
                $openingBalance=0;

                    $trans=modelStatements::selectTrans1(Session::get('PropertyCode'));

                    return view('/CashBookReport', compact('Accounts','trans','code','currencys','from','to','currnames','name','openingBalance'));

            } catch (\Exception $e) {

                return redirect()->route('otheraccounts')->withErrors(['error' => 'An error occurred!!' . $e->getMessage()]);
            }

            }

        public function fetchCashBookReport(Request $request)

        {
            $request->validate([
                'account' => 'required|string',
                 'from' => 'required|string',
                  'to' => 'required|string',
                  'curr' => 'required|string'
            ]);
            $Rate=1;
            $accounts = $request->input('account');
            $from = $request->input('from');
            $to = $request->input('to');
            $curr = $request->input('curr');
            $AccSubCode="0";
            $AccCode = $accounts;
            $currname=modelStatements::selectcurrencyName(Session::get('PropertyCode'),$curr);
            $currnames=$currname[0]->Name;
            $Accounts=modelStatements::selectglCashBookBYCode(Session::get('PropertyCode'),$accounts);
            $name= $Accounts[0]->Name;
            $code= $Accounts[0]->AccCode;
            $openingBalance=0;
            $currencys=modelStatements::selectcurrency(Session::get('PropertyCode'));
            $trans=modelStatements::selectTrans(Session::get('PropertyCode'),$AccCode,$AccSubCode,$curr, $from , $to,"Tenant");
            $transOpening=$trans;
            $selectHomeCurrency=modelStatements::selectHomeCurrency(Session::get('PropertyCode'));
            if(count($selectHomeCurrency)>0)
            {
                $homeCurrency=$selectHomeCurrency[0]->Currency;
                if($curr==$homeCurrency)
                {
                    $trans=modelStatements::selectHomeTrans(Session::get('PropertyCode'),$AccCode,$AccSubCode,$curr, $from , $to, "Tenant");
                    $transOpening=modelStatements::selectHomeTransOpening(Session::get('PropertyCode'),$AccCode,$AccSubCode,$curr, $from , $to,  "Tenant");
                    $openingBalance=$transOpening[0]->total;
                }
                else
                {
                    $myRateValidation=modelStatements::selectRate(Session::get('PropertyCode'),$curr,$AccCode,$AccSubCode, $from, $to);

                    if(count($myRateValidation)==0)
                    {
                        return redirect()->route('cashbookreport')->withErrors(['error' => 'Cannot Run This Report With The Selected Currency' ]);
                    }
                    else
                    {
                    $trans=modelStatements::selectTrans(Session::get('PropertyCode'),$AccCode,$AccSubCode,$curr, $from , $to,"Tenant");
                    $transOpening=modelStatements::selectTransOpeningBalance(Session::get('PropertyCode'),$AccCode,$AccSubCode,$curr, $from , $to,  "Tenant");
                    $openingBalance=$transOpening[0]->total;
                }

                }
            }
            else
            {
                return redirect()->route('cashbookreport')->withErrors(['error' => 'Home Currency Not Found' ]);
            }
            return view('/CashBookReport', compact('Accounts','trans','name','code','currencys','from','to','currnames','openingBalance'));
        }


        public function indexTax()
        {

                try
                {
                    $taxs=modelStatements::selectTax(Session::get('PropertyCode'));

                     $currencys=modelStatements::selectcurrency(Session::get('PropertyCode'));

                     $currnames="";
                $code=  "0000";
                $pfrom="";
                $pto="";
                $from="";
                $to="";

                $name="Tax";

                    $trans=modelStatements::selectTrans1(Session::get('PropertyCode'));

                    return view('/TaxReport', compact('trans','code','pfrom','pto','from','to','name','taxs','currnames','currencys'));



            } catch (\Exception $e) {

                return redirect()->route('otheraccounts')->withErrors(['error' => 'An error occurred!!' . $e->getMessage()]);
            }

            }

        public function fetchTax(Request $request)
        {

            $request->validate([
                'tax' => 'required|string',
                 'from' => 'required|string',
                  'to' => 'required|string',
                  'pfrom' => 'required|string',
                  'pto' => 'required|string',
                  'curr' => 'required|string'

            ]);

            $Rate=1;
            $tax = $request->input('tax');
            $from = $request->input('from');
            $to = $request->input('to');
            $pfrom = $request->input('pfrom');
            $pto = $request->input('pto');
            $curr = $request->input('curr');
            $AccSubCode="0";
            $AccCode ="0";
            $name=  "";
            $code=  "";

            $taxs=modelStatements::selectTax(Session::get('PropertyCode'));
            $currname=modelStatements::selectcurrencyName(Session::get('PropertyCode'),$curr);
            $currnames=$currname[0]->Name;

            if($tax=="All")
            {
                $name=  "Tax Report";
                $code=  "Tax Report";
            }
            else
            {
            $Accounts=modelStatements::selectTaxByID(Session::get('PropertyCode'),$tax);
            $name=  $Accounts[0]->Name;
            $code=  $Accounts[0]->Name;
            }

            $currencys=modelStatements::selectcurrency(Session::get('PropertyCode'));
            $trans=modelStatements::selectTransTax(Session::get('PropertyCode'),$AccCode,$AccSubCode,$curr, $from , $to,"Tax",$pfrom,$to,$tax);

            $selectHomeCurrency=modelStatements::selectHomeCurrency(Session::get('PropertyCode'));

            if(count($selectHomeCurrency)>0)
            {
                $homeCurrency=$selectHomeCurrency[0]->Currency;
                if($curr==$homeCurrency)
                {

                    $trans=modelStatements::selectHomeTransTax(Session::get('PropertyCode'),$AccCode,$AccSubCode,$curr, $from , $to,"Tax",$pfrom,$to,$tax);


                }
                else
                {
                    $myRateValidation=modelStatements::selectRate(Session::get('PropertyCode'),$curr,$AccCode,$AccSubCode, $from, $to);

                    if(count($myRateValidation)==0)
                    {
                        return redirect()->route('TaxReport')->withErrors(['error' => 'Cannot Run This Report With The Selected Currency' ]);
                    }
                    else
                    {
                    $trans=modelStatements::selectTransTax(Session::get('PropertyCode'),$AccCode,$AccSubCode,$curr, $from , $to,"Tax",$pfrom,$to,$tax);
                    }

                }

            }
            else
            {
                return redirect()->route('TaxReport')->withErrors(['error' => 'Home Currency Not Found' ]);

            }

            return view('/TaxReport', compact('trans','code','pfrom','pto','from','to','name','taxs','currnames','currencys'));



        }
                    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);
                        $toDate = Carbon::parse($request->to_date);

                        // **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
                        ]);
                    }
                    public function indexRent()
            {
                try {
                    // Initialize empty values to avoid "undefined variable" errors in the view
                    $summaryData = collect();
                    $detailedData = collect();
                    $fromDate = now()->format('Y-m-d');
                    $toDate = now()->format('Y-m-d');
                    $grandTotal = 0;

                    return view('Rentsummary', compact(
                        'summaryData',
                        'detailedData',
                        'fromDate',
                        'toDate',
                        'grandTotal'
                    ));
                } catch (\Exception $e) {
                    return redirect()->route('otheraccounts')->withErrors([
                        'error' => 'An error occurred!! ' . $e->getMessage()
                    ]);
                }
            }
            public function OutstandingRentReport(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);
                $toDate = Carbon::parse($request->to_date);

                // **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::fetchSummaryOutstandingData($fromDate, $toDate);


                    // Calculate the grand total for the summary data by summing the 'total' field
                   // Calculate the grand total as sum of (total - dr)
                    $grandTotal = $summaryData->reduce(function ($carry, $item) {
                        $total = $item->total ?? 0;
                        $dr = $item->dr ?? 0;
                        return $carry + ($total - $dr);
                    }, 0);
                } elseif ($request->report_type === 'detailed') {
                    // Fetch detailed data
                    $detailedData = Rentsum::fetchDetailedoutstandingData($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('Outstandingrent', [
                    '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
                ]);
            }
            public function indexRentoutstanding()
    {
        try {
            // Initialize empty values to avoid "undefined variable" errors in the view
            $summaryData = collect();
            $detailedData = collect();
            $fromDate = now()->format('Y-m-d');
            $toDate = now()->format('Y-m-d');
            $grandTotal = 0;

            return view('Outstandingrent', compact(
                'summaryData',
                'detailedData',
                'fromDate',
                'toDate',
                'grandTotal'
            ));
        } catch (\Exception $e) {
            return redirect()->route('otheraccounts')->withErrors([
                'error' => 'An error occurred!! ' . $e->getMessage()
            ]);
        }
    }
    public function RentCollectionReport(Request $request)
    {
        // Validate the input
        $request->validate([
            'from_date' => 'required|date',
            'to_date' => 'required|date',
            'curr' => 'required|integer'
        ]);

        $fromDate = Carbon::parse($request->from_date);
        $toDate = Carbon::parse($request->to_date);
        $curr = $request->curr;

        // Get currency name from the model
        $currname = modelStatements::selectcurrencyName(Session::get('PropertyCode'), $curr);
        $currnames = $currname[0]->Name ?? 'Unknown Currency';

        // Get filtered summary data from the model
        $summaryData = Rentsum::fetchSummaryCollectionData($fromDate, $toDate, $curr);

        // Calculate grand total as the sum of the 'dr' (amount paid)
        $grandTotal = $summaryData->reduce(function ($carry, $item) {
            $dr = $item->dr ?? 0;
            return $carry + $dr;
                }, 0);

        return view('Rentcollection', [
            'summaryData' => $summaryData,
            'fromDate' => $fromDate->format('Y-m-d'),
            'toDate' => $toDate->format('Y-m-d'),
            'grandTotal' => $grandTotal,
            'currnames' => $currnames,
            'currencys' => modelStatements::selectcurrency(Session::get('PropertyCode')) // to repopulate dropdown
        ]);
    }

          public function indexRentCollection()
            {
                try {
                    $currencys = modelStatements::selectcurrency(Session::get('PropertyCode'));

                    // Initialize empty values to avoid "undefined variable" errors in the view
                    $summaryData = collect();
                    $fromDate = now()->format('Y-m-d');
                    $toDate = now()->format('Y-m-d');
                    $grandTotal = 0;
                    $currnames = ''; // Important: Add this to avoid view errors

                    return view('Rentcollection', compact(
                        'summaryData',
                        'currencys',
                        'fromDate',
                        'toDate',
                        'grandTotal',
                        'currnames'
                    ));
                } catch (\Exception $e) {
                    return redirect()->route('otheraccounts')->withErrors([
                        'error' => 'An error occurred!! ' . $e->getMessage()
                    ]);
                }
            }
                    public function indexAgeAnalysis()
                    {
                        return view('AgeAnalysisReport');
                    }


            public function AgeAnalysisReport(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);
    $toDate = Carbon::parse($request->to_date);

    // Initialize data containers
    $reportData = [];
    $detailedData = collect();

    if ($request->report_type === 'summary') {
        // Fetch summary transactions
        $transactions = Rentsum::fetchAgeSummaryOutstandingData($fromDate, $toDate);

        foreach ($transactions as $transaction) {
            $tenantId = $transaction->tenantcode;
            $tenantName = $transaction->tenant_name;
            $entryDate = Carbon::parse($transaction->entrydate);
            $currentDate = $toDate;

            $daysOverdue = max(0, $entryDate->diffInDays($currentDate, false));
            $discountAmount = ($transaction->discount / 100) * $transaction->total;
            $taxAmount = ($transaction->tax / 100) * $transaction->total;

            // Match receipts by batch reference
            $matchedReceipts = DB::table('transactions')
                ->where('ttype', 'receipt')
                ->where('refference', $transaction->batch)
                ->sum('dr');

            // Calculate the final outstanding amount
            $amount = $transaction->total + $taxAmount - $discountAmount - $matchedReceipts;

            if ($amount <= 0) continue;

            // Initialize tenant's summary bucket
            if (!isset($reportData[$tenantId])) {
                $reportData[$tenantId] = [
                    'tenant' => $tenantName,
                    '180_days' => 0,
                    '150_days' => 0,
                    '120_days' => 0,
                    '90_days' => 0,
                    '60_days' => 0,
                    '30_days' => 0,
                    'current' => 0,
                    'balance' => 0,
                ];
            }

            // Bucket the amount based on overdue days
            if ($daysOverdue > 180) {
                $reportData[$tenantId]['180_days'] += $amount;
            } elseif ($daysOverdue > 150) {
                $reportData[$tenantId]['150_days'] += $amount;
            } elseif ($daysOverdue > 120) {
                $reportData[$tenantId]['120_days'] += $amount;
            } elseif ($daysOverdue > 90) {
                $reportData[$tenantId]['90_days'] += $amount;
            } elseif ($daysOverdue > 60) {
                $reportData[$tenantId]['60_days'] += $amount;
            } elseif ($daysOverdue > 30) {
                $reportData[$tenantId]['30_days'] += $amount;
            } else {
                $reportData[$tenantId]['current'] += $amount;
            }

            $reportData[$tenantId]['balance'] += $amount;
        }
    }

   if ($request->report_type === 'detailed') {

        $transactions = Rentsum::fetchAgeSummaryOutstandingData($fromDate, $toDate);

        foreach ($transactions as $transaction) {
            $tenantId = $transaction->tenantcode;
            $tenantName = $transaction->tenant_name;
            $tenantKey = $tenantId . ' ' . $tenantName;
            $entryDate = Carbon::parse($transaction->entrydate);
            $currentDate = $toDate;

            $daysOverdue = max(0, $entryDate->diffInDays($currentDate, false));
            $discountAmount = ($transaction->discount / 100) * $transaction->total;
            $taxAmount = ($transaction->tax / 100) * $transaction->total;

            $matchedReceipts = DB::table('transactions')
                ->where('ttype', 'receipt')
                ->where('refference', $transaction->batch)
                ->sum('dr');

            $amount = $transaction->total + $taxAmount - $discountAmount - $matchedReceipts;

            if ($amount <= 0) continue;

            // Initialize detailedData tenant bucket
            if (!isset($detailedData[$tenantKey])) {
                $detailedData[$tenantKey] = collect(); // Use Laravel Collection
            }

            // Push the transaction to the tenant's collection
            $detailedData[$tenantKey]->push((object)[
                'entrydate' => $transaction->entrydate,
                'batch' => $transaction->batch,
                'discount' => $transaction->discount,
                'total' => $transaction->total + $taxAmount, // include tax
                'dr' => $matchedReceipts,
            ]);
        }
    }

    // Return the view with report data
    return view('AgeAnalysisReport', [
        'reportData' => $reportData,
        'detailedData' => $detailedData,
        'from_date' => $fromDate->format('Y-m-d'),
        'to_date' => $toDate->format('Y-m-d'),
        'report_type' => $request->report_type,
    ]);
}


}
