<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Portada;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class PortadaController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $portadas = Portada::orderBy('orden')->get();
        return view('admin.portadas.index',compact('portadas'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return view('admin.portadas.create');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $data=$request->validate([
            'imagen' => 'required|image|max:1024',
            'titulo' => 'required|string|max:255',
            'inicio' => 'required|date',
            'fin' => 'nullable|date|after_or_equal:inicio',
            'estado' => 'required|boolean',
        ]);

        $data['dir_imagen']= Storage::put('portadas', $data['imagen']);

        $portada= Portada::create($data);

        session()->flash('swal',[
            'icon'=> 'success',
            'title'=> 'Realizado',
            'text'=> 'Portada creada correctamente.'
        ]);
        return redirect()->route('admin.portadas.edit', $portada);
    }

    /**
     * Display the specified resource.
     */
    public function show(Portada $portada)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Portada $portada)
    {
        return view('admin.portadas.edit', compact('portada'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Portada $portada)
    {
        $data=$request->validate([
            'imagen' => 'nullable|image|max:1024',
            'titulo' => 'required|string|max:255',
            'inicio' => 'required|date',
            'fin' => 'nullable|date|after_or_equal:inicio',
            'estado' => 'required|boolean',
        ]);

        if( isset($data['imagen'])){
            Storage::delete($portada->dir_imagen);
            $data['dir_imagen']=Storage::put('portadas', $data['imagen']);
        }

        $portada->update($data);

        session()->flash('swal',[
            'icon'=> 'success',
            'title'=> 'Realizado',
            'text'=> 'Portada se actualizó correctamente.'
        ]);
        return redirect()->route('admin.portadas.edit', $portada);

    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Portada $portada)
    {
        //
    }
}
