<?php

namespace App\Http\Controllers;

use App\Services\SupabaseService;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

/**
 * Fase 2: kelola definisi kolom/metrik sebuah instansi lewat web (tanpa ngoding).
 * Menyimpan ke tabel instansi_field.
 */
class FieldConfigController extends Controller
{
    public function __construct(private SupabaseService $supabase)
    {
    }

    public function index(string $slug)
    {
        $ref = $this->supabase->getInstansiRefBySlug($slug);
        if (!$ref) {
            abort(404, 'Instansi tidak ditemukan.');
        }

        return view('field-config', [
            'ref' => $ref,
            'slug' => $slug,
            'fields' => $this->supabase->getFields($ref['id'], activeOnly: false),
        ]);
    }

    public function store(Request $request, string $slug)
    {
        $ref = $this->supabase->getInstansiRefBySlug($slug);
        if (!$ref) {
            abort(404, 'Instansi tidak ditemukan.');
        }

        $request->validate([
            'label' => 'required|string|max:255',
            'satuan' => 'nullable|string|max:50',
            'urutan' => 'nullable|integer',
            'sheet_col' => 'nullable|string|max:5',
            'field_key' => 'nullable|string|max:100',
        ]);

        // field_key otomatis dari label bila kosong (mis. "Volume Timbulan" → "volume_timbulan")
        $fieldKey = $request->input('field_key')
            ?: Str::of($request->input('label'))->slug('_')->toString();

        try {
            $this->supabase->upsertField([
                'instansi_ref_id' => $ref['id'],
                'field_key' => $fieldKey,
                'label' => $request->input('label'),
                'satuan' => $request->input('satuan'),
                'tipe' => 'number',
                'urutan' => (int) $request->input('urutan', 0),
                'sheet_col' => $request->input('sheet_col') ? strtoupper($request->input('sheet_col')) : null,
                'is_active' => true,
            ]);
        } catch (\Throwable $e) {
            return back()->with('error', 'Gagal menyimpan kolom: ' . $e->getMessage());
        }

        return back()->with('success', 'Kolom disimpan.');
    }

    public function destroy(Request $request, string $slug)
    {
        $id = $request->input('id');
        if ($id) {
            $this->supabase->deleteField($id);
        }
        return back()->with('success', 'Kolom dihapus.');
    }
}
