<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\VideoCardResource;
use App\Models\AdCode;
use App\Models\Setting;
use App\Models\Video;

class SettingController extends Controller
{
    /** Public site configuration consumed by the frontend on boot. */
    public function index()
    {
        $s = Setting::allSettings();

        $marqueeEnabled = (bool) ($s['marquee_enabled'] ?? false)
            && trim((string) ($s['marquee_text'] ?? '')) !== '';

        $exclusive = null;
        if (! empty($s['exclusive_video_id'])) {
            $video = Video::published()->with('category')->find($s['exclusive_video_id']);
            if ($video) {
                $exclusive = new VideoCardResource($video);
            }
        }

        return response()->json([
            'site' => [
                'name' => $s['site_name'],
                'logo' => $s['logo_url'],
                'theme_primary' => $s['theme_primary'],
                'theme_dark' => (bool) $s['theme_dark'],
                'channel_name' => $s['channel_name'],
                'channel_avatar' => $s['channel_avatar'],
            ],
            'marquee' => $marqueeEnabled ? [
                'text' => $s['marquee_text'],
                'link' => $s['marquee_link'],
                'speed' => (int) $s['marquee_speed'],
                'bg' => $s['marquee_bg'],
                'color' => $s['marquee_color'],
            ] : null,
            'ads' => [
                'grid_frequency' => (int) $s['ad_grid_frequency'],
                'grid_random' => (bool) $s['ad_grid_random'],
            ],
            'exclusive' => $exclusive,
        ]);
    }

    /** Return enabled ad codes for a given placement. */
    public function ads(string $placement)
    {
        $allowed = ['grid', 'below_video', 'in_player', 'lock_screen'];
        if (! in_array($placement, $allowed, true)) {
            return response()->json(['data' => []]);
        }

        $ads = AdCode::where('placement', $placement)
            ->where('enabled', true)
            ->orderBy('position')
            ->get(['id', 'name', 'code']);

        return response()->json(['data' => $ads]);
    }
}
