<?php

namespace App\Http\Controllers;

use App\Models\ChurchProfile;
use App\Models\MemberPosition;
use App\Models\SacramentType;
use App\Models\ServiceType;
use App\Models\Setting;
use App\Models\UserPosition;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class SettingsController extends Controller
{
    public function churchProfile(): View
    {
        return view('settings.church-profile', [
            'profile' => ChurchProfile::firstOrCreate(['id' => 1]),
        ]);
    }

    public function updateChurchProfile(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'church_name' => ['required', 'string', 'max:255'],
            'diocese' => ['nullable', 'string', 'max:255'],
            'parish' => ['nullable', 'string', 'max:255'],
            'location' => ['required', 'string', 'max:255'],
            'phone' => ['nullable', 'string', 'max:50'],
            'email' => ['nullable', 'email', 'max:255'],
            'address' => ['nullable', 'string'],
            'logo_path' => ['nullable', 'string', 'max:255'],
        ]);

        ChurchProfile::firstOrCreate(['id' => 1])->update($data);
        $this->logActivity('updated', 'settings', 'Updated church profile');

        return back()->with('success', 'Church profile imeboreshwa.');
    }

    public function userPositions(): View
    {
        return $this->optionView('User Positions', UserPosition::orderBy('name')->get(), 'settings.user-positions.store', 'settings.user-positions.destroy');
    }

    public function storeUserPosition(Request $request): RedirectResponse
    {
        return $this->storeOption($request, UserPosition::class, 'User position imeongezwa.');
    }

    public function destroyUserPosition(UserPosition $position): RedirectResponse
    {
        return $this->destroyOption($position, 'User position imefutwa.');
    }

    public function memberPositions(): View
    {
        return $this->optionView('Member Positions', MemberPosition::orderBy('name')->get(), 'settings.member-positions.store', 'settings.member-positions.destroy');
    }

    public function storeMemberPosition(Request $request): RedirectResponse
    {
        return $this->storeOption($request, MemberPosition::class, 'Member position imeongezwa.');
    }

    public function destroyMemberPosition(MemberPosition $position): RedirectResponse
    {
        return $this->destroyOption($position, 'Member position imefutwa.');
    }

    public function serviceTypes(): View
    {
        return $this->optionView('Service Types', ServiceType::orderBy('name')->get(), 'settings.service-types.store', 'settings.service-types.destroy');
    }

    public function storeServiceType(Request $request): RedirectResponse
    {
        return $this->storeOption($request, ServiceType::class, 'Service type imeongezwa.');
    }

    public function destroyServiceType(ServiceType $type): RedirectResponse
    {
        return $this->destroyOption($type, 'Service type imefutwa.');
    }

    public function sacramentTypes(): View
    {
        return $this->optionView('Sacrament Types', SacramentType::orderBy('name')->get(), 'settings.sacrament-types.store', 'settings.sacrament-types.destroy');
    }

    public function storeSacramentType(Request $request): RedirectResponse
    {
        return $this->storeOption($request, SacramentType::class, 'Sacrament type imeongezwa.');
    }

    public function destroySacramentType(SacramentType $type): RedirectResponse
    {
        return $this->destroyOption($type, 'Sacrament type imefutwa.');
    }

    public function attendanceSettings(): View
    {
        return view('settings.simple-settings', [
            'title' => 'Attendance Settings',
            'group' => 'attendance',
            'settings' => $this->settingsFor('attendance'),
        ]);
    }

    public function qrSettings(): View
    {
        return view('settings.simple-settings', [
            'title' => 'QR Code Settings',
            'group' => 'qr',
            'settings' => $this->settingsFor('qr'),
        ]);
    }

    public function registrationSettings(): View
    {
        $settings = $this->settingsFor('registration');

        return view('settings.registration', [
            'isOpen' => $settings['is_open'] === 'Yes',
            'defaultStatus' => $settings['default_member_status'],
            'introText' => $settings['intro_text'],
        ]);
    }

    public function updateRegistrationSettings(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'is_open' => ['nullable', 'boolean'],
            'default_member_status' => ['required', 'in:active,inactive'],
            'intro_text' => ['nullable', 'string', 'max:255'],
        ]);

        $settings = [
            'is_open' => $request->boolean('is_open') ? 'Yes' : 'No',
            'default_member_status' => $data['default_member_status'],
            'intro_text' => $data['intro_text'] ?? '',
        ];

        foreach ($settings as $key => $value) {
            Setting::updateOrCreate(['group' => 'registration', 'key' => $key], ['value' => $value]);
        }

        $this->logActivity('updated', 'settings', 'Updated registration settings');

        return back()->with('success', 'Registration settings zimeboreshwa.');
    }

    public function updateSimpleSettings(Request $request, string $group): RedirectResponse
    {
        $data = $request->validate([
            'settings' => ['array'],
            'settings.*' => ['nullable', 'string'],
        ]);

        foreach (($data['settings'] ?? []) as $key => $value) {
            Setting::updateOrCreate(['group' => $group, 'key' => $key], ['value' => $value]);
        }

        $this->logActivity('updated', 'settings', "Updated {$group} settings");

        return back()->with('success', 'Settings zimeboreshwa.');
    }

    private function optionView(string $title, $items, string $storeRoute, string $destroyRoute): View
    {
        return view('settings.options', compact('title', 'items', 'storeRoute', 'destroyRoute'));
    }

    private function storeOption(Request $request, string $model, string $message): RedirectResponse
    {
        $data = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'description' => ['nullable', 'string'],
            'status' => ['required', 'in:active,inactive'],
        ]);

        $model::create($data);
        $this->logActivity('created', 'settings', "Created {$data['name']}");

        return back()->with('success', $message);
    }

    private function destroyOption($model, string $message): RedirectResponse
    {
        $model->delete();
        $this->logActivity('deleted', 'settings', "Deleted {$model->name}");

        return back()->with('success', $message);
    }

    private function settingsFor(string $group): array
    {
        $defaults = [
            'attendance' => [
                'allow_closed_service_edit' => 'No',
                'late_after_minutes' => '20',
                'default_attendance_status' => 'present',
            ],
            'qr' => [
                'token_prefix' => 'CHURCH-MEMBER',
                'scanner_fps' => '10',
                'qr_card_note' => 'Please present this card during service attendance.',
            ],
            'registration' => [
                'is_open' => 'No',
                'default_member_status' => 'inactive',
                'intro_text' => 'Jisajili kama member wa Anglican Church St Peter and Paul Mwenge Kijitonyama.',
            ],
        ];

        $stored = Setting::where('group', $group)->pluck('value', 'key')->all();

        return array_replace($defaults[$group] ?? [], $stored);
    }
}
