<?php

namespace App\Repositories;

use App\Models\BusinessProductsCart;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Mail\Mailer;


class BusinessProductsCartRepository
{
    public function __construct(
        BusinessProductsCart $businessProductsCart,
        Filesystem $filesystem,
        Mailer $mailer
    ) {
        $this->model = $businessProductsCart;
        $this->file = $filesystem;
        $this->mailer = $mailer;
    }

    public function getById($id)
    {
        return $this->model->where('id', $id)->first();
    }

    public function addProductToCart($productId, $pageId, $community_id = 0, $productsizeid = 0, $productcolorid = 0)
    {
		$product = app('App\Repositories\\BusinessProductsRepository')->getById($productId);		
		
		if($productsizeid==0 || $productcolorid==0){
			if($product){
				if($product->product_category==1){
					$firstRecord = app('App\\Repositories\\BusinessProductsCategoryValuesRepository')->getProductValue($product->id,'liquid-size');
					
					if($firstRecord){
						$productsizeid=$firstRecord->id;					
						$colors_data=app('App\\Repositories\\BusinessProductsCategoryValuesRepository')->getColorsFirstRecords($productId, $firstRecord->value);
						
						if($colors_data){
							$productcolorid=$colors_data->id;
						}
					}
				}elseif($product->product_category==2){
					$firstRecordSize = app('App\\Repositories\\BusinessProductsCategoryValuesRepository')->getProductValue($product->id,'wearable-size');	
					
					if($firstRecordSize){	
						$productsizeid=$firstRecordSize->id;
						$colors_data=app('App\\Repositories\\BusinessProductsCategoryValuesRepository')->getColorsFirstRecords($product->id,$firstRecordSize->value);
						
						if($colors_data){
							$productcolorid=$colors_data->id;
						}
					}
				}
			}	
		}		
		
		if(!$productsizeid){
			$productsizeid=0;
		}
		
		if(!$productcolorid){
			$productcolorid=0;
		}
		
        $userid = \Auth::user()->id;

        $existData = $this->getByProductUserColorSize($productId, $userid, $community_id,$productcolorid,$productsizeid);

        if ($community_id != 0) {
            $canOrder = $this->checkExistingCurrency($userid, $community_id, $pageId);

            if (! $canOrder) {
                return 'null';
            }
        }

        if ($existData) {

            //return 'exist';

            if ($existData->quantity == 3) {
                return 0;
            }
            $cart = $existData;
            $cart->quantity = $existData->quantity + 1;
        } else {
            $cart = $this->model->newInstance();
					
            $cart->productsizeid = $productsizeid;
            $cart->product_color_id = $productcolorid;
            $cart->quantity = 1;
        }
        $cart->product_id = $productId;
        $cart->user_id = $userid;
        $cart->business_id = $pageId;
        $cart->community_id = $community_id;


        $cart->save();

        return $this->getCartCountByBusiness($pageId, $userid, $community_id);
    }

    public function checkExistingCurrency($userid, $community_id, $pageId)
    {
        $cart = $this->model->where('user_id', $userid)->where('community_id', $community_id)->first();

        if ($cart) {
            if ($pageId == $cart->business_id) {
                return true;
            }

            $business = app('App\Repositories\\PageRepository')->findById($cart->business_id);

            $business_new = app('App\Repositories\\PageRepository')->findById($pageId);

            $business_currency = 'USD';
            if ($business and $business->currency) {
                $business_currency = $business->currency;
            }

            $new_business_currency = 'USD';
            if ($business_new and $business_new->currency) {
                $new_business_currency = $business_new->currency;
            }

            if ($business_currency != $new_business_currency) {
                return false;
            }
        }

        return true;
    }

    public function getByProductUser($productId, $userid, $community_id = 0)
    {
        return $this->model->where('product_id', $productId)->where('user_id', $userid)->where('community_id', $community_id)->first();
    }
	
	public function getByProductUserColorSize($productId, $userid, $community_id = 0,$color_id=0,$size_id=0)
    {
        return $this->model->where('productsizeid', $size_id)->where('product_color_id', $color_id)->where('product_id', $productId)->where('user_id', $userid)->where('community_id', $community_id)->first();		 
    }

    public function getCartCountByBusiness($business_id, $userid = null, $community_id = 0)
    {

        $userid = (empty($userid)) ? \Auth::user()->id : $userid;

        if ($business_id) {
            return $this->model->where('business_id', $business_id)->where('user_id', $userid)->where('community_id', $community_id)->sum('quantity');
        } else {
            return $this->model->where('user_id', $userid)->where('community_id', $community_id)->sum('quantity');
        }
        // return $this->model->where('business_id', $business_id)->where('user_id', $userid)->count();
    }

    public function getCartListByBusiness($business_id, $userid = null, $community_id = 0)
    {
        $userid = (empty($userid)) ? \Auth::user()->id : $userid;

        if ($business_id) {
            return $this->model->with('product')->where('business_id', $business_id)->where('user_id', $userid)->where('community_id', $community_id)->get();

        } else {
            return $this->model->with('product')->where('user_id', $userid)->where('community_id', $community_id)->get();
        }
    }

