<?php

namespace App\Http\Controllers\Api\Reports;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Transaction;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class VendorReportController extends Controller
{
    public function vendorBalanceReport(Request $request)
    {
        try {
            // Validate the request
            $validator=validator($request->all(),[
                'vendor_id'=>'required'
            ]);
    
            //Inout 1 = payment rec , 2= payment made
    
            if ($validator->fails()) { 
                return [
                    'success' => false, 
                    'message' => $validator->errors()->first()
                ];
            } 

            // Get the date range from the request, or set default to the last 1 month
            $endDate = $request->input('end_date') ?: Carbon::today()->format('Y-m-d');
            $startDate = $request->input('start_date') ?: Carbon::today()->startOfMonth()->format('Y-m-d') ;

            $vendor_id = $request->vendor_id;
            $vendor=User::find($vendor_id);

            // Fetch all transactions for the vendor
            $transactions = Transaction::where('vendor_id', $vendor_id)
                ->with('account:id,account_name,account_code')
                ->whereBetween('transaction_date', [$startDate, $endDate])
                ->select('transaction_date', 'transaction_id', 'account_id', 'entity_type', 'debit', 'credit')
                ->orderBy('transaction_date', 'asc')
                ->get();

            // Calculate total debit and credit
            $total_debit = $transactions->sum('debit');
            $total_credit = $transactions->sum('credit');

            // Calculate outstanding balance (debit - credit)
            $outstanding_balance = $total_debit - $total_credit;

            return response()->json([
                'success'   => true,
                'message'   => 'Vendor balance report retrieved successfully',
                'startDate'=>$startDate,
                'endDate'=>$endDate,
                'total_debit' => $total_debit,
                'total_credit' => $total_credit,
                'outstanding_balance' => $outstanding_balance,
                'user' => $vendor,
                'transactions' => $transactions
            ], 200);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'An unexpected error occurred',
                'error'   => $e->getMessage(),
                'data'    => null
            ], 500);
        }
    }

}
