<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Cotizacion;
use Barryvdh\DomPDF\Facade\Pdf;

class ReportController extends Controller
{
    public function sales(Request $request)
    {
        $from = $request->from ?? now()->startOfMonth()->format('Y-m-d');
        $to   = $request->to ?? now()->format('Y-m-d');

        $query = Cotizacion::with('cliente')
            ->whereBetween('created_at', [$from.' 00:00:00', $to.' 23:59:59']);

        $cotizaciones = $query->get();

        $totalSales = $cotizaciones->sum('total');
        $totalPaid = $cotizaciones->where('estado','aprobada')->sum('total');
        $totalDue = $totalSales - $totalPaid;
        $totalCount = $cotizaciones->count();

        return view('reports.sales', compact(
            'cotizaciones',
            'from',
            'to',
            'totalSales',
            'totalPaid',
            'totalDue',
            'totalCount'
        ));
    }

    public function salesPdf(Request $request)
    {
        $from = $request->from;
        $to = $request->to;

        $cotizaciones = Cotizacion::with('cliente')
            ->whereBetween('created_at', [$from.' 00:00:00', $to.' 23:59:59'])
            ->get();

        $totalSales = $cotizaciones->sum('total');

        $pdf = Pdf::loadView('reports.sales_pdf', compact('cotizaciones','from','to','totalSales'));

        return $pdf->download('Sales_Report.pdf');
    }
}