<?php
namespace App\Services\Product\Favorite;

use App\Models\Favorite;
use App\Models\Product;
use App\Services\Auth\User\AccountService;
use App\Services\Response\ResponseService;
use Illuminate\Support\Facades\Auth;

/**
 * Class based Helper to Send Notifications
 */
class FavoriteService
{
    private $product;

    public function __construct(Product $product = null)
    {
        $this->product = $product;
    }

    private function checkRemove($status,$user)
    {
        $fav = Favorite::where('status',$status)->where('user_id',$user->id)->orderBy('id','DESC')->get();
        
        foreach($fav as $row)
        {
            $product= Product::onlyTrashed()->find($row->product_id);
            if($product)
            {
                $row->delete();
            }
        }
    }
    public function favorites($message = '')
    {
        $user = (new AccountService())->getAccount();
        $status = $user['status'];
        $user = $user['user'];
        $this->checkRemove($status,$user);
        $ids = Favorite::where('user_id',$user->id)->where('status',$status)->pluck('product_id')->toArray();
        $products = Product::withDescription()->find($ids);
        $status = 200;
        $content =
            [
                'message' => $message,
                'status' => $status,
                'data' => $products,
            ];
        return $content;
    }

    public function favoriteToggle()
    {
        $user = (new AccountService())->getAccount();
        $status = $user['status'];
        $user = $user['user'];

        $fav = Favorite::where('status',$status)->where('user_id',$user->id)->where('product_id',$this->product->id)->first();

        if($fav)
        {
            $fav->delete();
            $type = false;
        }
        else
        {
            Favorite::create([
                'product_id' => $this->product->id,
                'user_id' => $user->id,
                'status' => $status,
            ]);
            $type = true;
        }
        $count = Favorite::where('status',$status)->where('user_id',$user->id)->count();
        $response = [
            'message'=>__('web.success'),
            'status' => 200,
            'data' => $count,
        ];

        return ResponseService::response($response);
    }

    public function checkFavorite()
    {
        $user = (new AccountService())->getAccount();
        $status = $user['status'];
        $user = $user['user'];
        $favorite = Favorite::where('product_id',$this->product->id)->where('status',$status)->where('user_id',$user? $user->id : null)->first();
        return $favorite ? true : false;
    }


}
