<?php

namespace Modules\Admin\Http\Controllers;

use Illuminate\Http\Request;
use Modules\Main\Models\City;
use Modules\Post\Models\Post;

use App\Http\Controllers\Controller;
use Modules\Post\Models\PostCategory;
use Illuminate\Support\Facades\Storage;

class AdminPostsController extends Controller
{
    public function index()
    {
        $posts = Post::orderBy('id', 'desc');
        if (!auth()->user()->isAdmin() && auth()->user()->isCityManager())
        {

        }
        $posts = $posts->get();
        return view('admin::posts.index', [
            'posts' => $posts
        ]);
    }

    public function create()
    {
        return view('admin::posts.create', [
            'categories' => PostCategory::cases()
        ]);
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name'       => 'required',
            'category'   => 'required',
            'short_text' => 'max:500',
            'text'       => 'required',
            'imageFile'  => 'required|mimes:jpg,bmp,png'
        ]);
        $path = $request->file('imageFile')->store('posts', ['disk' => 'public']);
        $request['image'] = $path;
        $post = Post::create(
            $request->only(['name', 'short_text', 'text', 'category', 'image'])
        );
        if (array_key_exists('cities', $request->all()) && is_array($request['cities']))
        {
            foreach ($request->cities as $cityId)
            {
                $post->cities()->create([
                    'city_id' => $cityId,
                ]);
            }
        }
        return to_route('admin.posts');
    }

    public function edit(Post $post)
    {
        return view('admin::posts.edit', [
            'categories' => PostCategory::cases(),
            'post'       => $post
        ]);
    }

    public function update(Request $request, Post $post)
    {
        $validated = $request->validate([
            'name'       => 'required',
            'category'   => 'required',
            'short_text' => 'max:500',
            'text'       => 'required',
        ]);

        if ($request->file('imageFile'))
        {
            $path = $request->file('imageFile')->store('posts', ['disk' => 'public']);
            $request['image'] = $path;
        }
        else
        {
            $reuqest['image'] = $post->image;
        }
        $post = $post->update(
            $request->only(['name', 'short_text', 'text', 'category', 'image'])
        );
        return to_route('admin.posts');
    }

    public function delete(Post $post)
    {
        $post->delete();
        return to_route('admin.posts');
    }
}
