<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\FormTemplate;
use App\Models\FormField;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Traits\ApiResponseTrait;
use Illuminate\Support\Str;
use App\Models\UserDeleteLog;
use App\Models\FormInstance;
use App\Models\FormInstanceValue;
use App\Models\FormTemplateStatutoryAct;

class FormTemplateController extends Controller
{
    use ApiResponseTrait;

    /**
     * List all form templates
     */
    public function list()
    {
        $forms = FormTemplate::where('is_active', 1)
            ->with('key_areas_compliance')
            ->with('key_areas_sub_compliance')
            ->with('state_master')
            ->with('statutory_act')
            ->orderBy('created_on', 'DESC')
            ->get();

        return $this->successResponse(
            'Form templates fetched successfully',
            $forms
        );
    }


    public function create(Request $request)
    {
        $data = $request->validate([
            'form.form_name' => 'required|string|max:255',
            'form.periodicity' => 'nullable',
            'form.client_id' => 'integer|exists:client_master,id',
            'form.branch_id' => 'integer|exists:client_branch,id',
            'form.state_id' => 'required|integer|exists:state_master,id',
            'form.key_areas_compliance_id' => 'nullable',
            'form.key_areas_sub_compliance_id' => 'nullable',
            'form.act_ids' => 'nullable|array',
            'form.act_ids.*' => 'integer|exists:statutory_master,id',
            'fields' => 'required|array|min:1',
            'fields.*.field_label' => 'required|string|max:255',
            'fields.*.field_type' => 'required|string',
            'fields.*.is_workflow_param' => 'boolean'
        ]);

        DB::beginTransaction();

        try {
            $template = FormTemplate::create([
                'form_code' => strtoupper(Str::slug($data['form']['form_name'])) . '_' . rand(100, 999),
                'form_name' => $data['form']['form_name'],
                'periodicity' => $data['form']['periodicity'],
                'client_id' => $data['form']['client_id'],
                'client_branch_id' => $data['form']['branch_id'],
                'state_id' => $data['form']['state_id'],
                'key_areas_compliance_id' => $data['form']['key_areas_compliance_id'],
                'key_areas_sub_compliance_id' => $data['form']['key_areas_sub_compliance_id'],
                'version' => 1,
                'is_active' => 1
            ]);

            foreach ($data['fields'] as $index => $field) {

                // ✅ AUTO‑GENERATED UNIQUE FIELD KEY
                $fieldKey =
                    strtolower($template->form_code) . '_' .
                    Str::slug($field['field_label'], '_') . '_' .
                    Str::random(4);

                FormField::create([
                    'form_template_id' => $template->id,
                    'field_key' => $fieldKey,
                    'field_label' => $field['field_label'],
                    'field_type' => $field['field_type'],
                    'is_required' => $field['is_required'] ?? 0,
                    'is_workflow_param' => $field['is_workflow_param'] ?? 0,
                    'is_visible_to_client' => $field['is_visible_to_client'] ?? 0,
                    'display_order' => $index + 1
                ]);
            }

            if (!empty($data['form']['act_ids'])) {
                foreach ($data['form']['act_ids'] as $statutoryId) {
                    FormTemplateStatutoryAct::create([
                        'form_template_id' => $template->id,
                        'statutory_id' => $statutoryId,
                    ]);
                }
            }


            DB::commit();

            return $this->successResponse(
                'Form template created successfully',
                $template
            );
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->errorResponse(
                'Failed to create form template',
                $e->getMessage(),
                500
            );
        }
    }


   public function get($id)
{
    $form = FormTemplate::with([
            'fields',
            'statutory_act',
            'key_areas_sub_compliance',
            'client' => function ($q) {
                $q->select('id', 'client_name', 'client_code');
            },
            'client_branch' => function ($q) {
                $q->select('id', 'client_id', 'branch_name', 'branch_code');
            }
        ])
        ->where('id', $id)
        ->first();

    return $form
        ? $this->successResponse('Form template fetched', $form)
        : $this->errorResponse('Form template not found', null, 404);
}


