<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\NewspaperPage;
use App\Models\Hotspot;
use Illuminate\Http\Request;

class HotspotController extends Controller
{
    public function index(NewspaperPage $page)
    {
        $page->load('hotspots', 'newspaper');
        return view('admin.hotspots.index', compact('page'));
    }

    public function store(Request $request, NewspaperPage $page)
    {
        $data = $request->validate([
            'title' => 'nullable|string|max:255',
            'x_percent' => 'required|numeric|min:0|max:100',
            'y_percent' => 'required|numeric|min:0|max:100',
            'width_percent' => 'required|numeric|min:1|max:100',
            'height_percent' => 'required|numeric|min:1|max:100',
            'link_type' => 'required|in:url,page,anchor',
            'link_value' => 'nullable|string|max:500',
            'is_active' => 'boolean',
        ]);

        $data['newspaper_page_id'] = $page->id;
        $data['is_active'] = $request->boolean('is_active', true);

        $hotspot = Hotspot::create($data);

        if ($request->expectsJson()) {
            return response()->json(['success' => true, 'hotspot' => $hotspot]);
        }

        return redirect()->route('admin.hotspots.index', $page)
            ->with('success', 'Hotspot added.');
    }

    public function update(Request $request, Hotspot $hotspot)
    {
        $data = $request->validate([
            'title' => 'nullable|string|max:255',
            'x_percent' => 'required|numeric|min:0|max:100',
            'y_percent' => 'required|numeric|min:0|max:100',
            'width_percent' => 'required|numeric|min:1|max:100',
            'height_percent' => 'required|numeric|min:1|max:100',
            'link_type' => 'required|in:url,page,anchor',
            'link_value' => 'nullable|string|max:500',
            'is_active' => 'boolean',
        ]);

        $data['is_active'] = $request->boolean('is_active', true);
        $hotspot->update($data);

        if ($request->expectsJson()) {
            return response()->json(['success' => true]);
        }

        return redirect()->route('admin.hotspots.index', $hotspot->page)
            ->with('success', 'Hotspot updated.');
    }

    public function destroy(Hotspot $hotspot)
    {
        $page = $hotspot->page;
        $hotspot->delete();

        return redirect()->route('admin.hotspots.index', $page)
            ->with('success', 'Hotspot deleted.');
    }
}
