<?php

namespace Modules\MedBloodBank\Http\Controllers;

use Illuminate\Http\Request;
use Modules\MedBloodBank\Services\BloodBankService;

/**
 * Stock dashboard (SIFA P6-T6): the group × product_type available-stock grid
 * with min-stock alert thresholds, the 7/15/30-day expiring-soon ladder, an
 * on-demand expiry sweep and a low-stock notify trigger.
 */
class DashboardController extends MedBloodBankBaseController
{
    public function __construct(private BloodBankService $service)
    {
    }

    /** Anyone with any mbb.* permission may view the dashboard. */
    private function guardAny(): void
    {
        $u = auth()->user();
        if (! ($u->can('mbb.donors.manage') || $u->can('mbb.donations.manage')
            || $u->can('mbb.screening.result') || $u->can('mbb.crossmatch.perform')
            || $u->can('mbb.issue.manage'))) {
            abort(403, 'Unauthorized action.');
        }
    }

    public function index()
    {
        $this->guardAny();

        $businessId = $this->businessId();
        $ladder = config('medbloodbank.expiry_ladder_days', [7, 15, 30]);

        return view('medbloodbank::dashboard.index', [
            'stock'        => $this->service->stockGrid($businessId),
            'expiringSoon' => $this->service->expiringSoon($businessId),
            'ladder'       => $ladder,
            'today'        => now()->startOfDay(),
        ]);
    }

    /** Run the expiry sweep on demand (mbb.donations.manage). */
    public function sweep(Request $request)
    {
        $this->guard('mbb.donations.manage');

        try {
            $count = $this->service->expireBags($this->businessId());

            return $this->ok(__('medbloodbank::lang.expiry_swept', ['count' => $count]));
        } catch (\Exception $e) {
            \Log::emergency($e->getMessage());

            return $this->fail();
        }
    }

    /** Fire the low-stock MedNotify event on demand (fail-soft). */
    public function notifyLow(Request $request)
    {
        $this->guard('mbb.donations.manage');

        try {
            $low = $this->service->notifyLowStock($this->businessId());

            return $this->ok(
                empty($low)
                    ? __('medbloodbank::lang.no_low_stock')
                    : __('medbloodbank::lang.low_stock_notified', ['groups' => implode(', ', $low)])
            );
        } catch (\Exception $e) {
            \Log::emergency($e->getMessage());

            return $this->fail();
        }
    }
}
