<?php

namespace App\Http\Controllers\Frontend;

use Session;
use App\Models\User;
use App\Models\Product;
use App\Models\Variant;
use Illuminate\Http\Request;
use App\Models\ProductVariant;
use App\Models\SiteConfiguration;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Gloudemans\Shoppingcart\Facades\Cart;
use App\Traits\CalculateProductSalePriceTrait;

class CheckOutController extends Controller
{
    use CalculateProductSalePriceTrait;
    public function index(Request $request)
    {
        $cart_sub_total = Cart::subtotal();
        $site_configuration =  SiteConfiguration::select('template_id')->first();
        $template = 'template' . $site_configuration->template_id;

        $delivery_charges = DB::table('delivery_charges')->where('status', 1)->select('id', 'name', 'delivery_charge')->get();
        $setting = SiteConfiguration::first();
        $cities = collect();
        $sub_cities = collect();

        if ($setting->show_city_sub_city == 1) {
            $cities = DB::table('cities')->select('id', 'name', 'delivery_charge')->where('status', 1)->get();
        }

        $cart_sub_total = Cart::subtotal();
        $cartItems = Cart::content()->values();
        $has_free_delivery = $cartItems->contains(function ($item) {
            return $item->options->is_free_delivery == 1;
        });
        $data = [
            'delivery_charges' => $delivery_charges,
            'cart_sub_total' => $cart_sub_total,
            'setting' => $setting,
            'cities' => $cities,
            'has_free_delivery' => $has_free_delivery ?? 0,
            'sub_cities' => $sub_cities,
        ];

        $cart_count = Cart::count();

        if ($cart_count > 0) {
            return view("frontend.pages.checkout.$template", $data);
        } else {

            $product = Product::with(['category:id,name,status', 'subCategory:id,name', 'subSubCategory:id,name'])
                ->select('id', 'slug', 'category_id', 'sub_category_id', 'sub_sub_category_id', 'name', 'stock', 'is_free_delivery', 'thumbnail_img', 'product_code', 'sale_price', 'discount', 'price')
                ->where('id', $request->product)
                ->firstOrFail();

            $product_sale_price = $this->calculateSalePrice($request, $product);

            $cart = new CartController();
            $cart->cartAdd($product, $request, $product_sale_price);
            session()->save();
            usleep(500000);

            return view("frontend.pages.checkout.$template", $data);
        }
    }
    public function getSubCity(Request $request)
    {
        $subcitys = DB::table('sub_cities')->where('city_id', $request->city_id)->get();
        return response()->json([
            'status' => true,
            'subcitys' => $subcitys
        ]);
    }
}
