<?php

namespace App\Http\Controllers\Care;

use App\Http\Controllers\Controller;
use App\Models\CareVoiceAnnouncement;
use App\Services\Care\CareDisplayService;
use App\Services\Care\CareVoiceAnnouncementService;
use App\Support\OrganizationBranding;
use Illuminate\Http\JsonResponse;
use Illuminate\View\View;

class DisplayPublicController extends Controller
{
    public function __construct(
        protected CareDisplayService $displays,
        protected CareVoiceAnnouncementService $voice,
    ) {}

    public function show(string $token): View
    {
        $screen = $this->displays->findByToken($token) ?? abort(404);
        $screen->loadMissing(['organization', 'branch']);
        $this->displays->touch($screen);

        $payload = $this->displays->payload($screen);
        $organization = $screen->organization;

        return view('care.display.public', [
            'screen' => $screen,
            'initialPayload' => $payload,
            'dataUrl' => '/display/'.$token.'/data',
            'playedUrl' => '/display/'.$token.'/announcements/__ID__/played',
            'pollMs' => config('care.display_poll_ms', 1200),
            'logoUrl' => $organization
                ? OrganizationBranding::logoUrl($organization)
                : asset(OrganizationBranding::DEFAULT_LOGO),
            'logoAlt' => $organization
                ? OrganizationBranding::logoAlt($organization)
                : 'Ladill Care',
            'poweredByLogoUrl' => asset(OrganizationBranding::DEFAULT_LOGO),
        ]);
    }

    public function data(string $token): JsonResponse
    {
        $screen = $this->displays->findByToken($token) ?? abort(404);
        $this->displays->touch($screen);

        return response()->json($this->displays->payload($screen));
    }

    public function played(string $token, CareVoiceAnnouncement $announcement): JsonResponse
    {
        $screen = $this->displays->findByToken($token) ?? abort(404);
        abort_unless($announcement->branch_id === $screen->branch_id, 404);

        $this->voice->markPlayed($announcement);

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