<?php

// app/Http/Controllers/ExpenseController.php

namespace App\Http\Controllers;

use App\Models\Expense;
use App\Models\ExpenseHead;
use Illuminate\Http\Request;

use App\Models\Car;
use App\Models\Customer;
use App\Models\sale;
use App\Models\CarLabReport;
use App\Models\Commission;

class ExpenseController extends Controller {
    // public function index() {
    //     $expenses = Expense::with('head')->latest()->paginate(10);
    //     $heads = ExpenseHead::all();

    //             // Fetch data from the database
    //     $totalCars = Car::where('status', 1)->count();
    //     // $totalreports = Car::whereIn('status', [1, 2] )->count();
    //     $totalreports = Car::count();
    //     $totalCustomers = Customer::count();
    //     $totalsold = Sale::where('status', 1)->count();
    //     $totalSales = Sale::where('status', 1)->sum('soled_price'); 
    //     $totalreceived = Sale::where('status', 1)->sum('received_amount');
    //     $totalremainings = Sale::where('status', 1)->sum('remaining_payment');
    //     $totalReports = CarLabReport::count(); // Assuming lab reports exist

    //     $totalexpense = Expense::sum('amount');

    //     $buyerCommission = Commission::sum('buyer_commission');
    //     $selerCommission = Commission::sum('seller_commission');
    //     $totalCommission = $buyerCommission + $selerCommission;
    //     $totalProfit = $totalCommission - $totalexpense;



    //     $recentActivities = [
    //         ['text' => 'New car added', 'created_at' => now()->subMinutes()],
    //         ['text' => 'Customer registered', 'created_at' => now()->subHours()],
    //         ['text' => 'New sale recorded', 'created_at' => now()->subDays()],
    //     ];

    //     return view('expenses.index', compact('totalProfit','totalCommission','totalexpense','expenses', 'heads','totalCars', 'totalreports', 'totalsold', 'totalSales', 'totalreceived', 'totalremainings', 'totalCustomers', 'recentActivities'));
    // }


// app/Http/Controllers/ExpenseController.php

public function index(Request $request)
{
    $query = Expense::with('head');

    // Filters
    if ($request->filled('expense_head_id')) {
        $query->where('expense_head_id', $request->expense_head_id);
    }
    if ($request->filled('paid_by')) {
        $query->where('paid_by', $request->paid_by);
    }
    if ($request->filled('from_date')) {
        $query->whereDate('date', '>=', $request->from_date);
    }
    if ($request->filled('to_date')) {
        $query->whereDate('date', '<=', $request->to_date);
    }

    // Clone BEFORE paginate to compute filtered total across all matching rows
    $filteredTotal = (clone $query)->sum('amount');

    $expenses = $query->latest('date')->paginate(100);
    $heads = ExpenseHead::all();


 
    // ---- Dashboard stats (unchanged names) ----
    // $totalCars       = Car::where('status', 1)->count();
    // $totalreports    = Car::count();
    // $totalCustomers  = Customer::count();
    // $totalsold       = Sale::where('status', 1)->count();
    // $totalSales      = Sale::where('status', 1)->sum('soled_price'); 
    // $totalreceived   = Sale::where('status', 1)->sum('received_amount');
    // $totalremainings = Sale::where('status', 1)->sum('remaining_payment');
    // $totalexpense    = Expense::sum('amount'); // <-- keep this exact var name for your cards

    // $buyerCommission  = Commission::sum('buyer_commission');
    // $sellerCommission = Commission::sum('seller_commission');
    // $totalCommission  = $buyerCommission + $sellerCommission;
    // $totalProfit      = $totalCommission - $totalexpense;
   // <-- for table footer
    return view('expenses.index', compact('expenses', 'heads', 'filteredTotal'
        // 'totalexpense',       // <-- for dashboard card
        // 'totalProfit','totalCommission',
        // 'totalCars','totalreports','totalsold','totalSales',
        // 'totalreceived','totalremainings','totalCustomers'
        ));
}


    public function store(Request $request) {
        $request->validate([
            'expense_head_id' => 'required|exists:expense_heads,id',
            'details' => 'nullable|string',
            'amount' => 'required|numeric|min:0',
            'date' => 'required|date',
            'paid_by' => 'required|string|max:255',
        ]);
    
        Expense::create($request->all());
    
        return back()->with('success', 'Expense added successfully.');
    }


    public function edit($id)
    {
        $editExpense = Expense::findOrFail($id);
        $heads = ExpenseHead::all();
        $expenses = Expense::with('head')->latest()->paginate(20);

        $filteredTotal = $expenses->sum('amount');

        return view('expenses.index', compact('editExpense', 'heads', 'expenses', 'filteredTotal'));
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'expense_head_id' => 'required|exists:expense_heads,id',
            'details' => 'nullable|string',
            'amount' => 'required|numeric|min:0',
            'date' => 'required|date',
            'paid_by' => 'required|string|max:255',
        ]);
    
        $expense = Expense::findOrFail($id);
        $expense->update($request->all());
    
        return redirect()->route('expenses.index')->with('success', 'Expense updated successfully!');
    }    
    

    public function destroy(Expense $expense) {
        $expense->delete();
        return back()->with('success', 'Expense deleted successfully.');
    }
}
