<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Category;
use App\Models\Coupon;
use App\Models\Event;
use App\Models\Store;
use Str;
use Cache;
use App\Models\Translation;
use Stichoza\GoogleTranslate\GoogleTranslate;

class StoreController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
        $page_data = [
            'title' => 'Stores',
            'slug' => 'All Stores'
        ];
        $page = request()->get('page', 1);
        $limit = request()->get('limit', 10);
        $stores = Store::select('stores.id','stores.name','stores.feature_image','stores.url','stores.category_id','stores.event_id')->with(['category:id,name', 'event:id,name'])
            ->orderby('updated_at', 'desc')->get();
       
        //   dd($stores);
        return view('admin.pages.stores.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' => 'Stores',
            'slug' => 'Add New Store'
        ];
        $categories = Category::pluck('name','id');
        $events = Event::pluck('name','id');
        return view('admin.pages.stores.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'));
        // dd($request->all());
        $store = new Store;

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

            $store->category_id = $request->category_id;
            $store->event_id = $request->event_id;
            $store->name = $request->name;
            $store->slug = Str::slug($request->name);
            $store->description = $request->description;
            $store->url = $request->url;
            $store->blog_description = $request->blog_description;
            $store->meta_title = $request->meta_title;
            $store->meta_description = $request->meta_description;
            $store->feature_image = $image;

            if ($store->save()) {
                foreach ($targets as $target) {
                    \Log::info("🔤 Translating to {$target}...");
                    
                    $translator = new GoogleTranslate($target, $source);
                    $successCount = 0;

                    // Translate Blogs (including description)
                    \Log::info("   📝 Translating blogs...");
                    $store = Store::find($store->id);
                    
                        try {
                    usleep(500000); // Delay
                    
                    $translatedName = $translator->translate($store->name);
                    Translation::setTranslated($target, 'stores', $store->id . '_name', $translatedName);
                    
                    if($store->description){
                        $translatedDescription = $translator->translate($store->description);
                        Translation::setTranslated($target, 'stores', $store->id . '_description', $translatedDescription);
                    }
                    
                   
                    
                    
                    $successCount++;
                    
                } catch (\Exception $e) {
                    \Log::error("     ❌ Failed: {$store->name}");
                }
                    
                }
                return redirect()->route('stores.index')->withSuccess('Store Added Successfully');
            } else {
                return back()->withError('Something went wrong!');
            }
        } else {
            return back()->withError('Please Upload Store Media!');
        }
    }

    /**
     * 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' => 'Stores',
            'slug' => 'Edit Store'
        ];
        $store = Store::with(['category:id,name', 'event:id,name'])
            ->where('stores.id', $id)
            ->first();
        $categories = Category::pluck('name','id');
        $events = Event::pluck('name','id');
        return view('admin.pages.stores.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'));
        $store = Store::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/stores/', $image);
            $store->feature_image = $image;

        }
        $store->category_id = $request->category_id;
        $store->event_id = $request->event_id;
        $store->name = $request->name;
        $store->slug = Str::slug($request->name);
        $store->description = $request->description;
        $store->url = $request->url;
        $store->blog_description = $request->blog_description;
        $store->meta_title = $request->meta_title;
        $store->meta_description = $request->meta_description;

        if ($store->save()) {
            foreach ($targets as $target) {
                    \Log::info("🔤 Translating to {$target}...");
                    
                    $translator = new GoogleTranslate($target, $source);
                    $successCount = 0;

                    // Translate Blogs (including description)
                    \Log::info("   📝 Translating blogs...");
                    $store = Store::find($store->id);
                    
                        try {
                    usleep(500000); // Delay
                    
                    $translatedName = $translator->translate($store->name);
                    Translation::setTranslated($target, 'stores', $store->id . '_name', $translatedName);
                    
                    if($store->description){
                        $translatedDescription = $translator->translate($store->description);
                        Translation::setTranslated($target, 'stores', $store->id . '_description', $translatedDescription);
                    }
                    
                   
                    
                    
                    $successCount++;
                    
                } catch (\Exception $e) {
                    \Log::error("     ❌ Failed: {$store->name}");
                }
                    
                }
            return redirect()->route('stores.index')->withSuccess('Store Updated Successfully!');
        } else {
            return back()->withError('Something went wrong!');
        }
    }

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

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

    public function coupons($id)
    {
        //  dd($id);
        $page_data = [
            'title' => 'Store Coupons',
            'slug' => 'Store Coupons'
        ];
        $query = Coupon::where('store_id', $id)->orderByRaw("CAST(sorting_order as UNSIGNED) ASC")->get();
        // dd($query);
        return view('admin.pages.stores.couponlist', get_defined_vars());
    }

    public function update_order(Request $request)
    {

        $query = Coupon::where('store_id', $request->store_id)->orderby('sorting_order', 'asc')->get();
        //  dd($query);
        $count = 0;
        foreach ($request->item as $row) {
            // $arr[] = $request->item[$count];
            $coupon = Coupon::where('id', $row)->first();
            $coupon->sorting_order = $count;
            $coupon->save();
            $count++;
        }

        if($coupon){
            return response()->json(['data' => $coupon, 'success' => true]);
        }else{
            return response()->json(['data' => $coupon, 'success' => false]);
        }
        // if ($coupon) {

        //     return back()->with('success', 'Coupons Sorted successfully.');

        // } else {
        //     return back()->with('error', 'Something went wrong!');

        // }
    }
}
