<?php

namespace Modules\MedNotify\Http\Controllers;

use Illuminate\Http\Request;
use Modules\MedNotify\Entities\MednotifyEvent;
use Modules\MedNotify\Entities\MednotifyPreference;

/**
 * "My preferences" — the current user manages their OWN per-event per-channel
 * opt-outs, digest mode and quiet hours. Every row is scoped to the session
 * business id AND the current user id; a user can never edit another user's
 * preferences.
 */
class PreferenceController extends MedNotifyBaseController
{
    public function edit()
    {
        $this->guard('mednotify.preferences.manage_own');

        $businessId = $this->businessId();
        $userId = (int) $this->userId();

        $events = MednotifyEvent::where(function ($q) use ($businessId) {
            $q->where('business_id', $businessId)->orWhereNull('business_id');
        })
            ->where('is_active', true)
            ->orderBy('event_key')
            ->get()
            ->unique('event_key')
            ->values();

        // Existing per-event×channel rows keyed "event|channel" for the matrix.
        $rows = MednotifyPreference::where('business_id', $businessId)
            ->where('user_id', $userId)
            ->whereNotNull('event_key')
            ->whereNotNull('channel')
            ->get()
            ->keyBy(fn ($p) => $p->event_key . '|' . $p->channel);

        // The global row (event_key NULL, channel NULL) carries digest + quiet hours.
        $global = MednotifyPreference::firstOrNew([
            'business_id' => $businessId,
            'user_id'     => $userId,
            'event_key'   => null,
            'channel'     => null,
        ]);

        return view('mednotify::preferences.edit', [
            'events'   => $events,
            'channels' => $this->channels(),
            'rows'     => $rows,
            'global'   => $global,
        ]);
    }

    public function update(Request $request)
    {
        $this->guard('mednotify.preferences.manage_own');

        $businessId = $this->businessId();
        $userId = (int) $this->userId();

        $data = $this->validate($request, [
            'digest'     => 'required|in:immediate,hourly,daily',
            'quiet_from' => 'nullable|date_format:H:i',
            'quiet_to'   => 'nullable|date_format:H:i',
            'matrix'     => 'nullable|array', // matrix[event_key][channel] = 1 when ENABLED
        ]);

        try {
            // Global row — digest + quiet hours.
            MednotifyPreference::updateOrCreate(
                ['business_id' => $businessId, 'user_id' => $userId, 'event_key' => null, 'channel' => null],
                [
                    'enabled'    => true,
                    'digest'     => $data['digest'],
                    'quiet_from' => $data['quiet_from'] ?? null,
                    'quiet_to'   => $data['quiet_to'] ?? null,
                ]
            );

            // Per event×channel enabled flags. A checked box = enabled (default),
            // so we only persist explicit OFF rows to keep the table lean, and
            // clear any prior OFF row that is now back on.
            $matrix = (array) ($data['matrix'] ?? []);
            $events = MednotifyEvent::where(function ($q) use ($businessId) {
                $q->where('business_id', $businessId)->orWhereNull('business_id');
            })->pluck('event_key')->unique();

            foreach ($events as $eventKey) {
                foreach ($this->channels() as $channel) {
                    $isEnabled = ! empty($matrix[$eventKey][$channel]);

                    if ($isEnabled) {
                        // Remove any explicit opt-out row (back to default: on).
                        MednotifyPreference::where('business_id', $businessId)
                            ->where('user_id', $userId)
                            ->where('event_key', $eventKey)
                            ->where('channel', $channel)
                            ->delete();
                    } else {
                        MednotifyPreference::updateOrCreate(
                            ['business_id' => $businessId, 'user_id' => $userId, 'event_key' => $eventKey, 'channel' => $channel],
                            ['enabled' => false, 'digest' => 'immediate']
                        );
                    }
                }
            }

            return redirect()->route('mednotify.preferences.edit')
                ->with('status', ['success' => 1, 'msg' => __('mednotify::lang.preferences_saved')]);
        } catch (\Exception $e) {
            \Log::emergency($e->getMessage());

            return redirect()->route('mednotify.preferences.edit')
                ->with('status', ['success' => 0, 'msg' => __('messages.something_went_wrong')]);
        }
    }
}
