<?php

namespace App\Livewire\Admin\Settings;

use App\Models\CustomerField;
use Livewire\Component;

class CustomerFieldSettings extends Component
{
    public $fields = [];
    public $editingPlaceholder = null;
    public $placeholderValue = '';
    public $pincodeField = [];

    public function mount()
    {
        $this->loadFields();
    }

    public function loadFields()
    {
        // Load all fields except pincode (pincode is handled separately)
        $this->fields = CustomerField::where('unique_key', '!=', 'pincode')
            ->orderBy('id')
            ->get()
            ->toArray();

        // Load or create pincode field
        $pincode = CustomerField::where('unique_key', 'pincode')->first();
        if (!$pincode) {
            $pincode = CustomerField::create([
                'unique_key' => 'pincode',
                'name' => 'Pincode/Serial Number',
                'placeholder' => 'Enter pincode here *',
                'required' => true,
                'visible' => true,
            ]);
        }
        $this->pincodeField = $pincode->toArray();
    }

    public function toggleVisible($fieldId)
    {
        $field = CustomerField::find($fieldId);
        if ($field) {
            $field->visible = !$field->visible;
            $field->save();
            $this->loadFields();
            session()->flash('message', 'Field visibility updated successfully!');
        }
    }

    public function toggleRequired($fieldId)
    {
        $field = CustomerField::find($fieldId);
        if ($field) {
            $field->required = !$field->required;
            $field->save();
            $this->loadFields();
            session()->flash('message', 'Field requirement updated successfully!');
        }
    }

    public function editPlaceholder($fieldId, $currentPlaceholder)
    {
        $this->editingPlaceholder = $fieldId;
        $this->placeholderValue = $currentPlaceholder;
    }

    public function updatePlaceholder($fieldId)
    {
        $field = CustomerField::find($fieldId);
        if ($field && trim($this->placeholderValue) !== '') {
            $field->placeholder = $this->placeholderValue;
            $field->save();
            $this->loadFields();
            session()->flash('message', 'Placeholder updated successfully!');
        }
        $this->editingPlaceholder = null;
        $this->placeholderValue = '';
    }

    public function cancelEdit()
    {
        $this->editingPlaceholder = null;
        $this->placeholderValue = '';
    }

    public function render()
    {
        return view('livewire.admin.settings.customer-field-settings')
            ->layout('layouts.app');
    }
}