    public function upateForm(Request $request, $id)
    {
        $data = $request->validate([
            'form.form_name' => 'required|string|max:255',
            'form.periodicity' => 'nullable',
            'form.client_id' => 'integer|exists:client_master,id',
            'form.branch_id' => 'integer|exists:client_branch,id',
            'form.state_id' => 'required|integer|exists:state_master,id',
            'form.key_areas_compliance_id' => 'nullable',
            'form.key_areas_sub_compliance_id' => 'nullable',
            'form.act_ids' => 'array',
            'form.act_ids.*' => 'integer|exists:statutory_master,id',
            'fields' => 'required|array|min:1',
            'fields.*.id' => 'nullable|exists:form_field,id',
            'fields.*.field_label' => 'required|string|max:255',
            'fields.*.field_type' => 'required|string',
            'fields.*.is_workflow_param' => 'boolean',
            'fields.*.display_order' => 'required|integer'
        ]);

        DB::beginTransaction();

        try {
            $template = FormTemplate::findOrFail($id);

            /* -----------------------------
         Update Form Template
        ------------------------------ */
            $template->update([
                'form_name'   => $data['form']['form_name'],
                'periodicity' => $data['form']['periodicity'],
                'client_id' => $data['form']['client_id'],
                'client_branch_id' => $data['form']['branch_id'],
                'state_id' => $data['form']['state_id'],
                'key_areas_compliance_id' => $data['form']['key_areas_compliance_id'],
                'key_areas_sub_compliance_id' => $data['form']['key_areas_sub_compliance_id'],
            ]);

            /* -----------------------------
         Existing Field IDs
        ------------------------------ */
            $incomingFieldIds = collect($data['fields'])
                ->pluck('id')
                ->filter()
                ->values();

            /* -----------------------------
         Delete Removed Fields
        ------------------------------ */
            FormField::where('form_template_id', $template->id)
                ->whereNotIn('id', $incomingFieldIds)
                ->delete();

            /* -----------------------------
         Upsert Fields
        ------------------------------ */
            foreach ($data['fields'] as $field) {

                // EXISTING FIELD → UPDATE
                if (!empty($field['id'])) {

                    FormField::where('id', $field['id'])->update([
                        'field_label'       => $field['field_label'],
                        'field_type'        => $field['field_type'],
                        'is_workflow_param' => $field['is_workflow_param'] ?? 0,
                        'display_order'     => $field['display_order'],
                    ]);
                }
                // NEW FIELD → CREATE
                else {

                    $fieldKey =
                        strtolower($template->form_code) . '_' .
                        Str::slug($field['field_label'], '_') . '_' .
                        Str::random(4);

                    FormField::create([
                        'form_template_id'  => $template->id,
                        'field_key'         => $fieldKey,
                        'field_label'       => $field['field_label'],
                        'field_type'        => $field['field_type'],
                        'is_required'       => $field['is_required'] ?? 0,
                        'is_workflow_param' => $field['is_workflow_param'] ?? 0,
                        'is_visible_to_client' => $field['is_visible_to_client'] ?? 0,
                        'display_order'     => $field['display_order'],
                    ]);
                }
            }

             /* -----------------------------
           STATUTORY ACT SYNC
        ------------------------------ */
        if (isset($data['form']['act_ids'])) {

            $incomingActIds = collect($data['form']['act_ids'])->unique();

            // Delete removed acts
            FormTemplateStatutoryAct::where('form_template_id', $template->id)
                ->whereNotIn('statutory_id', $incomingActIds)
                ->delete();

            // Insert new acts
            foreach ($incomingActIds as $actId) {
                FormTemplateStatutoryAct::firstOrCreate(
                    [
                        'form_template_id' => $template->id,
                        'statutory_id' => $actId,
                    ],
                );
            }
        }
            DB::commit();

            return $this->successResponse(
                'Form template updated successfully',
                $template->load('fields')
            );
        } catch (\Exception $e) {
            DB::rollBack();

            return $this->errorResponse(
                'Failed to update form template',
                $e->getMessage(),
                500
            );
        }
    }

    /**
     * Delete form template (with reason)
     */
    public function deleteForm(Request $request, $id)
    {


        DB::beginTransaction();

        try {
            $template = FormTemplate::findOrFail($id);

            $template->update([
                'is_active'  => 0,
            ]);


            FormField::where('form_template_id', $template->id)->delete();

            DB::commit();

            UserDeleteLog::create( [
                'table_id' => $id,
                'table_name'  => 'form_template',
                'reason' => $request['reason'],
            ]);

            return $this->successResponse(
                'Form template deleted successfully'
            );
        } catch (\Exception $e) {
            DB::rollBack();

            return $this->errorResponse(
                'Failed to delete form template',
                $e->getMessage(),
                500
            );
        }
    }

    /**
     * Clone form template
     */
    public function cloneForm($id)
    {
        DB::beginTransaction();

        try {
            $template = FormTemplate::with('fields')->findOrFail($id);

            /* -----------------------------
         Clone Form Template
        ------------------------------ */
            $newTemplate = FormTemplate::create([
                'form_code'   => strtoupper(Str::slug($template->form_name)) . '_' . rand(100, 999),
                'form_name'   => $template->form_name . ' (Copy)',
                'periodicity' => $template->periodicity,
                'key_areas_compliance_id' => $template->key_areas_compliance_id,
                'version'     => 1,
                'is_active'   => 1,
            ]);

            /* -----------------------------
         Clone Fields
        ------------------------------ */
            foreach ($template->fields as $field) {
                $fieldKey =
                    strtolower($newTemplate->form_code) . '_' .
                    Str::slug($field->field_label, '_') . '_' .
                    Str::random(4);

                FormField::create([
                    'form_template_id'  => $newTemplate->id,
                    'field_key'         => $fieldKey,
                    'field_label'       => $field->field_label,
                    'field_type'        => $field->field_type,
                    'is_required'       => $field->is_required,
                    'is_workflow_param' => $field->is_workflow_param,
                    'is_visible_to_client' => $field->is_visible_to_client,
                    'display_order'     => $field->display_order,
                ]);
            }

            DB::commit();

            return $this->successResponse(
                'Form template cloned successfully',
                $newTemplate->load('fields')
            );
        } catch (\Exception $e) {
            DB::rollBack();

            return $this->errorResponse(
                'Failed to clone form template',
                $e->getMessage(),
                500
            );
        }
    }



    public function saveFormValues(Request $request, $id)
    {
        $instance = FormInstance::findOrFail($id);

        foreach ($request->values as $fieldId => $value) {
            FormInstanceValue::updateOrCreate(
                [
                    'form_instance_id' => $instance->id,
                    'form_field_id' => $fieldId
                ],
                ['field_value' => $value]
            );
        }

        return $this->successResponse('Saved');
    }

    public function showForm($id)
    {
        return FormInstance::with([
            'template',
            'template.fields' => fn ($q) => $q->orderBy('display_order'),
            'values'
        ])->findOrFail($id);
    }


}
