<?php

namespace App\Http\Resources\Admin;

use App\Helpers\Helper;
use App\Topic;
use Illuminate\Http\Resources\Json\JsonResource;
use ImageCross;

class TopicResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param \Illuminate\Http\Request $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id'               => $this->id,
            'code'             => $this->code,
            'title'            => Helper::filterWords($this->title),
            'thumbnail'        => $this->thumbnail,
            'author'           => $this->author,
            'rank_id'          => $this->rank_id,
            'category_id'      => $this->category_id,
            'category'         => [
                'id'   => isset($this->category) ? $this->category->id : null,
                'name' => isset($this->category) ? $this->category->name : null,
            ],
            'keywords'         => $this->keywords,
            'publishDate'      => $this->rank->created_date,
            'total_comment'    => $this->total_comment,
            'number_of_views'  => $this->number_of_views,
            'seo_robots'       => $this->seo_robots,
            'seo_title'        => $this->seo_title,
            'seo_description'  => $this->seo_description,
            'seo_keywords'     => $this->seo_keywords,
            'is_allow_comment' => $this->is_allow_comment,
            'is_activated'     => $this->is_activated,
            'is_deleted'       => $this->is_deleted,
            'created_at'       => date('Y-m-d H:i:s', strtotime($this->created_at)),
            'updated_at'       => date('Y-m-d H:i:s', strtotime($this->updated_at)),
        ];
    }

    public static function generateCode($length = 6)
    {
        do {
            $key = strtoupper(substr(str_shuffle("010123401234501234567896789501234567896789234567890001234560123456789789123456789123456789012345"), 0, $length));
            $check = Topic::where('code', $key)->count();
        } while ($check > 0);

        return $key;
    }

    public static function createThumb($file, $width = 60, $height = 60)
    {
        try {
            $filePath = public_path('uploads/image/topic');
            $fileName = md5(date('YmdHis') . rand(1, 9999)) . '.jpg';
            $imgCross = ImageCross::make($file)->orientate()->save($filePath . '/' . $fileName);
            $imgCross->resize(60, 60, function ($constraint) {
                $constraint->aspectRatio();
                $constraint->upsize();
            })->save($filePath . '/thumbnail_60x60/' . $fileName);
            return $fileName;
        } catch (\Exception $exception) {
            return "";
        }
    }
}
