<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Gallery;
use App\Models\News;
use App\Models\Setting;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Intervention\Image\Facades\Image;

class AiController extends Controller
{
    public function index()
    {
        $keys = [
            'aiApiKey','noFaq'
        ];
        $data = [];
        foreach ($keys as $key) {
            $data[$key] = Setting::where('key' , $key)->value('value');
        }
        return view('admin.ai.index',$data);
    }
    public function aiStore(Request $request)
    {
        $array = [
            'aiApiKey','noFaq'
        ];
        foreach ($array as $key) {
            $value = $request->$key === 'on' ? 1 : $request->$key;
            Setting::where('key', $key)->update(['value' => $value]);
        }
        return redirect()->back()->with([
            'message' => 'اطلاعات ثبت شد'
        ]);
    }
    public function image()
    {
        return view('admin.ai.image');
    }
    public function imageS(Request $request)
    {
        return User::sendMakeImage($request->body);
    }
    public function imageC(Request $request)
    {
        $year = Carbon::now()->year;
        $time = time();
        $path = $_SERVER['DOCUMENT_ROOT'] . '/upload/image/' . $year . '/';
        $url = '/upload/image/' . $year . '/';
        $img = Image::make($request->image)->save('upload/image/' . $year . '/' . $time . '.' . 'jpg', 100, 'jpg');
        $sizefile = $img->filesize() / 1000;
        if ($sizefile > 1000) {
            $size = round($sizefile / 1000, 2) . 'mb';
        } else {
            $size = round($sizefile) . 'kb';
        }
        $image = Gallery::create([
            'name' => $time . '.' . 'jpg',
            'size' => $size,
            'type' => 'jpg',
            'user_id' => auth()->user()->id,
            'url' => $url . $time . '.' . 'jpg',
            'path' => $path . $time . '.' . 'jpg',
        ]);
        return 'done';
    }
    public function blog()
    {
        return view('admin.ai.blog');
    }
    public function blogS(Request $request)
    {
        return User::sendMakeBlog($request->body);
    }
    public function blogC(Request $request){
        return News::create([
            'title' => $request->body,
            'suggest' => 1,
            'status' => 0,
            'time' => 10,
            'image' => '',
            'titleSeo' => $request->body,
            'bodySeo' => $request->body2,
            'video' => null,
            'keyword' => null,
            'imageAlt' => null,
            'language' => 'fa',
            'user_id' => auth()->user()->id,
            'body' => $request->body2,
        ]);
    }
}
