<?php

namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use App\Models\DocumentHeader;
use App\Models\SupplierDocumentHeader;
use Illuminate\Http\Request;
use Carbon\Carbon;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
  public function index()
{
    $currentMonth = now()->month;
    $currentYear = now()->year;

    // Total Sales Invoice Amount for Current Month
    $monthlySalesInvoicesTotal = DocumentHeader::where('type', 'invoice')
        ->whereYear('document_date', $currentYear)
        ->whereMonth('document_date', $currentMonth)
        ->sum('inclusive_total');

    // Total Sales Receipts for Current Month
    $monthlySalesReceiptsTotal = DocumentHeader::where('type', 'receipt')
        ->whereYear('document_date', $currentYear)
        ->whereMonth('document_date', $currentMonth)
        ->sum('inclusive_total');

    // Outstanding = Invoices - Receipts
    $monthlyOutstanding = $monthlySalesInvoicesTotal - $monthlySalesReceiptsTotal;

        // Monthly Expenses from Supplier documents
    $monthlyExpensesTotal = SupplierDocumentHeader::where('type', 'sales_invoice')
        ->whereYear('created_at', $currentYear)
        ->whereMonth('created_at', $currentMonth)
        ->sum('inclusive_total');

    // ------------------------
    // Daily receipts for current month (for chart)
    $daysInMonth = Carbon::now()->daysInMonth;
    $dailyReceipts = [];

    for ($day = 1; $day <= $daysInMonth; $day++) {
        $date = Carbon::createFromDate($currentYear, $currentMonth, $day);
        $total = DocumentHeader::where('type', 'receipt')
            ->whereDate('document_date', $date)
            ->sum('inclusive_total');
        $dailyReceipts[] = $total;
    }

    return view('home', compact(
        'monthlySalesInvoicesTotal',
        'monthlySalesReceiptsTotal',
        'monthlyOutstanding',
        'monthlyExpensesTotal',
        'dailyReceipts'
    ));
}
}