    public function deleteCartItem($cartId, $business_id, $userid = null, $community_id = 0)
    {
        $userid = (empty($userid)) ? \Auth::user()->id : $userid;

        if ($business_id) {
            $this->model->where('business_id', $business_id)->where('user_id', $userid)->where('id', $cartId)->where('community_id', $community_id)->delete();
        } else {
            $this->model->where('user_id', $userid)->where('id', $cartId)->where('community_id', $community_id)->delete();
        }

        return $this->getCartCountByBusiness($business_id, $userid, $community_id);
    }

    public function changeProductCartQty($cartId, $business_id, $qty, $userid = null, $community_id = 0)
    {
        $userid = (empty($userid)) ? \Auth::user()->id : $userid;

        if ($business_id) {
            $this->model->where('business_id', $business_id)->where('user_id', $userid)->where('id', $cartId)->where('community_id', $community_id)->update(['quantity' => $qty]);
        } else {
            $this->model->where('user_id', $userid)->where('id', $cartId)->where('community_id', $community_id)->update(['quantity' => $qty]);
        }

        return $this->getCartCountByBusiness($business_id, $userid, $community_id);
    }

    public function deleteAllCartItem($business_id, $userid = null, $community_id = 0)
    {
        $userid = (empty($userid)) ? \Auth::user()->id : $userid;

        if ($business_id) {
            $this->model->where('community_id', $community_id)->where('business_id', $business_id)->where('user_id', $userid)->delete();
        } else {
            $this->model->where('community_id', $community_id)->where('user_id', $userid)->delete();
        }

        return $this->getCartCountByBusiness($business_id, $userid);
    }

    public function deleteAllGuestCartItem($business_id, $sessionId, $community_id = 0)
    {
        if (! $sessionId) {
            return 0;
        }

        $query = $this->model->where('community_id', $community_id)
            ->where('session_id', $sessionId)
            ->whereNull('user_id');

        if ($business_id) {
            $query->where('business_id', $business_id);
        }

        $query->delete();

        return $this->getGuestCartCountByBusiness($business_id, $sessionId, $community_id);
    }

    public function savePickupDate($date, $business_id, $community_id)
    {

        if ($date) {
            $picked_date = new \DateTime($date);
            $picked_date = date_format($picked_date, 'Y-m-d H:i:s');

            $this->model
                ->where('community_id', '=', $community_id)
                ->where('business_id', '=', $business_id)
                ->update(['order_date_time' => $picked_date]);
        }
    }

    public function deleteCartItemById($cartId, $userid = null)
    {
        if (empty($userid)) {
            if (\Auth::check()) {
                $userid = \Auth::user()->id;
                // Delete by user_id for authenticated users
                $this->model->where('user_id', $userid)->where('id', $cartId)->delete();
            } else {
                // For guest users, delete by cart id only (since we can't rely on user_id)
                $this->model->where('id', $cartId)->delete();
                return true;
            }
        } else {
            // Delete by user_id when userid is provided
            $this->model->where('user_id', $userid)->where('id', $cartId)->delete();
        }
        
        return true;
    }

    public function totalCartCount()
    {
        if (!\Auth::check()) {
            return 0; // Return 0 for guest users
        }
        $userid = \Auth::user()->id;

        return $this->model->where('user_id', $userid)->sum('quantity');
    }

    public function getMyCartCommunity()
    {
        $userid = \Auth::user()->id;

        return $this->model->with('community')->where('user_id', $userid)->groupBy('community_id')->get();
    }

    public function totalCartCountByCommunity($community_id)
    {
        $userid = \Auth::user()->id;

        return $this->model->where('user_id', $userid)->where('community_id', $community_id)->sum('quantity');
    }

