<?php

namespace Modules\ClinicLab\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\ClinicLab\Entities\CllOutreachOrder;
use Modules\ClinicLab\Entities\CllOutreachProvider;
use Modules\ClinicLab\Entities\CllSpecimen;
use Modules\ClinicLab\Entities\CllTestCatalog;
use Modules\ClinicLab\Entities\Services\SpecimenService;

/**
 * Outreach: external providers CRUD + external-sample intake — /clinic-lab/outreach.
 * Permission-gated on cliniclab.outreach.manage. business_id scoped.
 */
class CllOutreachController extends Controller
{
    protected function guard(): void
    {
        if (! auth()->user() || ! auth()->user()->can('cliniclab.outreach.manage')) {
            abort(403, 'Unauthorized action.');
        }
    }

    protected function bizId()
    {
        return request()->session()->get('user.business_id');
    }

    // ── Providers ──────────────────────────────────────────────────────────
    public function index()
    {
        $this->guard();
        $providers = CllOutreachProvider::forBusiness($this->bizId())
            ->withCount('orders')->orderBy('name')->get();
        $orders = CllOutreachOrder::forBusiness($this->bizId())
            ->with(['provider', 'specimen', 'catalog'])
            ->orderByDesc('id')->limit(100)->get();
        return view('clinicLab::outreach.index', compact('providers', 'orders'));
    }

    public function storeProvider(Request $request)
    {
        $this->guard();
        $data = $request->validate([
            'name'             => 'required|string|max:150',
            'contact_person'   => 'nullable|string|max:120',
            'phone'            => 'nullable|string|max:40',
            'email'            => 'nullable|email|max:120',
            'address'          => 'nullable|string|max:255',
            'price_group_note' => 'nullable|string|max:255',
            'is_active'        => 'nullable|boolean',
        ]);
        $data['business_id'] = $this->bizId();
        $data['is_active'] = $request->boolean('is_active', true);
        CllOutreachProvider::create($data);
        return back()->with('status', ['success' => 1, 'msg' => 'Outreach provider added.']);
    }

    public function updateProvider($id, Request $request)
    {
        $this->guard();
        $provider = CllOutreachProvider::forBusiness($this->bizId())->findOrFail($id);
        $data = $request->validate([
            'name'             => 'required|string|max:150',
            'contact_person'   => 'nullable|string|max:120',
            'phone'            => 'nullable|string|max:40',
            'email'            => 'nullable|email|max:120',
            'address'          => 'nullable|string|max:255',
            'price_group_note' => 'nullable|string|max:255',
            'is_active'        => 'nullable|boolean',
        ]);
        $data['is_active'] = $request->boolean('is_active');
        $provider->update($data);
        return back()->with('status', ['success' => 1, 'msg' => 'Provider updated.']);
    }

    public function destroyProvider($id)
    {
        $this->guard();
        CllOutreachProvider::forBusiness($this->bizId())->findOrFail($id)->delete();
        return back()->with('status', ['success' => 1, 'msg' => 'Provider removed.']);
    }

    // ── Outreach order intake ──────────────────────────────────────────────
    public function storeOrder(Request $request, SpecimenService $service)
    {
        $this->guard();
        $data = $request->validate([
            'provider_id'  => 'required|integer',
            'patient_name' => 'required|string|max:150',
            'catalog_id'   => 'nullable|integer',
        ]);

        $provider = CllOutreachProvider::forBusiness($this->bizId())->findOrFail($data['provider_id']);

        // Log the external sample through the SAME specimen flow.
        $specimen = CllSpecimen::create([
            'business_id'  => $this->bizId(),
            'specimen_no'  => $service->nextSpecimenNo((int) $this->bizId()),
            'catalog_id'   => $data['catalog_id'] ?? null,
            'specimen_type' => 'blood',
            'status'       => 'received',
            'received_at'  => now(),
            'received_by'  => auth()->id(),
        ]);

        CllOutreachOrder::create([
            'business_id'  => $this->bizId(),
            'provider_id'  => $provider->id,
            'patient_name' => $data['patient_name'],
            'specimen_id'  => $specimen->id,
            'catalog_id'   => $data['catalog_id'] ?? null,
            'status'       => 'received',
            'received_at'  => now(),
        ]);

        return back()->with('status', ['success' => 1, 'msg' => 'Outreach sample logged (specimen ' . $specimen->specimen_no . ').']);
    }

    public function markDelivered($id, Request $request)
    {
        $this->guard();
        $data = $request->validate([
            'delivery_channel' => 'required|in:portal,email,print,whatsapp',
        ]);
        $order = CllOutreachOrder::forBusiness($this->bizId())->findOrFail($id);
        $order->update([
            'status'           => 'delivered',
            'reported_at'      => $order->reported_at ?: now(),
            'delivery_channel' => $data['delivery_channel'],
        ]);
        return back()->with('status', ['success' => 1, 'msg' => 'Marked delivered.']);
    }
}
