<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use App\Models\Cart;
use App\Models\Product;
use App\Models\ProductTranslation;

class CartAPIController extends Controller
{
    private $language;
    public function __construct(Request $request)
    {
        parent::__construct();
        $this->request = $request;
        $this->language = $request->header('lang-code') && $request->header('lang-code') != '' ? $request->header('lang-code') : 'en';
    }

    public function addtoCart(Request $request)
    {
        try{
            $post = $request->all();
            $user_id = 0;            
            if($request->userAuthData){
                $user_id = $request->userAuthData->user_id;
            }
            $cartItemExist = Cart::where('user_id',$user_id)->where('product_id',$post['product_id'])->first();
            $product =  Product::where('id',$post['product_id'])->first();
            if (!$product) {
               return $this->sendError('Product not found', 401);
            }

            $price = ($product->discount_price>0)?$product->discount_price:$product->price;
            $total_amount = $post['quantity'] * $price;
            $total_delivery_amount = $total_amount * count($post['delivery_dates']);

            for ($i=0; $i < count($post['delivery_dates']); $i++) { 
                $post['delivery_dates'][$i] = date("Y-m-d H:i:s",strtotime($post['delivery_dates'][$i]));
            }

            $delivery_dates = implode(",",$post['delivery_dates']);
            $days = implode(",",$post['days']);
            $inject = array(
                "user_id" => $user_id,
                "product_id" => $post['product_id'],
                'quantity' =>$post['quantity'],
                "per_item_amount" => $price,
                'per_delivery_amount' => $total_amount,
                'total_delivery_amount' => $total_delivery_amount,
                "no_of_delivery" => count($post['delivery_dates']),
                "days" => $days,
                "delivery_dates" => $delivery_dates,
                'start_date' => date("Y-m-d",strtotime($product['start_date'])),
                'end_date' => date("Y-m-d",strtotime($product['end_date'])),
                "order_frequency" => $post['order_frequency']
            );

            if($cartItemExist){
                $inject['updated_at'] = date('Y-m-d h:i:s');
                Cart::where('id',$cartItemExist->id)->update($inject);
                $id = $cartItemExist->id;
            }else{
                $inject['created_at'] = date('Y-m-d h:i:s');
                $id = Cart::insertGetId($inject);
            }

            $response = $this->getUserCartProduct($user_id);
            return $this->sendResponse($response, 'Carts retrieved successfully');
        }catch(RepositoryException $e){
            return $this->sendError($e->getMessage());
        }
    }


    public function bulkAddtoCart(Request $request)
    {
        try{
            $post = $request->all();
            $user_id = 0;            
            if($request->userAuthData){
                $user_id = $request->userAuthData->user_id;
            }

            Cart::where('user_id',$user_id)->delete();
            $products = $post['products'];
            foreach ($products as $product) {
                $product = (array)$product;
                $checkProduct =  Product::where('id',$product['product_id'])->first();
                if ($checkProduct) {
                    $price = ($checkProduct->discount_price>0)?$checkProduct->discount_price:$checkProduct->price;
                    $total_amount = $product['quantity'] * $price;
                    $total_delivery_amount = $total_amount * count($product['delivery_dates']);

                    for ($i=0; $i < count($product['delivery_dates']); $i++) { 
                        $product['delivery_dates'][$i] = date("Y-m-d H:i:s",strtotime($product['delivery_dates'][$i]));
                    }

                    $delivery_dates = implode(",",$product['delivery_dates']);
                    $days = implode(",",$product['days']);

                    $inject = array(
                        "user_id" => $user_id,
                        "product_id" => $product['product_id'],
                        'quantity' =>$product['quantity'],
                        "per_item_amount" => $price,
                        'per_delivery_amount' => $total_amount,
                        'total_delivery_amount' => $total_delivery_amount,
                        "no_of_delivery" => count($product['delivery_dates']),
                        "days" => $days,
                        "delivery_dates" => $delivery_dates,
                        "order_frequency" => $product['order_frequency'],
                        'start_date' => date("Y-m-d",strtotime($product['start_date'])),
                        'end_date' => date("Y-m-d",strtotime($product['end_date'])),
                        'created_at'=>date('Y-m-d h:i:s')
                    );
                    Cart::insertGetId($inject);
                }
            }
            $response = $this->getUserCartProduct($user_id);
            return $this->sendResponse($response, 'Carts retrieved successfully');
        }catch(RepositoryException $e){
            return $this->sendError($e->getMessage());
        }
    }

    public function getCartData(Request $request)
    {


        echo "jkmngdkfmg";
        // try{
        //     $post = $request->all();
        //     $user_id = 0;            
        //     if($request->userAuthData){
        //         $user_id = $request->userAuthData->user_id;
        //     }
            
        //     $response = $this->getUserCartProduct($user_id);
        //     return $this->sendResponse($response, 'Carts retrieved successfully');
        // }catch(RepositoryException $e){
        //     return $this->sendError($e->getMessage());
        // }
    }

    public function deleteitemCart(Request $request)
    {
        try{
            $post = $request->all();

            if (!empty($post)) {
                Cart::where('id',$post['cart_id'])->delete();
                return $this->sendResponse('', 'Item removed');
            }else{
                return $this->sendError('Something went wrong', 401);
            }
        }catch(RepositoryException $e){
            return $this->sendError($e->getMessage());
        }
    }

    public function count(Request $request)
    {
        try{
            $post = $request->all();
            $user_id = 0;            
            if($request->userAuthData){
                $user_id = $request->userAuthData->user_id;
            }
            if ($user_id) {
                $cartData = Cart::where('user_id',$user_id)->count();
                return $this->sendResponse($cartData, 'Carts retrieved successfully');
            }else{
                return $this->sendError('User not found', 401);
            }

        }catch(RepositoryException $e){
            return $this->sendError($e->getMessage());
        }        
    }

    private function getUserCartProduct($user_id){
        $response = array();
        $cartData = Cart::where('user_id',$user_id)->with('product')->get();
        foreach($cartData as $cart){
            if($cart->product){
                $translated_data = ProductTranslation::where('lang_code',$this->language)->where('product_id',$cart->product_id)->first();
                if($translated_data){
                    if($translated_data->name!=''){
                        $cart->product->name = $translated_data->name;
                    }
                    if($translated_data->description!=''){
                        $cart->product->description = $translated_data->description;
                    }
                }
                array_push($response, $cart);
            }else{
                Cart::where('user_id',$cart->id)->delete();
            }
        }
        return $response;
    }
}
