<?php

namespace Modules\MedDocuments\Http\Controllers;

use Illuminate\Http\Request;
use Modules\MedDocuments\Entities\MeddocType;
use Yajra\DataTables\Facades\DataTables;

/**
 * Doc-type taxonomy CRUD. System types (business_id NULL) are read-only — they
 * appear in the list but cannot be edited or deleted; a tenant can only manage
 * its own custom types.
 */
class DocTypeController extends MedDocBaseController
{
    public function index()
    {
        $this->guard('meddoc.manage_types');

        return view('meddocuments::types.index');
    }

    public function data(Request $request)
    {
        $this->guard('meddoc.manage_types');

        $q = MeddocType::forBusiness($this->businessId())
            ->select(['id', 'business_id', 'type_key', 'label', 'description', 'retention_days', 'requires_signature', 'is_active']);

        return DataTables::of($q)
            ->addColumn('scope', fn ($t) => $t->business_id === null
                ? '<span class="label label-primary">' . __('meddocuments::lang.system') . '</span>'
                : '<span class="label label-default">' . __('meddocuments::lang.custom') . '</span>')
            ->editColumn('requires_signature', fn ($t) => $t->requires_signature ? '<i class="fa fa-check text-success"></i>' : '—')
            ->editColumn('retention_days', fn ($t) => $t->retention_days ?: '—')
            ->editColumn('is_active', fn ($t) => $t->is_active
                ? '<span class="label label-success">' . __('meddocuments::lang.active') . '</span>'
                : '<span class="label label-default">' . __('meddocuments::lang.inactive') . '</span>')
            ->addColumn('action', function ($t) {
                if ($t->business_id === null) {
                    return '<span class="text-muted"><i class="fa fa-lock"></i> ' . __('meddocuments::lang.read_only') . '</span>';
                }

                return '<button data-href="' . route('meddoc.types.edit', $t->id) . '" class="btn btn-xs btn-primary meddoc-modal-btn"><i class="fa fa-edit"></i></button> '
                    . '<button data-href="' . route('meddoc.types.destroy', $t->id) . '" class="btn btn-xs btn-danger meddoc-delete"><i class="fa fa-trash"></i></button>';
            })
            ->rawColumns(['scope', 'requires_signature', 'is_active', 'action'])
            ->make(true);
    }

    public function create()
    {
        $this->guard('meddoc.manage_types');

        return view('meddocuments::types.create');
    }

    public function store(Request $request)
    {
        $this->guard('meddoc.manage_types');

        $data = $this->rules($request);

        try {
            $data['business_id'] = $this->businessId();
            $data['type_key'] = $this->keyFor($request, $data);
            $data['requires_signature'] = $request->boolean('requires_signature');
            $data['is_active'] = $request->boolean('is_active', true);
            MeddocType::create($data);

            return $this->ok(__('meddocuments::lang.added_success'));
        } catch (\Exception $e) {
            \Log::emergency($e->getMessage());

            return $this->fail();
        }
    }

    public function edit($id)
    {
        $this->guard('meddoc.manage_types');
        $type = $this->findCustom($id);

        return view('meddocuments::types.edit', compact('type'));
    }

    public function update(Request $request, $id)
    {
        $this->guard('meddoc.manage_types');
        $data = $this->rules($request);

        try {
            $type = $this->findCustom($id);
            $data['requires_signature'] = $request->boolean('requires_signature');
            $data['is_active'] = $request->boolean('is_active', true);
            // type_key stays stable after creation.
            unset($data['type_key']);
            $type->update($data);

            return $this->ok(__('meddocuments::lang.updated_success'));
        } catch (\Exception $e) {
            \Log::emergency($e->getMessage());

            return $this->fail();
        }
    }

    public function destroy($id)
    {
        $this->guard('meddoc.manage_types');

        try {
            $type = $this->findCustom($id);

            if ($type->documents()->exists()) {
                return $this->fail(__('meddocuments::lang.type_in_use'));
            }

            $type->delete();

            return $this->ok(__('meddocuments::lang.deleted_success'));
        } catch (\Exception $e) {
            return $this->fail();
        }
    }

    /*
    |--------------------------------------------------------------------------
    | Internals
    |--------------------------------------------------------------------------
    */

    /** Only a tenant's own (non-system) types are editable. */
    protected function findCustom($id): MeddocType
    {
        return MeddocType::where('business_id', $this->businessId())->findOrFail($id);
    }

    protected function rules(Request $request): array
    {
        return $this->validate($request, [
            'label'          => 'required|string|max:191',
            'type_key'       => 'nullable|string|max:100|regex:/^[a-z0-9_]+$/',
            'description'    => 'nullable|string|max:1000',
            'retention_days' => 'nullable|integer|min:1',
        ]);
    }

    protected function keyFor(Request $request, array $data): string
    {
        $key = $data['type_key'] ?? null;
        if (! empty($key)) {
            return $key;
        }

        return \Illuminate\Support\Str::slug($data['label'], '_');
    }
}
