<?php

namespace App\Http\Controllers;

use App\Models\Anuncio;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class AnuncioController extends Controller
{
    public function index()
    {
        $anuncios = Anuncio::with('author')->latest()->paginate(15);
        return view('anuncio.index', compact('anuncios'));
    }

    public function create()
    {
        return view('anuncio.create', [
            'types' => Anuncio::TYPES,
            'roles' => Anuncio::ROLES,
        ]);
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'title'      => 'required|string|max:200',
            'body'       => 'nullable|string|max:3000',
            'image'      => 'nullable|image|max:51200',
            'type'       => 'required|in:info,promocion,mantenimiento,aviso',
            'audience'   => 'required|array|min:1',
            'audience.*' => 'string',
            'expires_at' => 'nullable|date|after:now',
            'active'     => 'boolean',
        ]);

        $data['user_id']    = auth()->id();
        $data['active']     = $request->boolean('active', true);
        $data['expires_at'] = $request->expires_at ?: null;

        if ($request->hasFile('image')) {
            $data['image_path'] = $request->file('image')->store('anuncios', 'public');
        }

        unset($data['image']);
        Anuncio::create($data);

        return redirect()->route('anuncio.index')->with('success', 'Anuncio creado correctamente.');
    }

    public function edit(Anuncio $anuncio)
    {
        return view('anuncio.edit', [
            'anuncio' => $anuncio,
            'types'   => Anuncio::TYPES,
            'roles'   => Anuncio::ROLES,
        ]);
    }

    public function update(Request $request, Anuncio $anuncio)
    {
        $data = $request->validate([
            'title'      => 'required|string|max:200',
            'body'       => 'nullable|string|max:3000',
            'image'      => 'nullable|image|max:51200',
            'type'       => 'required|in:info,promocion,mantenimiento,aviso',
            'audience'   => 'required|array|min:1',
            'audience.*' => 'string',
            'expires_at' => 'nullable|date',
            'active'     => 'boolean',
        ]);

        $data['active']     = $request->boolean('active', true);
        $data['expires_at'] = $request->expires_at ?: null;

        if ($request->hasFile('image')) {
            if ($anuncio->image_path) {
                Storage::disk('public')->delete($anuncio->image_path);
            }
            $data['image_path'] = $request->file('image')->store('anuncios', 'public');
        } elseif ($request->boolean('remove_image') && $anuncio->image_path) {
            Storage::disk('public')->delete($anuncio->image_path);
            $data['image_path'] = null;
        }

        unset($data['image']);
        $anuncio->update($data);

        return redirect()->route('anuncio.index')->with('success', 'Anuncio actualizado.');
    }

    public function destroy(Anuncio $anuncio)
    {
        if ($anuncio->image_path) {
            Storage::disk('public')->delete($anuncio->image_path);
        }
        $anuncio->delete();

        return back()->with('success', 'Anuncio eliminado.');
    }

    public function toggleActive(Anuncio $anuncio)
    {
        $anuncio->update(['active' => !$anuncio->active]);
        return back()->with('success', $anuncio->active ? 'Anuncio activado.' : 'Anuncio desactivado.');
    }
}
