<?php

namespace App\Http\Controllers\Agency\Customer;

use App\Http\Controllers\Controller;
use App\Models\Customer\Customer;
use App\Models\Customer\CustomerFieldDefinition;
use App\Models\Customer\CustomerFieldValue;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

/**
 * Acente özel alan şema yönetimi.
 * Alan TANIMI oluşturma/düzenleme/silme işlemleri.
 */
class CustomerFieldDefinitionController extends Controller
{
     // ─── INDEX ────────────────────────────────────────────────────────────────

     public function index()
     {
          $definitions = CustomerFieldDefinition::byAgency(Auth::user()->currentAgencyId())
               ->ordered()
               ->withCount('values')
               ->get();

          return view('agency.customers.fields.index', compact('definitions'));
     }

     // ─── CREATE / STORE ───────────────────────────────────────────────────────

     public function create()
     {
          return view('agency.customers.fields.create');
     }

     public function store(Request $request)
     {
          $agencyId = Auth::user()->currentAgencyId();

          $validated = $request->validate([
               'label' => 'required|string|max:120',
               'field_key' => [
                    'nullable',
                    'string',
                    'max:60',
                    'regex:/^[a-z0-9_]+$/',
                    // Aynı acentede tekrar edemez (field_key boşsa boot'ta üretilir)
                    \Illuminate\Validation\Rule::unique('customer_field_definitions')
                         ->where('agency_id', $agencyId),
               ],
               'field_type' => 'required|in:text,textarea,number,decimal,boolean,date,select,multiselect,email,phone,url',
               'options' => 'nullable|array',
               'options.*.value' => 'required_with:options|string|max:100',
               'options.*.label' => 'required_with:options|string|max:100',
               'validation_rules' => 'nullable|string|max:255',
               'default_value' => 'nullable|string|max:255',
               'is_required' => 'boolean',
               'is_searchable' => 'boolean',
               'is_filterable' => 'boolean',
               'is_visible_in_list' => 'boolean',
               'help_text' => 'nullable|string|max:255',
               'sort_order' => 'nullable|integer|min:0',
          ]);

          $validated['agency_id'] = $agencyId;

          CustomerFieldDefinition::create($validated);

          return redirect()
               ->route('agency.customers.fields.index')
               ->with('success', '"' . $validated['label'] . '" alani olusturuldu.');
     }

     // ─── EDIT / UPDATE ────────────────────────────────────────────────────────

     public function edit(CustomerFieldDefinition $field)
     {
          $this->authorizeAgency($field);

          return view('agency.customers.fields.edit', compact('field'));
     }

     public function update(Request $request, CustomerFieldDefinition $field)
     {
          $this->authorizeAgency($field);

          $agencyId = Auth::user()->currentAgencyId();

          $validated = $request->validate([
               'label' => 'required|string|max:120',
               'field_key' => [
                    'required',
                    'string',
                    'max:60',
                    'regex:/^[a-z0-9_]+$/',
                    \Illuminate\Validation\Rule::unique('customer_field_definitions')
                         ->where('agency_id', $agencyId)
                         ->ignore($field->id),
               ],
               'field_type' => 'required|in:text,textarea,number,decimal,boolean,date,select,multiselect,email,phone,url',
               'options' => 'nullable|array',
               'options.*.value' => 'required_with:options|string|max:100',
               'options.*.label' => 'required_with:options|string|max:100',
               'validation_rules' => 'nullable|string|max:255',
               'default_value' => 'nullable|string|max:255',
               'is_required' => 'boolean',
               'is_searchable' => 'boolean',
               'is_filterable' => 'boolean',
               'is_visible_in_list' => 'boolean',
               'help_text' => 'nullable|string|max:255',
               'sort_order' => 'nullable|integer|min:0',
          ]);

          // field_type değişirse mevcut değerleri temizlemeyi sor
          if ($field->field_type !== $validated['field_type'] && $field->values()->exists()) {
               // Uyarı ver ama silme (UI tarafından handle edilir)
               session()->flash('warning', 'Alan tipi değiştirildi. Mevcut müşteri değerleri eski tipte saklı kalacak; uyumsuzluk olabilir.');
          }

          $field->update($validated);

          return back()->with('success', 'Alan başarıyla güncellendi.');
     }

     // ─── DELETE ───────────────────────────────────────────────────────────────

     public function destroy(CustomerFieldDefinition $field)
     {
          $this->authorizeAgency($field);

          $valueCount = $field->values()->count();
          $field->delete(); // soft delete — değerler cascade değil, korunur

          return redirect()
               ->route('agency.customers.fields.index')
               ->with('success', "Alan silindi." . ($valueCount > 0 ? " {$valueCount} müşteri değeri arşivlendi." : ''));
     }

     // ─── SIRA GÜNCELLEME (AJAX drag & drop) ──────────────────────────────────

     public function reorder(Request $request)
     {
          $request->validate([
               'order' => 'required|array',
               'order.*' => 'integer|exists:customer_field_definitions,id',
          ]);

          $agencyId = Auth::user()->currentAgencyId();

          foreach ($request->order as $pos => $id) {
               CustomerFieldDefinition::where('id', $id)
                    ->where('agency_id', $agencyId) // güvenlik: sadece kendi alanlarını değiştirebilir
                    ->update(['sort_order' => $pos]);
          }

          return response()->json(['success' => true]);
     }

     // ─── AKTIF / PASİF ───────────────────────────────────────────────────────

     public function toggleActive(CustomerFieldDefinition $field)
     {
          $this->authorizeAgency($field);

          $field->update(['is_active' => !$field->is_active]);

          return response()->json([
               'success' => true,
               'is_active' => $field->is_active,
               'message' => $field->is_active ? 'Alan aktif edildi.' : 'Alan pasif edildi.',
          ]);
     }

     // ─── YARDIMCI ─────────────────────────────────────────────────────────────

     protected function authorizeAgency(CustomerFieldDefinition $field): void
     {
          if ($field->agency_id !== Auth::user()->currentAgencyId()) {
               abort(403, 'Bu alana erişim yetkiniz yok.');
          }
     }
}
