<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ProfileController;
use App\Http\Controllers\WebController;
use App\Http\Controllers\CartController;
use App\Http\Controllers\CheckoutController;
use App\Models\Products;
use App\Models\Cart;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/
Route::get('/cart', [CartController::class, 'viewCart'])->name('cart.view');
Route::post('/cart/add', [CartController::class, 'addToCart'])->name('cart.add');
Route::get('/checkout', [CheckoutController::class, 'show'])->name('checkout');
Route::post('/checkout/process', [CheckoutController::class, 'process'])->name('checkout.process');
Route::get('/checkout/success', [CheckoutController::class, 'success'])->name('checkout.success');
Route::get('/checkout/cancel', [CheckoutController::class, 'cancel'])->name('checkout.cancel');
Route::get('/thank-you/{order_id}', [CheckoutController::class, 'showThankYou'])->name('thank-you');
// Public Routes
Route::get('/', function () {
    $products = Products::orderBy('id','desc')->limit(12)->get();
    $liquid = Products::where('category','liquid')->take(12)->get();

    if (Auth::check()) {
        $user = Auth::id(); // shorthand for auth()->user()->id
        $cart = Cart::where('user_id', $user)->count();
        return view('welcome', compact('products', 'cart','liquid'));
    } else {
        return view('welcome', compact('products','liquid'));
    }
})->name('home');

Route::get('/contactus', [WebController::class, 'contact_us'])->name('contact_us');
Route::post('/contact', [WebController::class, 'contact_form'])->name('contact_form');
Route::get('/about', [WebController::class, 'about'])->name('about');
Route::get('/privacy-policy', [WebController::class, 'privacypolicy'])->name('privacypolicy');
Route::get('/shipping-policy', [WebController::class, 'shippingpolicy'])->name('shippingpolicy');
Route::get('/returns-refunds', [WebController::class, 'returnsrefunds'])->name('returnsrefunds');
Route::get('/terms-conditions', [WebController::class, 'termsconditions'])->name('termsconditions');
Route::get('/aftershaves', [WebController::class, 'aftershaves'])->name('allproducts');
Route::get('/clean', [WebController::class, 'clean'])->name('clean');
Route::get('/vapepods', [WebController::class, 'vapepods'])->name('vapepods');
Route::get('/hardware', [WebController::class, 'hardware'])->name('hardware');
Route::get('/disposibles', [WebController::class, 'disposibles'])->name('disposibles');
Route::get('/liquid', [WebController::class, 'liquid'])->name('liquid');
Route::get('/heat', [WebController::class, 'heat'])->name('heat');
Route::get('/product_details/{id}', [WebController::class, 'product_details'])->name('product_details');
Route::get('/search-products', [WebController::class, 'search'])->name('products.search');
Route::get('/category-products/{category}', [App\Http\Controllers\WebController::class, 'getCategoryProducts']);



// Authentication Routes
require __DIR__.'/auth.php';

// Authenticated User Routes



// Route::post('/create-payment-intent', function (Request $request) {
//     \Stripe\Stripe::setApiKey(config('services.stripe.secret'));
    
//     try {
//         $cartItems = session()->get('cart', []);
        
//         if (empty($cartItems)) {
//             return response()->json([
//                 'success' => false,
//                 'error' => 'Your cart is empty'
//             ], 400);
//         }

//         // Calculate total amount from session cart
//         $amount = array_reduce($cartItems, function($carry, $item) {
//             return $carry + ($item['price'] * $item['quantity']);
//         }, 0) * 100; // Convert to cents

//         $intent = \Stripe\PaymentIntent::create([
//             'amount' => $amount,
//             'currency' => 'usd',
//             'metadata' => [
//                 'user_id' => auth()->check() ? auth()->id() : null, // Handle both logged-in and guest users
//                 'session_id' => session()->getId(), // Track by session
//                 'integration_check' => 'accept_a_payment'
//             ],
//             'automatic_payment_methods' => [
//                 'enabled' => true,
//             ],
//         ]);

//         return response()->json([
//             'success' => true,
//             'clientSecret' => $intent->client_secret,
//             'paymentIntentId' => $intent->id,
//             'amount' => $amount
//         ]);

//     } catch (\Exception $e) {
//         \Log::error('Payment Intent Creation Error:', [
//             'error' => $e->getMessage(),
//             'trace' => $e->getTraceAsString()
//         ]);
//         return response()->json([
//             'success' => false,
//             'error' => $e->getMessage()
//         ], 500);
//     }
// })->name('create.payment.intent');

Route::post('/create-payment-intent', [CheckoutController::class, 'createPaymentIntent']);

// PayPal Routes
Route::post('/create-paypal-order', [CheckoutController::class, 'createPayPalOrder']);
// Route::post('/create-payment-intent', [CheckoutController::class, 'createPaymentIntent'])->name('create.payment.intent');
Route::post('/capture-paypal-order', [CheckoutController::class, 'capturePayPalOrder']);
Route::post('/paypal-payment', [CheckoutController::class, 'paypalPayment'])->name('paypal.payment');
Route::get('/payment/success', [CheckoutController::class, 'paymentSuccess'])->name('payment.success');
Route::get('/payment/cancel', [CheckoutController::class, 'paymentCancel'])->name('payment.cancel');


    Route::delete('/cart/{cart}', [CartController::class, 'removeFromCart'])->name('cart.remove');
    Route::patch('/cart/{cart}', [CartController::class, 'updateCart'])->name('cart.update');
Route::middleware(['auth'])->group(function () {
    // Dashboard 
    Route::get('/dashboard', function () {
        $products = Products::limit(6)->get();
        return view('dashboard', compact('products'));
    })->name('dashboard');

    // Profile Routes
    Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit');
    Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');
    Route::delete('/profile', [ProfileController::class, 'destroy'])->name('profile.destroy');

    // Cart Routes
  
   


    // Checkout Routes
 

    // Payment Routes
   
});

// Admin Routes
Route::prefix('admin')->middleware(['auth', 'role'])->group(function () {
    Route::get('/dashboard', [WebController::class, 'admin'])->name('admin');
    Route::get('/products', [WebController::class, 'all_product'])->name('all_product');
    Route::get('/creatproducts', [WebController::class, 'create'])->name('create');
    Route::post('/product_add', [WebController::class, 'add_product'])->name('add_product');
    Route::put('/update_product/{id}', [WebController::class, 'update_product'])->name('update_product');
    Route::get('/product_add/{id}', [WebController::class, 'edit_product'])->name('edit_product');
    Route::post('/products_delete/{id}', [WebController::class, 'del_product'])->name('del_product');
    Route::get('/messages', [WebController::class, 'messages'])->name('messages');
    Route::get('/orders', [WebController::class, 'orders'])->name('orders');
});

Route::get('/search', [CheckoutController::class, 'search'])->name('admin.orders');


Route::get('auth/google', [WebController::class, 'redirectToGoogle'])
     ->name('google.login');

Route::get('auth/google/callback', [WebController::class, 'handleGoogleCallback'])
     ->name('google.callback');


