<?php

namespace App\Http\Controllers\Backend;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Post;
use App\Block;
use App\Attachment;

class BlocksController extends PostsController
{
    public function index($id)
    {
        $post = Post::findOrFail($id);

        return view('backend.blocks.index', [
            'post' => $post
        ])->with('new', false);
    }

    public function create($id)
    {
        $block = Block::create([
            'post_id' => $id
        ]);
        $block->post()->create([
            'order' => Block::where('post_id', $id)->count() + 1
        ]);

        return back()->with([
            'status' => 'El bloque ha sido agregado',
            'new' => true
        ]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $block = Block::findOrFail($id);
        $block->fill($request->only( 'selector', 'url'))->save();
        $block->post()->update($request->post);

        $this->uploadSingle($request, $block);
        $this->upload($request->file('images'), $block);

        return response()->json([
            'message' => 'El bloque ha sido actualizado',
            'block' => view('backend.partials.block', [
                'block' => $block,
                'type' => $block->parent_post->postable_type == 'App\Plan' ? 'product-block' : null
            ])->render()
        ]);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function delete($id)
    {
        $block = Block::findOrFail($id);
        $block->post->media()->delete();
        $block->post()->delete();
        $block->delete();

        return back()->with('status', 'El bloque ha sido eliminado');
    }
}
