<?php

namespace Modules\VetClinic\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Str;
use Modules\VetClinic\Entities\VcConsentTemplate;
use Yajra\DataTables\Facades\DataTables;

/**
 * Manages the catalogue of consent form templates (VetClinic settings).
 * System templates (business_id NULL) are read-only — a clinic clones one to
 * get an editable copy that keeps the same code so it shadows the original.
 */
class VcConsentTemplateController extends Controller
{
    use \Modules\VetClinic\Http\Controllers\Traits\LogsVcActivity;

    private function guard(): void
    {
        if (!auth()->user()->can('vet_clinic.access_settings')) {
            abort(403, 'Unauthorized action.');
        }
    }

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

        return view('vetClinic::consent-templates.index', [
            'categories' => VcConsentTemplate::categories(),
            'variables'  => VcConsentTemplate::availableVariables(),
        ]);
    }

    public function list(Request $request)
    {
        $this->guard();

        $businessId = $request->session()->get('user.business_id');
        $query = VcConsentTemplate::forBusiness($businessId)
            ->orderBy('category')->orderBy('sort_order')->orderBy('name_en');

        $categories = VcConsentTemplate::categories();

        return DataTables::of($query)
            ->addColumn('category_badge', function ($row) use ($categories) {
                $color = VcConsentTemplate::categoryColor($row->category);
                $label = $categories[$row->category] ?? $row->category;
                return '<span class="label label-' . $color . '">' . e($label) . '</span>';
            })
            ->addColumn('name_cell', function ($row) {
                $html = '<strong>' . e($row->name_en) . '</strong>';
                if ($row->name_ar) {
                    $html .= '<br><span class="text-muted" dir="rtl" style="font-size:12px;">' . e($row->name_ar) . '</span>';
                }
                if ($row->requires_witness) {
                    $html .= ' <span class="label label-warning" style="font-size:9px;"><i class="fa fa-user-check"></i> Witness</span>';
                }
                return $html;
            })
            ->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('status_badge', function ($row) {
                $color = $row->status === 'active' ? 'success' : 'danger';
                return '<span class="label label-' . $color . '">' . ucfirst($row->status) . '</span>';
            })
            ->addColumn('action', function ($row) {
                if (is_null($row->business_id)) {
                    return '<button class="btn btn-xs btn-default btn-view-ct" data-id="' . $row->id . '"><i class="fa fa-eye"></i> View</button> '
                         . '<button class="btn btn-xs btn-primary btn-clone-ct" data-id="' . $row->id . '"><i class="fa fa-copy"></i> Clone to edit</button>';
                }
                return '<button class="btn btn-xs btn-primary btn-edit-ct" data-id="' . $row->id . '"><i class="fa fa-edit"></i></button> '
                     . '<button class="btn btn-xs btn-danger btn-delete-ct" data-id="' . $row->id . '"><i class="fa fa-trash"></i></button>';
            })
            ->rawColumns(['category_badge', 'name_cell', 'system_badge', 'status_badge', 'action'])
            ->make(true);
    }

    public function edit(Request $request, $id)
    {
        $this->guard();

        $businessId = $request->session()->get('user.business_id');
        $tpl = VcConsentTemplate::forBusiness($businessId)->findOrFail($id);

        return response()->json($tpl);
    }

    public function store(Request $request)
    {
        $this->guard();

        $data = $this->validated($request);
        $businessId = $request->session()->get('user.business_id');

        $tpl = VcConsentTemplate::create(array_merge($data, [
            'business_id' => $businessId,
            'code'        => $this->uniqueCode($data['name_en'], $businessId),
            'created_by'  => auth()->id(),
        ]));
        $this->vcLog('create', $tpl);

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

    public function update(Request $request, $id)
    {
        $this->guard();

        $businessId = $request->session()->get('user.business_id');
        // Only the clinic's own templates can be edited — never a system row.
        $tpl = VcConsentTemplate::where('business_id', $businessId)->findOrFail($id);

        $data = $this->validated($request);
        $original = $tpl->getOriginal();
        $tpl->update($data);

        $dirty = array_keys($tpl->getChanges());
        if ($dirty) {
            $this->vcLog('update', $tpl, [
                'before' => array_intersect_key($original, array_flip($dirty)),
                'after'  => array_intersect_key($tpl->getAttributes(), array_flip($dirty)),
                'fields' => $dirty,
            ]);
        }

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

    /**
     * Clone a system template into an editable business copy. The copy keeps
     * the same code so it shadows the system original in the consent picker.
     */
    public function clone(Request $request, $id)
    {
        $this->guard();

        $businessId = $request->session()->get('user.business_id');
        $src = VcConsentTemplate::whereNull('business_id')->findOrFail($id);

        $copy = VcConsentTemplate::create([
            'business_id'      => $businessId,
            'code'             => $src->code,
            'category'         => $src->category,
            'name_en'          => $src->name_en,
            'name_ar'          => $src->name_ar,
            'body_en'          => $src->body_en,
            'body_ar'          => $src->body_ar,
            'requires_witness' => $src->requires_witness,
            'sort_order'       => $src->sort_order,
            'status'           => 'active',
            'created_by'       => auth()->id(),
        ]);
        $this->vcLog('create', $copy, ['cloned_from' => $src->id]);

        return response()->json([
            'success'  => true,
            'msg'      => 'Editable copy created. You can now customise it.',
            'template' => $copy,
        ]);
    }

    public function destroy(Request $request, $id)
    {
        $this->guard();

        $businessId = $request->session()->get('user.business_id');
        $tpl = VcConsentTemplate::where('business_id', $businessId)->findOrFail($id);
        $this->vcLog('delete', $tpl, ['before' => $this->_vcFilterAttrs($tpl->getAttributes())]);
        $tpl->delete();

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

    private function validated(Request $request): array
    {
        $request->validate([
            'name_en'  => 'required|string|max:191',
            'name_ar'  => 'nullable|string|max:191',
            'category' => 'required|string|max:40',
            'body_en'  => 'required|string',
            'body_ar'  => 'nullable|string',
        ]);

        $category = array_key_exists($request->category, VcConsentTemplate::categories())
            ? $request->category : 'general';

        return [
            'name_en'          => $request->name_en,
            'name_ar'          => $request->name_ar,
            'category'         => $category,
            'body_en'          => $request->body_en,
            'body_ar'          => $request->body_ar,
            'requires_witness' => $request->boolean('requires_witness'),
            'sort_order'       => (int) ($request->sort_order ?? 100),
            'status'           => $request->status === 'inactive' ? 'inactive' : 'active',
        ];
    }

    /** Build a code unique within the business from the English name. */
    private function uniqueCode(string $name, ?int $businessId): string
    {
        $base = Str::slug($name, '_') ?: 'consent';
        $base = substr($base, 0, 50);
        $code = $base;
        $i = 2;
        while (VcConsentTemplate::where('business_id', $businessId)->where('code', $code)->exists()) {
            $code = $base . '_' . $i++;
        }
        return $code;
    }
}
