<?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\Store;
use App\Models\Translation;
use Stichoza\GoogleTranslate\GoogleTranslate;
use Cache;

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

        $page = request()->get('page', 1);
        $limit = request()->get('limit', 10);
        $coupons = Cache::remember('coupons' . $page, 20, function () use ($limit) {
            return Coupon::select('coupons.id', 'coupons.title', 'coupons.url', 'coupons.code', 'coupons.store_id')->with('store:id,name,feature_image')
                ->orderby('coupons.id', 'desc')->get();
        });
        return view('admin.pages.coupons.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' => 'Coupons',
            'slug' => 'Add New Coupon'
        ];
        $stores = Store::pluck('name', 'id');
        // dd($stores);
        return view('admin.pages.coupons.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', 'en-US','pl'));
        $coupon = new Coupon;
        // $splitDate = explode(' - ', $request->expire);

        // $startdate = Str::replaceArray('/',['-','-'],$splitDate[0]);
        // $enddate = Str::replaceArray('/',['-','-'],$splitDate[1]);

        $coupon->title = $request->title;
        $coupon->description = $request->description;
        $coupon->code = $request->code;
        $coupon->type = $request->type;
        $coupon->is_exclusive = $request->is_exclusive;
        $coupon->total_use = $request->total_use;
        $coupon->url = $request->url;
        $coupon->status = $request->status;
        $coupon->category_id = $request->category_id;
        $coupon->store_id = $request->store_id;
        $coupon->start_date = $request->start_date;
        $coupon->end_date = $request->end_date;


        if ($coupon->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...");
                    $coupon = Coupon::find($coupon->id);
                    
                        try {
                    usleep(500000); // Delay
                    
                   $translatedName = $translator->translate($coupon->title);
                    Translation::setTranslated($target, 'coupons', $coupon->id . '_title', $translatedName);

                    if($coupon->description){
                        $translatedDescription = $translator->translate($coupon->description);
                        Translation::setTranslated($target, 'coupons', $coupon->id . '_description', $translatedDescription);
                    }

                    if($coupon->code){
                        $translatedCode = $translator->translate($coupon->code);
                        Translation::setTranslated($target, 'coupons', $coupon->id . '_code', $translatedCode);
                    }

                    if($coupon->type){
                        $translatedType = $translator->translate($coupon->type);
                        Translation::setTranslated($target, 'coupons', $coupon->id . '_type', $translatedType);
                    }

                    
                    $successCount++;
                    
                } catch (\Exception $e) {
                    \Log::error("     ❌ Failed: {$coupon->title}");
                }
                    
                }
            return redirect()->route('coupons.index')->with('success', 'Coupon Added Successfully!');
        } else {
            return back()->with('error', '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' => 'Coupons',
            'slug' => 'Edit Coupon'
        ];
        $coupon = Coupon::with('store:id,name')
            ->where('coupons.id', $id)->first();
        $stores = Store::pluck('name', 'id');

        return view('admin.pages.coupons.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', 'en-US','pl'));
        $coupon = Coupon::find($id);
        // $splitDate = explode(' - ', $request->expire);

        // $startdate = Str::replaceArray('/',['-','-'],$splitDate[0]);
        // $enddate = Str::replaceArray('/',['-','-'],$splitDate[1]);
        // dd($request->all());
        $coupon->title = $request->title;
        $coupon->description = $request->description;
        $coupon->code = $request->code;
        $coupon->type = $request->type;
        $coupon->is_exclusive = $request->is_exclusive;
        $coupon->total_use = $request->total_use;
        $coupon->url = $request->url;
        $coupon->status = $request->status;
        $coupon->category_id = $request->category_id;
        $coupon->store_id = $request->store_id;
        $coupon->start_date = $request->start_date;
        $coupon->end_date = $request->end_date;


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

                    // Translate Blogs (including description)
                    \Log::info("   📝 Translating blogs...");
                    $coupon = Coupon::find($coupon->id);
                    
                        try {
                    usleep(500000); // Delay
                    
                   $translatedName = $translator->translate($coupon->title);
                    Translation::setTranslated($target, 'coupons', $coupon->id . '_title', $translatedName);

                    if($coupon->description){
                        $translatedDescription = $translator->translate($coupon->description);
                        Translation::setTranslated($target, 'coupons', $coupon->id . '_description', $translatedDescription);
                    }

                    if($coupon->code){
                        $translatedCode = $translator->translate($coupon->code);
                        Translation::setTranslated($target, 'coupons', $coupon->id . '_code', $translatedCode);
                    }

                    if($coupon->type){
                        $translatedType = $translator->translate($coupon->type);
                        Translation::setTranslated($target, 'coupons', $coupon->id . '_type', $translatedType);
                    }

                    
                    $successCount++;
                    
                } catch (\Exception $e) {
                    \Log::error("     ❌ Failed: {$coupon->title}");
                }
                    
                }
            return redirect()->route('coupons.index')->with('success', 'Coupon Updated Successfully!');
        } else {
            return back()->with('error', 'Something went wrong');
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
        $coupon = Coupon::find($id);
        if ($coupon->delete()) {
            return back()->with('success', 'Coupon Deleted Successfully!');
        } else {
            return back()->with('error', 'Something went wrong!');
        }
    }

    public function check_sorting_order(Request $request)
    {
        $check = Coupon::where('store_id', $request->store_id)
            ->where('sorting_order', $request->sorting_order)
            ->first();
        if (empty($check)) {
            return response()->json(['data' => null, 'message' => 'Correct Number', 'success' => true]);
        } else {
            return response()->json(['data' => $check, 'message' => 'Already Taken', 'success' => false]);
        }
    }
}