<?php

namespace App\Http\Controllers;

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

class CartController extends Controller
{
    public function Add($ProductId,$Quantity=1)
    {
        $cart = session()->get('cart', []);
        if (isset($cart[$ProductId])) {
            $cart[$ProductId]['quantity'] += $Quantity;
            if ($cart[$ProductId]['quantity'] <= 0) {
                unset($cart[$ProductId]);
            }
        } else {
            $cart[$ProductId] = [                
                "quantity" => $Quantity,               
            ];
        }
        session()->put('cart', $cart);
        return view('cart.index');
    }
    public static function Get()
    {
        $cart = session()->get('cart', []);
        if ($cart) {
            foreach ($cart as $ProductId => $item) {
                $cart[$ProductId]['product'] = Product::find($ProductId);
            }
        }
        return $cart;
    }
    public function Remove($ProductId)
    {
        $cart = session()->get('cart');
        if (isset($cart[$ProductId])) {
            unset($cart[$ProductId]);
            session()->put('cart', $cart);
        }
         return view('cart.index');
    }
    public function CheckoutAProduct($ProductId,$Quantity=1)
    {
        $ProductName=Product::find($ProductId)->title;
        $WhatsappNumber = env('WHATSAPP_NUMBER');
        $Order=new Order();
        $Order->type='whatsapp';
        $Order->description='Order via whatsapp';
        $Order->save();
        $Order->details()->create([
            'product_id'=>$ProductId,
            'quantity'=>$Quantity
        ]);        
       return redirect('https://wa.me/'.$WhatsappNumber.'?text=I%20want%20to%20order%20Product%20'.$ProductName.'%20Quantity%20'.$Quantity);
    }
    public function Checkout()
    {
        $Order=new Order();
        $Order->type='whatsapp';
        $Order->description='Order via whatsapp';
        $Order->save();
        $cart = session()->get('cart', []);
        if ($cart) {
            foreach ($cart as $ProductId => $item) {
                $cart[$ProductId]['product'] = Product::find($ProductId);
                $Order->details()->create([
                    'product_id'=>$ProductId,
                    'quantity'=>$item['quantity']
                ]);
            }
        }
        $WhatsappNumber = env('WHATSAPP_NUMBER');
        $message="I want to order the following Products:%0A";
        foreach($cart as $item)
        {
            $message.=$item['product']->title.' Quantity '.$item['quantity'].'%0A';
        }
        session()->forget('cart');
        return redirect('https://wa.me/'.$WhatsappNumber.'?text='.$message);
    }
   
    
    
}
