<?php

namespace App\Repositories\Admin;

use App\Models\Blog;
use App\Repositories\Interfaces\Admin\BlogInterface;
use Carbon\Carbon;
use App\Traits\ImageTrait;
use Illuminate\Http\UploadedFile;

class BlogRepositories implements BlogInterface
{
    use ImageTrait;

    public function all()
    {
        return Blog::get();
    }

    public function store($request)
    {
        try {
            if (isset($request['image']) && $request['image'] instanceof UploadedFile) {
                $requestImage = $request['image'];
                $response = $this->saveImage($requestImage, '_blog_');
                $thumbnail = $response['images'];
            }
            $data = [
                'title' => $request['title'],
                'slug' => $request['slug'],
                'status' => $request['status'] ?? 0,
                'is_top' => $request['is_top'] ?? 0,
                'category_id' => $request['category_id'],
                'image' => isset($thumbnail) ? json_encode($thumbnail) : '',
                'seo_title' => $request['seo_title'],
                'description' => $request['description'],
                'meta_description' => $request['meta_description'],
                'focus_keyword' => $request['focus_keyword'],
                'tags' => $request['tags'],
                'created_at' => Carbon::now(),
                'updated_at' => Carbon::now(),
            ];
            return Blog::create($data);
        } catch (\Exception $e) {
            return false;
        }
    }

    public function update($request, $id)
    {
        try {
            $blog = Blog::where('id', $id)->first();
            if (isset($request['image']) && $request['image'] instanceof UploadedFile) {
                $this->imageDelete($id, 'blog', 'image');
                $requestImage = $request['image'];
                $response = $this->saveImage($requestImage, '_blog_');
                $thumbnail = $response['images'];
            }
            $data = [
                'title' => $request['title'],
                'slug' => $request['slug'],
                'status' => $request['status'] ?? 0,
                'is_top' => $request['is_top'] ?? 0,
                'category_id' => $request['category_id'],
                'image' => isset($thumbnail) ? json_encode($thumbnail) : $blog->image,
                'seo_title' => $request['seo_title'],
                'meta_description' => $request['meta_description'],
                'description' => $request['description'],
                'focus_keyword' => $request['focus_keyword'],
                'tags' => $request['tags'],
                'updated_at' => Carbon::now(),
            ];
            return Blog::where('id', $id)->update($data);
        } catch (\Exception $e) {
            return false;
        }
    }
}