<?php
namespace App\Http\Controllers;
use App\Models\CustomerReceipt; use App\Models\DailyClosing; use App\Models\Expense; use App\Models\Sale; use App\Models\SupplierPayment; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth;
class DailyClosingController extends Controller {
 public function index(){ $closings=DailyClosing::latest('closing_date')->paginate(20); return view('daily_closing.index',compact('closings')); }
 public function create(Request $request){
  $date=$request->date ?? now()->toDateString();
  $previous=DailyClosing::where('closing_date','<',$date)->latest('closing_date')->first();
  $opening=$previous?->actual_cash ?? 0;
  $cashSales=Sale::whereDate('sale_date',$date)->sum('paid_amount');
  $creditSales=Sale::whereDate('sale_date',$date)->sum('due_amount');
  $receipts=CustomerReceipt::whereDate('receipt_date',$date)->sum('amount');
  $supplierPayments=SupplierPayment::whereDate('payment_date',$date)->sum('amount');
  $expenses=Expense::whereDate('expense_date',$date)->sum('amount');
  $expected=$opening+$cashSales+$receipts-$supplierPayments-$expenses;
  return view('daily_closing.create',compact('date','opening','cashSales','creditSales','receipts','supplierPayments','expenses','expected'));
 }
 public function store(Request $request){
  $data=$request->validate(['closing_date'=>'required|date|unique:daily_closings,closing_date','opening_cash'=>'required|numeric','cash_sales'=>'required|numeric','credit_sales'=>'required|numeric','customer_receipts'=>'required|numeric','supplier_payments'=>'required|numeric','expenses'=>'required|numeric','expected_cash'=>'required|numeric','actual_cash'=>'required|numeric','notes'=>'nullable']);
  $data['difference']=$data['actual_cash']-$data['expected_cash']; $data['status']='closed'; $data['user_id']=Auth::id(); DailyClosing::create($data);
  return redirect()->route('daily-closing.index')->with('success','Daily closing saved.');
 }
}
