<?php

namespace Modules\ClinicCore\Http\Controllers;

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

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

    private function gate()
    {
        if (!auth()->user()->can('clinic.manage_evaluation_questions') && !auth()->user()->can('clinic.access_settings')) {
            abort(403, 'Unauthorized action.');
        }
    }

    public function index()
    {
        $this->gate();
        return view('clinicCore::settings.evaluation-questions');
    }

    public function list(Request $request)
    {
        $this->gate();
        $businessId = $request->session()->get('user.business_id');
        $category   = $request->get('category', 'pet_owner');

        $query = ClcEvaluationQuestion::forBusiness($businessId)
            ->category($category)
            ->orderBy('sort_order')
            ->orderBy('id');

        return DataTables::of($query)
            ->addColumn('response_type_badge', function ($row) {
                $map = ['rating' => 'warning', 'yes_no' => 'info', 'text' => 'default'];
                $color = $map[$row->response_type] ?? 'default';
                return '<span class="label label-' . $color . '">' . strtoupper(str_replace('_', '/', $row->response_type)) . '</span>';
            })
            ->addColumn('required_badge', fn($row) => $row->is_required
                ? '<span class="label label-danger">Required</span>'
                : '<span class="label label-default">Optional</span>')
            ->addColumn('status_badge', function ($row) {
                $color = $row->status === 'active' ? 'success' : 'default';
                return '<span class="label label-' . $color . '">' . ucfirst($row->status) . '</span>';
            })
            ->addColumn('source_badge', fn($row) => is_null($row->business_id)
                ? '<span class="label label-primary">System</span>'
                : '<span class="label label-success">Custom</span>')
            ->addColumn('action', function ($row) {
                $edit = '<button class="btn btn-xs btn-primary btn-edit-question" data-id="' . $row->id . '"><i class="fa fa-edit"></i></button> ';
                $del  = is_null($row->business_id)
                    ? '<button class="btn btn-xs btn-default" disabled title="System default — edit to override"><i class="fa fa-lock"></i></button>'
                    : '<button class="btn btn-xs btn-danger btn-delete-question" data-id="' . $row->id . '"><i class="fa fa-trash"></i></button>';
                return $edit . $del;
            })
            ->rawColumns(['action', 'response_type_badge', 'required_badge', 'status_badge', 'source_badge'])
            ->make(true);
    }

    public function store(Request $request)
    {
        $this->gate();
        $request->validate([
            'category'      => 'required|in:pet_owner,clinic',
            'question_text' => 'required|string|max:1000',
            'response_type' => 'required|in:rating,text,yes_no',
        ]);

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

        $question = ClcEvaluationQuestion::create([
            'business_id'   => $businessId,
            'category'      => $request->category,
            'question_text' => $request->question_text,
            'response_type' => $request->response_type,
            'is_required'   => $request->boolean('is_required'),
            'sort_order'    => (int) ($request->sort_order ?? 0),
            'status'        => $request->status ?? 'active',
        ]);
        $this->drmLog('create', $question);

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

    public function edit($id)
    {
        $this->gate();
        $businessId = request()->session()->get('user.business_id');
        return response()->json(ClcEvaluationQuestion::forBusiness($businessId)->findOrFail($id));
    }

    public function update(Request $request, $id)
    {
        $this->gate();
        $request->validate([
            'question_text' => 'required|string|max:1000',
            'response_type' => 'required|in:rating,text,yes_no',
        ]);

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

        // If editing a system default, clone it as a business-owned override
        if (is_null($row->business_id)) {
            $clone = $row->replicate();
            $clone->business_id = $businessId;
            $clone->question_text = $request->question_text;
            $clone->response_type = $request->response_type;
            $clone->is_required   = $request->boolean('is_required');
            $clone->sort_order    = (int) ($request->sort_order ?? $row->sort_order);
            $clone->status        = $request->status ?? 'active';
            $clone->save();
            $this->drmLog('create', $clone, ['note' => 'Business override of system default question #' . $row->id]);

            return response()->json(['success' => true, 'msg' => 'Created business override', 'promoted' => true]);
        }

        $before = $row->getOriginal();
        $row->update([
            'question_text' => $request->question_text,
            'response_type' => $request->response_type,
            'is_required'   => $request->boolean('is_required'),
            'sort_order'    => (int) ($request->sort_order ?? $row->sort_order),
            'status'        => $request->status ?? 'active',
        ]);
        $dirty = array_keys($row->getChanges());
        $this->drmLog('update', $row, [
            'before' => array_intersect_key($before, array_flip($dirty)),
            'after'  => array_intersect_key($row->getAttributes(), array_flip($dirty)),
            'fields' => $dirty,
        ]);

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

    public function destroy($id)
    {
        $this->gate();
        $businessId = request()->session()->get('user.business_id');
        $row = ClcEvaluationQuestion::forBusiness($businessId)->findOrFail($id);
        if (is_null($row->business_id)) {
            return response()->json(['success' => false, 'msg' => 'Cannot delete system default'], 422);
        }
        $this->drmLog('delete', $row, ['before' => $this->_drmFilterAttrs($row->getAttributes())]);
        $row->delete();
        return response()->json(['success' => true, 'msg' => __('clinicCore::lang.deleted_successfully')]);
    }
}
