<?php

namespace App\Http\Controllers\Reports;

use App\Http\Controllers\Controller;
use App\Models\ReceiptVoucher;
use App\Traits\Basics\HandlesJsonExceptions;
use App\Traits\Basics\HasCrudActions;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\View\View;
use Exception;

class RevenueReportController extends Controller
{
    use HasCrudActions, HandlesJsonExceptions;

    /** ==============* Properties *============== */
    protected string $model = ReceiptVoucher::class;
    protected string $viewPath = 'reports.revenues.';

    /** ==============* Index & View *============== */
    public function index(): View
    {
        return view("{$this->viewPath}.index");
    }

    public function filter(Request $request)
    {
        try {

            $query = $this->model::with(['customer', 'paymentMethod'])->where('status', 'active');

            if ($request->filled('from_date')) {
                $query->whereDate('payment_date', '>=', $request->from_date);
            }

            if ($request->filled('to_date')) {
                $query->whereDate('payment_date', '<=', $request->to_date);
            }

            if ($request->filled('payment_method_id')) {
                $query->where('payment_method_id', $request->payment_method_id);
            }

            if ($request->filled('user_id')) {
                $query->where('created_by', $request->user_id);
            }

            $vouchers = $query->latest('payment_date')->get();

            $summary = [
                'total_amount' => $vouchers->sum('amount'),
                'count' => $vouchers->count(),
                'by_method' => $vouchers->groupBy('paymentMethod.name_ar')
                    ->map(function($group) {
                        return [
                            'count' => $group->count(),
                            'amount' => $group->sum('amount')
                        ];
                    })
            ];

            return view("{$this->viewPath}.index", [
                'summary' => $summary,
                'vouchers' => $vouchers,
                'request' => $request->all(),
            ]);
        } catch (Exception $e) {
            DB::rollBack();
            return redirect()->back()->withErrors(["error" => $e->getMessage()]);
        }
    }
}
