<?php

namespace App\Http\Controllers;

use App\Models\Cart;
use App\Models\Product;
use Illuminate\Http\Request;

class CartsController extends Controller
{
    public function index(Request $request)
    {
        if ($request->isMethod('POST')) {
            $carts = Cart::query()->where('session_id', session()->getId())->where('is_buy', 0)->get();
            $total = 0.00;
            $shipping = 0.00;
            $subtotal = 0.00;
            $count = count($carts);
            foreach ($carts as $cart) {
                $subtotal = ($cart->numbers * $cart->product->price) + $subtotal;
            }
            $tax = $subtotal * getenv('PAYPAL_TAX');
            $subtotal = round($subtotal, 2);
            $total = $subtotal + $tax + $shipping;
            $total = round($total, 2);
            $total = number_format($total, 0, '.', '');
            $subtotal = number_format($subtotal, 0, '.', '');
            $tax = number_format($tax, 0, '.', '');
            $countryCode = 'DK';
            $currencyCode = getenv('PAYPAL_CURRENCY');
            $data = compact('subtotal', 'total', 'tax', 'count', 'countryCode', 'currencyCode');
            return response()->json([
                'code' => 1,
                'status' => 'success',
                'msg' => '',
                'data' => $data
            ]);
        }

        return view('carts.index');
    }

    public function store(Request $request)
    {
        $pid = $request->pid;
        $quantity = intval($request->quantity);
        $model = $request->jian;
        $sessionId = $request->session()->getId();
        $ip = $request->ip();
        $product = Product::query()->findOrFail($pid);
        $cart = Cart::query()->with('product')->where('session_id', $sessionId)->where('product_id', $product->pid)
            ->where('is_buy', 0)->first();
        if ($cart) {
            $quantity = $quantity === 1 ? 2 : $quantity;
            $cart->numbers = $quantity;
            $cart->singletotal = round($product->price * $cart->quantity);
            $cart->save();
        } else {
            Cart::query()->create([
                'product_id' => $product->pid,
                'session_id' => $sessionId,
                'jian' => $product->jianjie1,
                'brand' => $product->cs,
                'numbers' => $quantity,
                'baseprice' => $product->price,
                'singletotal' => round($product->price * $quantity, 2),
                'ip' => $ip
            ]);
        }
        return redirect()->route('carts.index');
    }
}
