<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\SubCategory;
use Illuminate\Http\Request;
use App\Models\Category;
use App\Models\Blog;
use Str;
use Cache;
use App\Models\Translation;
use Stichoza\GoogleTranslate\GoogleTranslate;

class BlogController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        //
        $page_data = [
            'title' => 'Blogs',
            'slug' => 'All Blogs'
        ];

        $page = request()->get('page', 1);
        $limit = request()->get('limit', 10);
        $blogs = Cache::remember('blogs' . $page, 20, function () use ($limit) {
            return Blog::select('id', 'title','slug','feature_image','status')->orderBy('id', 'desc')->paginate($limit);
        });
        return view('admin.pages.blogs.index', get_defined_vars())
            ->with('i', ($page - 1) * 5);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
        $page_data = [
            'title' => 'Blogs',
            'slug' => 'Add New Blog'
        ];
        $categories = Category::pluck('name', 'id');
        return view('admin.pages.blogs.create', get_defined_vars());

    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
        $source = $request->input('source', 'en'); // default English
        $targets = explode(',', $request->input('targets', 'pl'));

        $blog = new Blog;

        if ($request->hasFile('featured_image')) {
            $file = $request->file('featured_image');
            $image = uniqid() . '.' . $file->guessExtension();
            $image_path = $file->move(public_path() . '/admin-assets/images/blogs/', $image);
            $blog->feature_image = $image;

        }
        $blog->category_id = $request->category_id;
        $blog->sub_category_id = $request->sub_category_id;
        $blog->title = $request->title;
        $blog->type = $request->type;
        $blog->status = $request->status;
        $blog->slug = Str::slug($request->title);
        $blog->description = $request->description;
        $blog->meta_title = $request->meta_title;
        $blog->meta_description = $request->meta_description;
        // dd($blog);
        if ($blog->save()) {
             foreach ($targets as $target) {
                    
                    $translator = new GoogleTranslate($target, $source);
                    $successCount = 0;

                    // Translate Blogs (including description)
                    
                    $blog = Blog::Select('blogs.*','categories.name as category')
                                ->leftjoin('categories','categories.id','blogs.category_id')->where('blogs.id',$blog->id)->first(); 
                    
                        try {
                            usleep(500000); // Delay
                            
                            // Translate title
                            $translatedTitle = $translator->translate($blog->title);
                            Translation::setTranslated($target, 'blogs', $blog->id . '_title', $translatedTitle);
                            
                            // Translate description
                            if ($blog->description) {
                                $translatedDescription = $translator->translate($blog->description);
                                Translation::setTranslated($target, 'blogs', $blog->id . '_description', $translatedDescription);
                            }
                            
                            // Translate category if it's a string field
                            if ($blog->category) {
                                $translatedCategory = $translator->translate($blog->category);
                                Translation::setTranslated($target, 'blogs', $blog->id . '_category', $translatedCategory);
                            }
                            
                            
                            $successCount++;
                            
                        } catch (\Exception $e) {
                            \Log::error("     ❌ Failed: {$blog->title}");
                        }
                    
                }
            return redirect()->route('blogs.index')->withSuccess('Blog Added Successfully!');
        } else {
            return redirect()->back()->withError('Something went wrong!');
        }

    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
        $page_data = [
            'title' => 'Blogs',
            'slug' => 'Add New Blog'
        ];
        $blog = Blog::with(['sub_category:id,name','category:id,name'])->where('blogs.id', $id)->first();
        $categories = Category::pluck('name', 'id');
        $subcategories = SubCategory::select('name', 'id')->where('category_id',$blog->category_id)->get();
        // dd($blog);
        return view('admin.pages.blogs.edit', get_defined_vars());
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
         $source = $request->input('source', 'en'); // default English
        $targets = explode(',', $request->input('targets', 'pl'));
        $blog = Blog::find($id);

        if ($request->hasFile('featured_image')) {
            $file = $request->file('featured_image');
            $image = uniqid() . '.' . $file->guessExtension();
            $image_path = $file->move(public_path() . '/admin-assets/images/blogs/', $image);
            $blog->feature_image = $image;

        }
        $blog->category_id = $request->category_id;
        $blog->sub_category_id = $request->sub_category_id;
        $blog->title = $request->title;
        $blog->type = $request->type;
        $blog->status = $request->status;
        $blog->slug = Str::slug($request->title);
        $blog->description = $request->description;
        $blog->meta_title = $request->meta_title;
        $blog->meta_description = $request->meta_description;

        if ($blog->update()) {
             foreach ($targets as $target) {
                    
                    $translator = new GoogleTranslate($target, $source);
                    $successCount = 0;

                    // Translate Blogs (including description)
                    
                    $blog = Blog::Select('blogs.*','categories.name as category')
                                ->leftjoin('categories','categories.id','blogs.category_id')->where('blogs.id',$blog->id)->first(); 
                    
                        try {
                            usleep(500000); // Delay
                            
                            // Translate title
                            $translatedTitle = $translator->translate($blog->title);
                            Translation::setTranslated($target, 'blogs', $blog->id . '_title', $translatedTitle);
                            
                            // Translate description
                            if ($blog->description) {
                                $translatedDescription = $translator->translate($blog->description);
                                Translation::setTranslated($target, 'blogs', $blog->id . '_description', $translatedDescription);
                            }
                            
                            // Translate category if it's a string field
                            if ($blog->category) {
                                $translatedCategory = $translator->translate($blog->category);
                                Translation::setTranslated($target, 'blogs', $blog->id . '_category', $translatedCategory);
                            }
                            
                            
                            $successCount++;
                            
                        } catch (\Exception $e) {
                            \Log::error("     ❌ Failed: {$blog->title}");
                        }
                    
                }
            return redirect()->route('blogs.index')->withSuccess('Blog updated Successfully!');
        } else {
            return redirect()->back()->withError('Something went wrong!');
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
        $blog = Blog::find($id);
        if ($blog->delete()) {

            return redirect()->route('blogs.index')->withSuccess('Blog deleted Successfully!');
        } else {
            return redirect()->back()->withError('Something went wrong!');

        }
    }

    public function subCategoryApi(Request $request){
    	$sub = Subcategory::where('category_id',$request->categoryid)->get();
    	return response()->json(['subcategory' => $sub]);
    }
}
