<?php

namespace App\Http\Controllers;

use App\Models\Investor;
use App\Models\Investment;
use App\Models\Car;

use Illuminate\Http\Request;

class InvestorController extends Controller
{
    // Show all investors
    public function index()
    {
        $investors = Investor::with('investments')->get();
        // Fetch all active cars
        $cars = Car::where('status', 1)->get();
    
        return view('investors.index', compact('investors', 'cars')); // ✅ Include cars
    }
    


    // Store new investor
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'father_name' => 'required|string|max:255',
            'cnic' => 'required|string|max:20|unique:investors,cnic',
            'address' => 'nullable|string',
        ]);

        Investor::create($request->all());

        return back()->with('success', 'Investor added successfully.');
    }

    // Add Investment (IN/OUT/CAR)
    public function addInvestment(Request $request, Investor $investor)
    {
        $request->validate([
            'type' => 'required|in:in,out,car', // ✅ Added 'car'
            'amount' => 'required|numeric|min:1',
            'date' => 'required|date',
            'remarks' => 'nullable|string',
            'car_id' => 'nullable|exists:cars,id',
        ]);
    
        $investor->investments()->create($request->all());
    
        return back()->with('success', 'Investment recorded successfully.');
    }
    
    

// Investor statement
public function statement($investorId, Request $request)
{
    $investor = Investor::findOrFail($investorId);

    $from = $request->input('from');
    $to = $request->input('to');

    $query = Investment::where('investor_id', $investorId);

    if ($from && $to) {
        // Convert month (YYYY-MM) to full date range
        $fromDate = \Carbon\Carbon::parse($from . '-01')->startOfMonth();
        $toDate = \Carbon\Carbon::parse($to . '-01')->endOfMonth();

        $query->whereBetween('date', [$fromDate, $toDate]);
    }

    $investments = $query->orderBy('date', 'asc')->get();

    $totalIn = $investments->where('type', 'in')->sum('amount');
    $totalOut = $investments->where('type', 'out')->sum('amount');
    $totalpurchase = $investments->where('type', 'car')->sum('amount');
    $balance = $totalIn - $totalOut - $totalpurchase;

    return view('investors.statement', compact(
        'investor', 'investments', 'totalIn', 'totalOut', 'totalpurchase', 'balance', 'from', 'to'
    ));
}



    
    
    
}