    // Guest Cart Methods
        public function addProductToGuestCart($productId, $pageId, $sessionId, $community_id = 0, $productsizeid = 0, $productcolorid = 0)
    {
	
		$product = app('App\Repositories\\BusinessProductsRepository')->getById($productId);		
		
		if($productsizeid==0 || $productcolorid==0){
			if($product){
				if($product->product_category==1){
					$firstRecord = app('App\\Repositories\\BusinessProductsCategoryValuesRepository')->getProductValue($product->id,'liquid-size');
					
					if($firstRecord){
						$productsizeid=$firstRecord->id;					
						$colors_data=app('App\\Repositories\\BusinessProductsCategoryValuesRepository')->getColorsFirstRecords($productId, $firstRecord->value);
						
						if($colors_data){
							$productcolorid=$colors_data->id;
						}
					}
				}elseif($product->product_category==2){
					$firstRecordSize = app('App\\Repositories\\BusinessProductsCategoryValuesRepository')->getProductValue($product->id,'wearable-size');	
					
					if($firstRecordSize){	
						$productsizeid=$firstRecordSize->id;
						$colors_data=app('App\\Repositories\\BusinessProductsCategoryValuesRepository')->getColorsFirstRecords($product->id,$firstRecordSize->value);
						
						if($colors_data){
							$productcolorid=$colors_data->id;
						}
					}
				}
			}	
		}		
		
		if(!$productsizeid){
			$productsizeid=0;
		}
		
		if(!$productcolorid){
			$productcolorid=0;
		}
	
        $existData = $this->getByProductSession($productId, $sessionId, $community_id,$productcolorid,$productsizeid);

        if ($community_id != 0) {
            $canOrder = $this->checkExistingCurrencyForGuest($sessionId, $community_id, $pageId);

            if (!$canOrder) {
                return 'null';
            }
        }

        if ($existData) {
            if ($existData->quantity == 3) {
                return 0;
            }
            $cart = $existData;
            $cart->quantity = $existData->quantity + 1;
        } else {
            $cart = $this->model->newInstance();
            $cart->quantity = 1;			
			
        	$cart->productsizeid = $productsizeid;
       		$cart->product_color_id = $productcolorid;
        }
        
        $cart->product_id = $productId;
        $cart->user_id = null; // Guest cart
        $cart->session_id = $sessionId;
        $cart->business_id = $pageId;
        $cart->community_id = $community_id;

        $cart->save();

        return $this->getGuestCartCountByBusiness($pageId, $sessionId, $community_id);
    }
	
    public function getByProductSession($productId, $sessionId, $community_id = 0,$color_id=0,$size_id=0)
    {
        return $this->model->where('productsizeid', $size_id)->where('product_color_id', $color_id)->where('product_id', $productId)->where('session_id', $sessionId)->where('community_id', $community_id)->first();
    }

    public function checkExistingCurrencyForGuest($sessionId, $community_id, $pageId)
    {
        $cart = $this->model->where('session_id', $sessionId)->where('community_id', $community_id)->first();

        if ($cart) {
            if ($pageId == $cart->business_id) {
                return true;
            }

            $business = app('App\Repositories\\PageRepository')->findById($cart->business_id);
            $business_new = app('App\Repositories\\PageRepository')->findById($pageId);

            $business_currency = 'USD';
            if ($business and $business->currency) {
                $business_currency = $business->currency;
            }

            $new_business_currency = 'USD';
            if ($business_new and $business_new->currency) {
                $new_business_currency = $business_new->currency;
            }

            if ($business_currency != $new_business_currency) {
                return false;
            }
        }

        return true;
    }

    public function getGuestCartCountByBusiness($business_id, $sessionId, $community_id = 0)
    {
        if ($business_id) {
            return $this->model->where('business_id', $business_id)->where('session_id', $sessionId)->where('community_id', $community_id)->sum('quantity');
        } else {
            return $this->model->where('session_id', $sessionId)->where('community_id', $community_id)->sum('quantity');
        }
    }

    public function getGuestCartListByBusiness($business_id, $sessionId, $community_id = 0)
    {
        if ($business_id) {
            return $this->model->with('product')->where('business_id', $business_id)->where('session_id', $sessionId)->where('community_id', $community_id)->get();
        } else {
            return $this->model->with('product')->where('session_id', $sessionId)->where('community_id', $community_id)->get();
        }
    }

    public function deleteGuestCartItem($cartId, $businessId, $sessionId, $community_id = 0)
    {
        $this->model->where('id', $cartId)->where('session_id', $sessionId)->delete();
        return $this->getGuestCartCountByBusiness($businessId, $sessionId, $community_id);
    }

    public function changeGuestProductCartQty($cartId, $businessId, $qty, $sessionId, $community_id = 0)
    {
        $cart = $this->model->where('id', $cartId)->where('session_id', $sessionId)->first();
        
        if ($cart) {
            $cart->quantity = $qty;
            $cart->save();
        }
        
        return $this->getGuestCartCountByBusiness($businessId, $sessionId, $community_id);
    }

    public function mergeGuestCartWithUser($sessionId, $userId)
    {
        $guestCartItems = $this->model->where('session_id', $sessionId)->whereNull('user_id')->get();
        
        foreach ($guestCartItems as $guestItem) {
            // Check if user already has this product in cart
						
            $existingUserCart = $this->getByProductUserColorSize($guestItem->product_id, $userId, $guestItem->community_id, $guestItem->product_color_id, $guestItem->productsizeid);
            
            if ($existingUserCart) {
                // Merge quantities (max 5)
                $newQuantity = min(5, $existingUserCart->quantity + $guestItem->quantity);
                $existingUserCart->quantity = $newQuantity;
                $existingUserCart->save();
                
                // Delete guest cart item
                $guestItem->delete();
            } else {
                // Convert guest cart to user cart
                $guestItem->user_id = $userId;
                $guestItem->session_id = null;
                $guestItem->save();
            }
        }
        
        return ['status' => 'success', 'message' => 'Guest cart merged successfully'];
    }
}
