<?php

namespace Modules\ClinicCore\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\ClinicCore\Entities\ClcVaccineType;
use Yajra\DataTables\Facades\DataTables;

class ClcVaccineTypeController extends Controller
{
    use \Modules\ClinicCore\Http\Controllers\Traits\LogsClcActivity;

    public function index()
    {
        if (!auth()->user()->can('clinic.access_settings')) {
            abort(403, 'Unauthorized action.');
        }

        return view('clinicCore::vaccine-types.index');
    }

    public function list(Request $request)
    {
        if (!auth()->user()->can('clinic.access_settings')) {
            abort(403, 'Unauthorized action.');
        }

        $businessId = request()->session()->get('user.business_id');
        $query = ClcVaccineType::forBusiness($businessId)->orderBy('name');

        $categoryLabels = [
            'core_vaccine'     => 'Core Vaccine',
            'non_core_vaccine' => 'Non-Core Vaccine',
            'spot_on'          => 'Spot-on',
            'deworming'        => 'Deworming',
            'oral'             => 'Oral',
            'nasal'            => 'Nasal',
            'topical'          => 'Topical',
            'preventive'       => 'Preventive',
            'other'            => 'Other',
        ];
        $categoryColors = [
            'core_vaccine'     => 'primary',
            'non_core_vaccine' => 'info',
            'spot_on'          => 'warning',
            'deworming'        => 'success',
            'oral'             => 'default',
            'nasal'            => 'default',
            'topical'          => 'default',
            'preventive'       => 'info',
            'other'            => 'default',
        ];

        return DataTables::of($query)
            ->addColumn('species_list', function ($row) {
                if (!$row->species_target) return '<span class="text-muted">All</span>';
                return implode(', ', array_map('ucfirst', $row->species_target));
            })
            ->addColumn('category_badge', function ($row) use ($categoryLabels, $categoryColors) {
                if (!isset($row->category)) return '—';
                $cat = $row->category ?? 'core_vaccine';
                $color = $categoryColors[$cat] ?? 'default';
                return '<span class="label label-' . $color . '">' . ($categoryLabels[$cat] ?? $cat) . '</span>';
            })
            ->addColumn('status_badge', function ($row) {
                $color = $row->status === 'active' ? 'success' : 'danger';
                return '<span class="label label-' . $color . '">' . ucfirst($row->status) . '</span>';
            })
            ->addColumn('system_badge', function ($row) {
                return is_null($row->business_id)
                    ? '<span class="label label-info">System</span>'
                    : '<span class="label label-default">Custom</span>';
            })
            ->addColumn('product_badge', function ($row) {
                if (!empty($row->product_id)) {
                    return '<span class="label label-success" title="Linked to ERP product (POS pricing enabled)"><i class="fa fa-link"></i> Linked</span>';
                }
                return '<span class="label label-warning" title="No ERP product linked — won\'t auto-bill in POS"><i class="fa fa-chain-broken"></i> Not linked</span>';
            })
            ->addColumn('action', function ($row) {
                if (is_null($row->business_id)) {
                    return '<span class="text-muted" style="font-size:11px;">System default</span>';
                }
                $edit = '<button class="btn btn-xs btn-primary btn-edit-vt" data-id="' . $row->id . '"><i class="fa fa-edit"></i></button> ';
                $del  = '<button class="btn btn-xs btn-danger btn-delete-vt" data-id="' . $row->id . '"><i class="fa fa-trash"></i></button>';
                return $edit . $del;
            })
            ->rawColumns(['action', 'status_badge', 'system_badge', 'category_badge', 'species_list', 'product_badge'])
            ->make(true);
    }

    public function store(Request $request)
    {
        if (!auth()->user()->can('clinic.access_settings')) {
            abort(403, 'Unauthorized action.');
        }

        $request->validate(['name' => 'required|string|max:150', 'valid_for_months' => 'required|integer|min:1']);
        $businessId = request()->session()->get('user.business_id');

        $vt = ClcVaccineType::create([
            'business_id'      => $businessId,
            'name'             => $request->name,
            'manufacturer'     => $request->manufacturer,
            'category'         => $request->category ?? 'core_vaccine',
            'species_target'   => $request->species_target ? array_filter($request->species_target) : null,
            'description'      => $request->description,
            'valid_for_months' => $request->valid_for_months,
            'status'           => $request->status ?? 'active',
            'product_id'       => $request->filled('product_id') ? (int) $request->product_id : null,
        ]);
        $this->drmLog('create', $vt);

        return response()->json(['success' => true, 'msg' => __('clinicCore::lang.saved_successfully')]);
    }

    public function edit($id)
    {
        $businessId = request()->session()->get('user.business_id');
        $vt = ClcVaccineType::where('business_id', $businessId)->findOrFail($id);
        return response()->json($vt);
    }

    public function update(Request $request, $id)
    {
        if (!auth()->user()->can('clinic.access_settings')) {
            abort(403, 'Unauthorized action.');
        }

        $request->validate(['name' => 'required|string|max:150', 'valid_for_months' => 'required|integer|min:1']);
        $businessId = request()->session()->get('user.business_id');
        $vt = ClcVaccineType::where('business_id', $businessId)->findOrFail($id);
        $original = $vt->getOriginal();
        $vt->update([
            'name'             => $request->name,
            'manufacturer'     => $request->manufacturer,
            'category'         => $request->category ?? 'core_vaccine',
            'species_target'   => $request->species_target ? array_filter($request->species_target) : null,
            'description'      => $request->description,
            'valid_for_months' => $request->valid_for_months,
            'status'           => $request->status ?? 'active',
            'product_id'       => $request->filled('product_id') ? (int) $request->product_id : null,
        ]);
        $dirty = array_keys($vt->getChanges());
        if ($dirty) {
            $this->drmLog('update', $vt, [
                'before' => array_intersect_key($original, array_flip($dirty)),
                'after'  => array_intersect_key($vt->getAttributes(), array_flip($dirty)),
                'fields' => $dirty,
            ]);
        }

        return response()->json(['success' => true, 'msg' => __('clinicCore::lang.updated_successfully')]);
    }

    public function destroy($id)
    {
        if (!auth()->user()->can('clinic.access_settings')) {
            abort(403, 'Unauthorized action.');
        }

        $businessId = request()->session()->get('user.business_id');
        $vt = ClcVaccineType::where('business_id', $businessId)->findOrFail($id);
        $this->drmLog('delete', $vt, ['before' => $this->_drmFilterAttrs($vt->getAttributes())]);
        $vt->delete();

        return response()->json(['success' => true, 'msg' => __('clinicCore::lang.deleted_successfully')]);
    }
}
