<?php

namespace App\Http\Controllers\Admin;

use App\Helpers\DeliveryChallanDocumentSettings;
use Illuminate\Http\Request;

class DeliveryChallanDocumentPreferenceController extends AdminController
{
    public function index(Request $request)
    {
        $companyId = $this->companyId();
        $tab = $request->query('tab', 'options');
        if (! in_array($tab, ['options', 'labels'], true)) {
            $tab = 'options';
        }

        $docSettings = DeliveryChallanDocumentSettings::forCompany($companyId);
        $config = DeliveryChallanDocumentSettings::config();

        return view('admin.preferences.delivery-challans.index', [
            'activeSection' => 'delivery_challans_doc',
            'tab' => $tab,
            'options' => $docSettings['options'],
            'labels' => $docSettings['labels'],
            'optionDefs' => $config['options'] ?? [],
            'labelDefs' => $config['labels'] ?? [],
        ]);
    }

    public function update(Request $request)
    {
        $companyId = $this->companyId();
        $tab = $request->input('tab', 'options');

        if ($tab === 'labels') {
            $rules = [];
            foreach (array_keys(DeliveryChallanDocumentSettings::defaultLabels()) as $key) {
                $rules["labels.{$key}"] = ['nullable', 'string', 'max:100'];
            }

            $validated = $request->validate($rules);
            $labels = [];
            foreach (DeliveryChallanDocumentSettings::defaultLabels() as $key => $default) {
                $labels[$key] = trim((string) ($validated['labels'][$key] ?? $default));
                if ($labels[$key] === '') {
                    $labels[$key] = DeliveryChallanDocumentSettings::defaultLabels()[$key];
                }
            }

            DeliveryChallanDocumentSettings::update(
                $companyId,
                DeliveryChallanDocumentSettings::optionsForCompany($companyId),
                $labels
            );
        } else {
            $options = [];
            foreach (array_keys(DeliveryChallanDocumentSettings::defaultOptions()) as $key) {
                $options[$key] = $request->boolean($key);
            }

            DeliveryChallanDocumentSettings::update(
                $companyId,
                $options,
                DeliveryChallanDocumentSettings::labelsForCompany($companyId)
            );
        }

        return redirect()
            ->route('admin.preferences.delivery-challans', ['tab' => $tab])
            ->with('success', 'Delivery challan settings saved successfully.');
    }
}
