<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Order;
use Illuminate\Support\Facades\Auth;
use Stripe\Stripe;
use Stripe\OAuth;
use Stripe\PaymentIntent;
use Illuminate\Support\Str;

class CheckoutController extends Controller
{
   public function show(){
    $cart = session('cart',[]);
    if(empty($cart)) return redirect()->route('cart.index')->with('error', 'cart is empty');


    $total=collect($cart)->reduce(fn($c,$i)=>$c +
     ($i['price']*$i['quantity']),0);
    return view('checkout.index',['cart'=>$cart,'total'=>$total,'user'=>Auth::user()]);
   }
public function placeCashOrder(Request $request){
    $request->validate([
        'name'=>'required|string|max:255',
        'email'=>'required|email',
        'phone'=>'required|string|max:30',
        'address'=>'required|string:max:500',
    ]);

    $cart = session('cart',[]);
    if(empty($cart)) return back()->with('error','Cart is empty');

    $total = collect($cart)->reduce(fn($c,$i)=>$c+($i['price']*$i['quantity']),0);

    $order=Order::create([
        'user_id' =>Auth::id(),
        'total_price' =>$total,
        'status' =>'pending',
        'payment_method'=>'cash',
        'payment_status'=>'unpaid',
        'Shipping_address' =>$request->address,
        'tracking_code' =>strtoupper(Str::random(10)),
    ]);

    //TODO:
    session()->forget('cart');
    return redirect()->route('checkout.show')->with('success',
     'Order pleced (Cash).Tracking:{$order:tracking_code}');


}


}
