<?php

namespace App\Http\Controllers;

use App\Models\Order;
use App\Models\OrderItem;
use Illuminate\Http\Request;
use net\authorize\api\contract\v1 as AnetAPI;
use net\authorize\api\controller as AnetController;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use App\Models\User;
use App\Models\Product; 
use Illuminate\Support\Facades\DB;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;
use App\Services\ShippoService;

class CheckoutController extends Controller
{
    
    protected $shippoService;
    
    public function __construct(ShippoService $shippoService)
    {
        $this->shippoService = $shippoService;
    }

    public function getShippingMethods($carrier)
{
    try {
        $methods = DB::table('shipping_methods')
            ->where('carrier', $carrier)
            ->where('is_active', true)
            ->select('id', 'name', 'service_type', 'estimated_days')
            ->get();

        return response()->json([
            'success' => true,
            'methods' => $methods
        ]);
    } catch (\Exception $e) {
        Log::error('Error fetching shipping methods: ' . $e->getMessage());
        return response()->json([
            'success' => false,
            'error' => 'Unable to fetch shipping methods'
        ], 500);
    }
}

// public function calculateShipping(Request $request)
//     {
//         $request->validate([
//             'address' => 'required|string',
//             'city' => 'required|string',
//             'state' => 'required|string',
//             'zip_code' => 'required|string',
//             'country' => 'required|string',
//         ]);

//         $cart = Cart::getContent();
//         $weight = $this->calculateCartWeight($cart);

//         $toAddress = [
//             'street1' => $request->address,
//             'city' => $request->city,
//             'state' => $request->state,
//             'zip' => $request->zip_code,
//             'country' => $request->country,
//         ];

//         $rates = $this->shippoService->calculateShipping($toAddress, $weight, $cart);

//         if (!$rates) {
//             return response()->json([
//                 'success' => false,
//                 'message' => 'Unable to calculate shipping rates'
//             ], 422);
//         }

//         return response()->json([
//             'success' => true,
//             'rates' => $rates
//         ]);
//     }

// public function calculateShipping(Request $request)
//     {
//         $request->validate([
//             'address' => 'required|string',
//             'city' => 'required|string',
//             'state' => 'required|string',
//             'zip_code' => 'required|string',
//             'country' => 'required|string',
//             'weight' => 'required|numeric'
//         ]);

//         try {
//             $toAddress = [
//                 'name' => 'Guest Customer',
//                 'street1' => $request->address,
//                 'city' => $request->city,
//                 'state' => $request->state,
//                 'zip' => $request->zip_code,
//                 'country' => $request->country,
//             ];

//             //$rates = $this->shippoService->calculateShipping($toAddress, $request->weight);
//             // Around line 111, you should have something like this:
//             $rates = $this->shippoService->calculateShipping($toAddress, $weight, $subtotal);

//             return response()->json([
//                 'success' => true,
//                 'rates' => $rates
//             ]);
//         } catch (\Exception $e) {
//             Log::error('Shipping calculation error: ' . $e->getMessage());
//             return response()->json([
//                 'success' => false,
//                 'error' => 'Unable to calculate shipping rates'
//             ], 422);
//         }
//     }

public function calculateShipping(Request $request)
{
    $request->validate([
        'address' => 'required|string',
        'city' => 'required|string',
        'state' => 'required|string',
        'zip_code' => 'required|string',
        'country' => 'required|string',
        'weight' => 'required|numeric'
    ]);

    try {
        $toAddress = [
            'name' => 'Guest Customer',
            'street1' => $request->address,
            'city' => $request->city,
            'state' => $request->state,
            'zip' => $request->zip_code,
            'country' => $request->country,
        ];

        // Use the weight from the request
        $weight = $request->weight;
        
        // Get cart items to calculate subtotal if needed
        $cartItems = session('cart', []);
        $subtotal = collect($cartItems)->sum(function($item) {
            return $item['price'] * $item['quantity'];
        });

        // Call the ShippoService with the correct parameters
        $result = $this->shippoService->calculateShipping($toAddress, $weight, $subtotal);

        return response()->json($result);
    } catch (\Exception $e) {
        Log::error('Shipping calculation error: ' . $e->getMessage());
        return response()->json([
            'success' => false,
            'error' => 'Unable to calculate shipping rates'
        ], 422);
    }
}

    protected function calculateCartWeight($cart)
    {
        return $cart->sum(function($item) {
            $product = Product::find($item->id);
            return ($product->weight ?? 0.5) * $item->quantity;
        });
    }

private function calculateDistanceBasedRate($zipCode, $weight, $method)
{
    // Base rates by shipping method
    $rates = [
        'standard' => [
            'base' => 5.00,
            'per_kg' => 1.50,
            'days' => '3-5'
        ],
        'express' => [
            'base' => 12.00,
            'per_kg' => 2.50,
            'days' => '1-2'
        ],
        'economy' => [
            'base' => 3.50,
            'per_kg' => 1.00,
            'days' => '5-7'
        ]
    ];

    // Get selected rate
    $selectedRate = $rates[$method] ?? $rates['standard'];

    // Simple zone calculation based on ZIP code first digit
    $storeZip = substr(config('services.shipping.store_zip', '90210'), 0, 1);
    $customerZip = substr($zipCode, 0, 1);
    $zoneDiff = abs($customerZip - $storeZip);

    // Zone multipliers
    $zoneMultiplier = 1.0;
    if ($zoneDiff <= 1) {
        $zoneMultiplier = 1.0; // Same or adjacent zone
    } elseif ($zoneDiff <= 3) {
        $zoneMultiplier = 1.2; // Nearby zones
    } elseif ($zoneDiff <= 5) {
        $zoneMultiplier = 1.5; // Mid-distance zones
    } else {
        $zoneMultiplier = 1.8; // Far zones
    }

    // Calculate final rate
    $baseRate = $selectedRate['base'];
    $weightRate = $weight * $selectedRate['per_kg'];
    $totalRate = ($baseRate + $weightRate) * $zoneMultiplier;

    return [
        'rate' => round($totalRate, 2),
        'estimated_days' => $selectedRate['days'],
        'method_name' => ucfirst($method) . ' Shipping'
    ];
}

// public function calculateShipping(Request $request)
// {
//     $request->validate([
//         'zip_code' => 'required|string',
//         'state' => 'required|string',
//         'method' => 'required|string',
//         'weight' => 'required|numeric'
//     ]);

//     try {
//         $shippingData = $this->calculateDistanceBasedRate(
//             $request->zip_code,
//             $request->weight,
//             $request->method
//         );

//         return response()->json([
//             'success' => true,
//             'rates' => [
//                 'id' => $request->method,
//                 'name' => $shippingData['method_name'],
//                 'rate' => $shippingData['rate'],
//                 'estimated_days' => $shippingData['estimated_days']
//             ]
//         ]);
//     } catch (\Exception $e) {
//         Log::error('Error calculating shipping: ' . $e->getMessage());
//         return response()->json([
//             'success' => false,
//             'error' => 'Unable to calculate shipping rates'
//         ], 500);
//     }
// }

// public function calculateTax(Request $request)
// {
//     try {
//         \Log::info('Tax calculation request:', $request->all());
        
//         $state = $request->input('state');
//         $subtotal = floatval($request->input('subtotal', 0));

//         // Define tax rates per state (move to database or config later)
//         $taxRates = [
//             'AL' => 4.00,
//             'AK' => 0.00,
//             'AZ' => 5.60,
//             'AR' => 6.50,
//             'CA' => 7.25,
//             'CO' => 2.90,
//             'CT' => 6.35,
//             'DE' => 0.00,
//             'FL' => 6.00,
//             'GA' => 4.00,
//             'HI' => 4.00,
//             'ID' => 6.00,
//             'IL' => 6.25,
//             'IN' => 7.00,
//             'IA' => 6.00,
//             'KS' => 6.50,
//             'KY' => 6.00,
//             'LA' => 4.45,
//             'ME' => 5.50,
//             'MD' => 6.00,
//             'MA' => 6.25,
//             'MI' => 6.00,
//             'MN' => 6.875,
//             'MS' => 7.00,
//             'MO' => 4.225,
//             'MT' => 0.00,
//             'NE' => 5.50,
//             'NV' => 6.85,
//             'NH' => 0.00,
//             'NJ' => 6.625,
//             'NM' => 5.125,
//             'NY' => 4.00,
//             'NC' => 4.75,
//             'ND' => 5.00,
//             'OH' => 5.75,
//             'OK' => 4.50,
//             'OR' => 0.00,
//             'PA' => 6.00,
//             'RI' => 7.00,
//             'SC' => 6.00,
//             'SD' => 4.50,
//             'TN' => 7.00,
//             'TX' => 6.25,
//             'UT' => 6.10,
//             'VT' => 6.00,
//             'VA' => 5.30,
//             'WA' => 6.50,
//             'WV' => 6.00,
//             'WI' => 5.00,
//             'WY' => 4.00,
//             'DC' => 6.00,
//         ];

//         $taxRate = $taxRates[$state] ?? 0;
//         $taxAmount = ($subtotal * $taxRate) / 100;

//         \Log::info('Tax calculation result:', [
//             'state' => $state,
//             'subtotal' => $subtotal,
//             'tax_rate' => $taxRate,
//             'tax_amount' => $taxAmount
//         ]);

//         return response()->json([
//             'success' => true,
//             'tax_rate' => $taxRate,
//             'tax_amount' => $taxAmount
//         ]);
//     } catch (\Exception $e) {
//         \Log::error('Tax calculation error: ' . $e->getMessage());
//         return response()->json([
//             'success' => false,
//             'message' => 'Error calculating tax'
//         ], 500);
//     }
// }


public function calculateTax(Request $request)
{
    try {
        \Log::info('Tax calculation request received', [
            'state' => $request->input('state'),
            'subtotal' => $request->input('subtotal')
        ]);

        $state = $request->input('state');
        $subtotal = floatval($request->input('subtotal', 0));

        $taxRate = TaxRate::where('state_code', $state)
                         ->where('active', true)
                         ->first();

        \Log::info('Tax rate lookup result', [
            'found_rate' => $taxRate ? $taxRate->rate : 'no rate found'
        ]);

        $rate = $taxRate ? $taxRate->rate : 0;
        $taxAmount = ($subtotal * $rate) / 100;

        \Log::info('Tax calculation result', [
            'rate' => $rate,
            'tax_amount' => $taxAmount
        ]);

        return response()->json([
            'success' => true,
            'tax_rate' => $rate,
            'tax_amount' => $taxAmount
        ]);
    } catch (\Exception $e) {
        \Log::error('Tax calculation error: ' . $e->getMessage(), [
            'exception' => $e,
            'request_data' => $request->all()
        ]);
        
        return response()->json([
            'success' => false,
            'message' => 'Error calculating tax: ' . $e->getMessage()
        ], 500);
    }
}

    private function getMerchantAuthentication()
{
    $merchantAuthentication = new \net\authorize\api\contract\v1\MerchantAuthenticationType();
    $merchantAuthentication->setName(config('services.authorize.login'));
    $merchantAuthentication->setTransactionKey(config('services.authorize.transaction_key'));
    
    Log::info('Merchant authentication configured', [
        'login_id_length' => strlen(config('services.authorize.login')),
        'transaction_key_length' => strlen(config('services.authorize.transaction_key'))
    ]);
    
    return $merchantAuthentication;
}

    public function index()
    {
        $cartItems = session()->get('cart', []);
        if (empty($cartItems)) {
            return redirect()->route('cart.index');
        }

        $subtotal = collect($cartItems)->sum(function ($item) {
            return $item['price'] * $item['quantity'];
        });
        
        $tax = $subtotal * 0.0825;
        $shipping = session()->get('delivery_option') === 'delivery' ? 10 : 0;
        $total = $subtotal + $tax + $shipping;

        return view('checkout.index', compact('cartItems', 'subtotal', 'tax', 'shipping', 'total'));
    }


    public function checkout()
{
    $cartItems = session()->get('cart', []);
    if (empty($cartItems)) {
        return redirect()->route('cart.index');
    }

    $subtotal = collect($cartItems)->sum(function ($item) {
        return $item['price'] * $item['quantity'];
    });
    
     // Get selected state from session or set a default
     $selectedState = session()->get('selected_state');
        
     // Get tax rate from database if state is selected
     $taxRate = 0;
     if ($selectedState) {
         $taxRate = DB::table('tax_rates')
             ->where('state_code', $selectedState)
             ->value('rate') ?? 0;
     }
 
     $taxRate = ($taxRate ?? 0) / 100;
     
     $tax = $subtotal * $taxRate;
    $shipping = session()->get('delivery_option') === 'delivery' ? 10 : 0;
    //$shipping_zones = DB::table('shipping_zones')->select('state')->distinct()->get();
    $total = $subtotal + $tax + $shipping;
    
            // Get states from tax_rates table
            $states = DB::table('tax_rates')
            ->pluck('state_name', 'state_code')
            ->toArray();

    return view('checkout.index', compact('cartItems', 'subtotal', 'tax', 'shipping', 'total', 'states'));
}



// public function processCheckout(Request $request)
// {
//     try {
//         Log::info('Starting checkout process', ['request' => $request->all()]);
//         DB::beginTransaction();

//         // Base validation rules
//         $validationRules = [
//             'delivery_method' => 'required|in:pickup,delivery',
//             'payment_method' => 'required|in:card,cash_on_delivery',
//             'notes' => 'nullable|string'
//         ];

//         // Add address validation only if delivery is selected
//         // if ($request->delivery_method === 'delivery') {
//         //     $validationRules['address_id'] = 'required|exists:addresses,id,user_id,' . Auth::id();
//         // }

//         // Add card validation if card payment is selected
//         // if ($request->payment_method === 'card') {
//         //     $validationRules = array_merge($validationRules, [
//         //         'cardNumber' => 'required|string|size:16',
//         //         'cardExpiry' => 'required|string|size:5',
//         //         'cardCvv' => 'required|string|size:3',
//         //     ]);
//         // }
        
//          if ($request->delivery_method === 'delivery') {
//             $validationRules = array_merge($validationRules, [
//                 'address' => 'required|string|max:255',
//                 'city' => 'required|string|max:255',
//                 'state' => 'required|string|max:255',
//                 'zip_code' => 'required|string|max:20',
//                 'country' => 'required|string|max:20',
//             ]);
//         }

//         $validated = $request->validate($validationRules);
        
//         // Order calculations
//         // $orderNumber = 'ORD-' . strtoupper(Str::random(10));
//         // Log::info('Generated order number', ['order_number' => $orderNumber]);

//         // Check if cart is empty
//         $cartItems = session()->get('cart', []);
//         Log::info('Cart items retrieved', ['items' => $cartItems]);
        
//         if (empty($cartItems)) {
//             throw new \Exception('Your cart is empty.');
//         }

//         // Calculate totals
//         $subtotal = collect($cartItems)->sum(function($item) {
//             return $item['price'] * $item['quantity'];
//         });
//         $tax = $subtotal * 0.0825;
//         $shipping = $request->delivery_method === 'delivery' ? 10 : 0;
//         $total = $subtotal + $tax + $shipping;

//         // Process card payment if selected
//         // if ($request->payment_method === 'card') {
//         //     Log::info('Processing card payment', ['total' => $total]);
//         //     $paymentResult = $this->processPayment($request, $total);
//         //     if (!$paymentResult['success']) {
//         //         throw new \Exception($paymentResult['message']);
//         //     }
//         // }

//         if ($request->payment_method === 'card') {
//             Log::info('Processing card payment', ['total' => $total]);
//             $paymentResult = $this->processPayment(new Request([
//                 'dataValue' => $request->dataValue,
//                 'dataDescriptor' => $request->dataDescriptor,
//                 'amount' => $total
//             ]));
            
//             if (!$paymentResult['success']) {
//                 return back()->with('error', $paymentResult['message']);
//             }
//         }


//         Log::info('Order totals calculated', [
//             'subtotal' => $subtotal,
//             'tax' => $tax,
//             'shipping' => $shipping,
//             'total' => $total
//         ]);


//         // Prepare order data
//         $orderData = [
//             'order_number' => 'ORD-' . strtoupper(Str::random(10)),
//             'user_id' => Auth::id(),
//             'subtotal' => $subtotal,
//             'tax' => $tax,
//             'shipping' => $shipping,
//             'total' => $total,
//             'payment_method' => $request->payment_method,
//             'payment_status' => $request->payment_method === 'card' ? 'paid' : 'pending',
//             'order_status' => $request->payment_method === 'card' ? 'processing' : 'pending',
//             'notes' => $request->notes,
//             'shipping_email' => Auth::user()->email, // Ensure email is set
//             'billing_email' => Auth::user()->email,  // Ensure email is set
//         ];

//         // Add address details if delivery is selected
//         if ($request->delivery_method === 'delivery') {
//             //$address = Auth::user()->addresses()->findOrFail($request->address_id);
//             $orderData = array_merge($orderData, [
//                 'shipping_name' => $request->first_name . ' ' . $request->last_name,
//                 'shipping_email' => Auth::user()->email,
//                 'shipping_phone' => $request->phone,
//                 'shipping_address' => $request->address ?? null,
//                 'shipping_city' => $request->city ?? null,
//                 'shipping_state' => $request->state ?? null,
//                 'shipping_country' => $request->country ?? null,
//                 'shipping_zipcode' => $request->zip_code ?? null,
//                 'billing_name' => $request->first_name . ' ' . $request->last_name,
//                 'billing_email' => Auth::user()->email,
//                 'billing_phone' => $request->phone,
//                 'billing_address' => $request->address ?? "20 Parkroad",
//                 'billing_city' => $request->city ?? "St Louise",
//                 'billing_state' => $request->state ?? "Texas",
//                 'billing_country' => $request->country ?? "US",
//                 'billing_zipcode' => $request->zip_code ?? "75773",
//             ]);
//         }

//         // Create order
//         $order = Order::create($orderData);
//         Log::info('Order created', ['order_id' => $order->id]);

//         // Create order items and update stock
//         foreach ($cartItems as $id => $item) {
//             // Check if product exists and has enough stock
//             $product = Product::findOrFail($id);
//             if ($product->stock_quantity < $item['quantity']) {
//                 throw new \Exception("Insufficient stock for {$item['name']}");
//             }

//             OrderItem::create([
//                 'order_id' => $order->id,
//                 'product_id' => $id,
//                 'product_name' => $item['name'],
//                 'quantity' => $item['quantity'],
//                 'price' => $item['price'],
//                 'subtotal' => $item['price'] * $item['quantity']
//             ]);

//             // Update product stock for card payments
//             if ($request->payment_method === 'card') {
//                 $product->decrement('stock_quantity', $item['quantity']);
//             }
//         }

//         // Send confirmation email
//         // try {
//         //     $this->sendOrderConfirmationEmail($order, $request->payment_method);
//         // } catch (\Exception $e) {
//         //     Log::error('Failed to send confirmation email', ['error' => $e->getMessage()]);
//         //     // Continue processing even if email fails
//         // }

//         // Send confirmation email
//         $emailSent = $this->sendOrderConfirmationEmail($order, $request->payment_method);
//         if (!$emailSent) {
//             Log::warning('Order confirmation email could not be sent', ['order_id' => $order->id]);
//         }


//         DB::commit();
//         $orderNumber = $order->order_number;
//         session()->forget(['cart', 'delivery_option']);
//         Log::info('Checkout completed successfully', ['order_number' => $order->order_number]);

//         return redirect()->route('checkout.success', ['order' => $order->order_number])
//             ->with('success', 'Order placed successfully!');
            

//     } catch (\Exception $e) {
//         DB::rollBack();
//         Log::error('Checkout process failed', [
//             'error' => $e->getMessage(),
//             'trace' => $e->getTraceAsString()
//         ]);
//         return back()->with('error', 'Order processing failed: ' . $e->getMessage());
//     }
// }


public function processCheckout(Request $request)
{
    try {
        Log::info('Starting checkout process', ['request' => $request->all()]);
        DB::beginTransaction();

        // Initialize validation rules
        $validationRules = [
            'first_name' => 'required|string|max:255',
            'last_name' => 'required|string|max:255',
            'phone' => 'required|string|max:20',
            'delivery_method' => 'required|in:pickup,delivery',
            'payment_method' => 'required|in:card,cash_on_delivery',
        ];

        // Add delivery validation rules if delivery method is selected
        if ($request->delivery_method === 'delivery') {
            $validationRules = array_merge($validationRules, [
                'address' => 'required|string|max:255',
                'city' => 'required|string|max:255',
                'state' => 'required|string|max:255',
                'zip_code' => 'required|string|max:20',
                'country' => 'required|string|max:2',
                'shipping_method' => 'required|string',
                'shipping_cost' => 'required|numeric',
            ]);
        } else {
            // If pickup, require billing address
            $validationRules = array_merge($validationRules, [
                'billing_address' => 'required|string|max:255',
                'billing_city' => 'required|string|max:255',
                'billing_state' => 'required|string|max:255',
                'billing_zip_code' => 'required|string|max:20',
                'billing_country' => 'required|string|max:2',
            ]);
        }

        $validated = $request->validate($validationRules);

        // Check if cart is empty
        $cartItems = session()->get('cart', []);
        if (empty($cartItems)) {
            throw new \Exception('Your cart is empty.');
        }

        // Calculate totals
        $subtotal = collect($cartItems)->sum(function($item) {
            return $item['price'] * $item['quantity'];
        });
        $tax = $subtotal * 0.0825;
        $shipping = $request->delivery_method === 'delivery' ? $request->shipping_cost : 0;
        $total = $subtotal + $tax + $shipping;

        // Process card payment if selected
        if ($request->payment_method === 'card') {
            Log::info('Processing card payment', ['total' => $total]);
            $paymentResult = $this->processPayment(new Request([
                'dataValue' => $request->dataValue,
                'dataDescriptor' => $request->dataDescriptor,
                'amount' => $total
            ]));
            
            if (!$paymentResult['success']) {
                return back()->with('error', $paymentResult['message']);
            }
        }

        // Prepare order data
        $orderData = [
            'order_number' => 'ORD-' . strtoupper(Str::random(10)),
            'user_id' => Auth::id(),
            'subtotal' => $subtotal,
            'tax' => $tax,
            'shipping' => $shipping,
            'total' => $total,
            'payment_method' => $request->payment_method,
            'payment_status' => $request->payment_method === 'card' ? 'paid' : 'pending',
            'order_status' => $request->payment_method === 'card' ? 'processing' : 'pending',
            'notes' => $request->notes,
            'shipping_email' => Auth::user()->email,
            'billing_email' => Auth::user()->email,
        ];

        // Add address details if delivery is selected
        if ($request->delivery_method === 'delivery') {
            $orderData = array_merge($orderData, [
                'shipping_name' => $request->first_name . ' ' . $request->last_name,
                'shipping_email' => Auth::user()->email,
                'shipping_phone' => $request->phone,
                'shipping_address' => $request->address,
                'shipping_city' => $request->city,
                'shipping_state' => $request->state,
                'shipping_country' => $request->country,
                'shipping_zipcode' => $request->zip_code,
                'billing_name' => $request->first_name . ' ' . $request->last_name,
                'billing_email' => Auth::user()->email,
                'billing_phone' => $request->phone,
                'billing_address' => $request->billing_address ?? $request->address,
                'billing_city' => $request->billing_city ?? $request->city,
                'billing_state' => $request->billing_state ?? $request->state,
                'billing_country' => $request->billing_country ?? $request->country,
                'billing_zipcode' => $request->billing_zip_code ?? $request->zip_code,
            ]);
        } else {
            // For pickup orders
            $orderData = array_merge($orderData, [
                'billing_name' => $request->first_name . ' ' . $request->last_name,
                'billing_email' => Auth::user()->email,
                'billing_phone' => $request->phone,
                'billing_address' => $request->billing_address,
                'billing_city' => $request->billing_city,
                'billing_state' => $request->billing_state,
                'billing_country' => $request->billing_country,
                'billing_zipcode' => $request->billing_zip_code,
            ]);
        }

        // Create order
        $order = Order::create($orderData);

        // Create order items and update stock
        foreach ($cartItems as $id => $item) {
            $product = Product::findOrFail($id);
            if ($product->stock_quantity < $item['quantity']) {
                throw new \Exception("Insufficient stock for {$item['name']}");
            }

            OrderItem::create([
                'order_id' => $order->id,
                'product_id' => $id,
                'product_name' => $item['name'],
                'quantity' => $item['quantity'],
                'price' => $item['price'],
                'subtotal' => $item['price'] * $item['quantity']
            ]);

            if ($request->payment_method === 'card') {
                $product->decrement('stock_quantity', $item['quantity']);
            }
        }

        // Send confirmation email
        $emailSent = $this->sendOrderConfirmationEmail($order, $request->payment_method);
        if (!$emailSent) {
            Log::warning('Order confirmation email could not be sent', ['order_id' => $order->id]);
        }

        DB::commit();
        session()->forget(['cart', 'delivery_option']);

        return redirect()->route('checkout.success', ['order' => $order->order_number])
            ->with('success', 'Order placed successfully!');

    } catch (\Exception $e) {
        DB::rollBack();
        Log::error('Checkout process failed', [
            'error' => $e->getMessage(),
            'trace' => $e->getTraceAsString()
        ]);
        return back()->with('error', 'Order processing failed: ' . $e->getMessage());
    }
}




public function processPayment(Request $request)
{
    try {
        $input = $request->all();
        Log::info('Payment request received', ['amount' => $input['amount'] ?? 'not provided']);
        
        if (!$input || empty($input['dataValue']) || empty($input['dataDescriptor'])) {
            throw new Exception("Invalid payment data received.");
        }
        
        // Log successful validation
        Log::info('Payment data validated successfully');
        
        // Create the payment with tokenized data
        $opaqueData = new \net\authorize\api\contract\v1\OpaqueDataType();
        $opaqueData->setDataValue($input['dataValue']);
        $opaqueData->setDataDescriptor($input['dataDescriptor']);
        
        Log::info('OpaqueData created');
        
        $paymentType = new \net\authorize\api\contract\v1\PaymentType();
        $paymentType->setOpaqueData($opaqueData);
        
        $transactionRequest = new \net\authorize\api\contract\v1\TransactionRequestType();
        $transactionRequest->setTransactionType("authCaptureTransaction");
        $transactionRequest->setAmount($input['amount']);
        $transactionRequest->setPayment($paymentType);
        
        Log::info('Transaction request configured');
        
        $request = new \net\authorize\api\contract\v1\CreateTransactionRequest();
        $request->setMerchantAuthentication($this->getMerchantAuthentication());
        $request->setTransactionRequest($transactionRequest);
        
        Log::info('About to execute API request');
        
        $controller = new \net\authorize\api\controller\CreateTransactionController($request);
        $response = $controller->executeWithApiResponse(\net\authorize\api\constants\ANetEnvironment::SANDBOX);
        
        Log::info('API response received', [
            'resultCode' => $response ? $response->getMessages()->getResultCode() : 'No response'
        ]);
        
        if ($response != null && $response->getMessages()->getResultCode() == "Ok") {
            $tResponse = $response->getTransactionResponse();
            
            if ($tResponse != null && $tResponse->getMessages() != null) {
                Log::info('Transaction successful', [
                    'transaction_id' => $tResponse->getTransId(),
                    'auth_code' => $tResponse->getAuthCode()
                ]);
                
                return [
                    'success' => true,
                    'transaction_id' => $tResponse->getTransId(),
                    'auth_code' => $tResponse->getAuthCode() 
                ];
            }
        } else if ($response != null) {
            // Log detailed error information
            Log::error('Authorize.Net error', [
                'resultCode' => $response->getMessages()->getResultCode(),
                'message' => $response->getMessages()->getMessage()[0]->getText() ?? 'No message'
            ]);
            
            if ($response->getTransactionResponse() != null) {
                Log::error('Transaction response error', [
                    'code' => $response->getTransactionResponse()->getErrors()[0]->getErrorCode() ?? 'No code',
                    'message' => $response->getTransactionResponse()->getErrors()[0]->getErrorText() ?? 'No message'
                ]);
            }
        }
        
        return ['success' => false, 'message' => 'Payment failed. Please try again.'];
    } catch (\Exception $e) {
        Log::error('Payment Processing Error: ' . $e->getMessage(), [
            'trace' => $e->getTraceAsString()
        ]);
        return ['success' => false, 'message' => 'Payment processing failed: ' . $e->getMessage()];
    }
}

    
    
//     public function processOrder(Request $request)
// {
//     $request->validate([
//         'payment_method' => 'required|in:card,cash_on_delivery',
//         'shipping_name' => 'required',
//         'shipping_email' => 'required|email',
//         'shipping_phone' => 'required',
//         'shipping_address' => 'required',
//         'shipping_city' => 'required',
//         'shipping_state' => 'required',
//         'shipping_country' => 'required',
//         'shipping_zipcode' => 'required',
//     ]);

//     // Additional validation for card payment
//     if ($request->payment_method === 'card') {
//         $request->validate([
//             'cardNumber' => 'required',
//             'cardExpiry' => 'required',
//             'cardCvv' => 'required',
//         ]);
//     }

//     try {
//         // Calculate totals
//         $cartItems = session()->get('cart', []);
//         $subtotal = collect($cartItems)->sum(function ($item) {
//             return $item['price'] * $item['quantity'];
//         });
//         $tax = $subtotal * 0.0825;
//         $shipping = session()->get('delivery_option') === 'delivery' ? 10 : 0;
//         $total = $subtotal + $tax + $shipping;

//         // Process card payment if selected
//         if ($request->payment_method === 'card') {
//             $paymentResult = $this->processCardPayment($request, $total);
//             if (!$paymentResult['success']) {
//                 return back()->with('error', $paymentResult['message']);
//             }
//         }

//         // Create order
//         $order = Order::create([
//             'order_number' => 'ORD-' . uniqid(),
//             'user_id' => auth()->id(),
//             'subtotal' => $subtotal,
//             'tax' => $tax,
//             'shipping' => $shipping,
//             'total' => $total,
//             'payment_method' => $request->payment_method,
//             'payment_status' => $request->payment_method === 'card' ? 'paid' : 'pending',
//             'order_status' => 'processing',
//             'shipping_name' => $request->shipping_name,
//             'shipping_email' => $request->shipping_email,
//             'shipping_phone' => $request->shipping_phone,
//             'shipping_address' => $request->shipping_address,
//             'shipping_city' => $request->shipping_city,
//             'shipping_state' => $request->shipping_state,
//             'shipping_country' => $request->shipping_country,
//             'shipping_zipcode' => $request->shipping_zipcode,
//             'billing_name' => $request->billing_name ?? $request->shipping_name,
//             'billing_email' => $request->billing_email ?? $request->shipping_email,
//             'billing_phone' => $request->billing_phone ?? $request->shipping_phone,
//             'billing_address' => $request->billing_address ?? $request->shipping_address,
//             'billing_city' => $request->billing_city ?? $request->shipping_city,
//             'billing_state' => $request->billing_state ?? $request->shipping_state,
//             'billing_country' => $request->billing_country ?? $request->shipping_country,
//             'billing_zipcode' => $request->billing_zipcode ?? $request->shipping_zipcode,
//             'notes' => $request->notes
//         ]);

//         // Create order items
//         foreach ($cartItems as $id => $item) {
//             OrderItem::create([
//                 'order_id' => $order->id,
//                 'product_id' => $id,
//                 'product_name' => $item['name'],
//                 'quantity' => $item['quantity'],
//                 'price' => $item['price'],
//                 'subtotal' => $item['price'] * $item['quantity']
//             ]);
//         }

//         // Clear cart
//         session()->forget(['cart', 'delivery_option']);

//         return redirect()->route('checkout.success', $order->order_number)
//             ->with('success', 'Order placed successfully!');

//     } catch (\Exception $e) {
//         return back()->with('error', 'An error occurred. Please try again.');
//     }
// }

// private function processCardPayment($request, $total)
// {
//     try {
//         $creditCard = new AnetAPI\CreditCardType();
//         $creditCard->setCardNumber($request->cardNumber);
//         $expiry = explode('/', $request->cardExpiry);
//         $creditCard->setExpirationDate(trim($expiry[1]) . '-' . trim($expiry[0]));
//         $creditCard->setCardCode($request->cardCvv);

//         $paymentType = new AnetAPI\PaymentType();
//         $paymentType->setCreditCard($creditCard);

//         $transactionRequestType = new AnetAPI\TransactionRequestType();
//         $transactionRequestType->setTransactionType("authCaptureTransaction");
//         $transactionRequestType->setAmount($total);
//         $transactionRequestType->setPayment($paymentType);

//         $request = new AnetAPI\CreateTransactionRequest();
//         $request->setMerchantAuthentication($this->getMerchantAuthentication());
//         $request->setTransactionRequest($transactionRequestType);

//         $controller = new AnetController\CreateTransactionController($request);
//         $response = $controller->executeWithApiResponse(\net\authorize\api\constants\ANetEnvironment::SANDBOX);

//         if ($response != null && $response->getMessages()->getResultCode() == "Ok") {
//             return ['success' => true];
//         }

//         return ['success' => false, 'message' => 'Payment failed. Please try again.'];

//     } catch (\Exception $e) {
//         return ['success' => false, 'message' => 'Payment processing error. Please try again.'];
//     }
// }


// ... existing code ...

// public function guestCheckout()
// {
//     $cartItems = session()->get('cart', []);
//     if (empty($cartItems)) {
//         return redirect()->route('cart.index');
//     }

//     $subtotal = collect($cartItems)->sum(function ($item) {
//         return $item['price'] * $item['quantity'];
//     });
    
//     $tax = $subtotal * 0.0825;
//     $shipping = session()->get('delivery_option') === 'delivery' ? 10 : 0;
// //$shipping_zones = DB::table('shipping_zones')->select('state')->distinct()->get();
//     $total = $subtotal + $tax + $shipping;


    
//     $states = [
//         'AL' => 'Alabama',
//             'AK' => 'Alaska',
//             'AZ' => 'Arizona',
//             'AR' => 'Arkansas',
//             'CA' => 'California',
//             'CO' => 'Colorado',
//             'CT' => 'Connecticut',
//             'DE' => 'Delaware',
//             'DC' => 'District of Columbia',
//             'FL' => 'Florida',
//             'GA' => 'Georgia',
//             'HI' => 'Hawaii',
//             'ID' => 'Idaho',
//             'IL' => 'Illinois',
//             'IN' => 'Indiana',
//             'IA' => 'Iowa',
//             'KS' => 'Kansas',
//             'KY' => 'Kentucky',
//             'LA' => 'Louisiana',
//             'ME' => 'Maine',
//             'MD' => 'Maryland',
//             'MA' => 'Massachusetts',
//             'MI' => 'Michigan',
//             'MN' => 'Minnesota',
//             'MS' => 'Mississippi',
//             'MO' => 'Missouri',
//             'MT' => 'Montana',
//             'NE' => 'Nebraska',
//             'NV' => 'Nevada',
//             'NH' => 'New Hampshire',
//             'NJ' => 'New Jersey',
//             'NM' => 'New Mexico',
//             'NY' => 'New York',
//             'NC' => 'North Carolina',
//             'ND' => 'North Dakota',
//             'OH' => 'Ohio',
//             'OK' => 'Oklahoma',
//             'OR' => 'Oregon',
//             'PA' => 'Pennsylvania',
//             'PR' => 'Puerto Rico',
//             'RI' => 'Rhode Island',
//             'SC' => 'South Carolina',
//             'SD' => 'South Dakota',
//             'TN' => 'Tennessee',
//             'TX' => 'Texas',
//             'UT' => 'Utah',
//             'VT' => 'Vermont',
//             'VA' => 'Virginia',
//             'VI' => 'Virgin Islands',
//             'WA' => 'Washington',
//             'WV' => 'West Virginia',
//             'WI' => 'Wisconsin',
//             'WY' => 'Wyoming',
//             'AS' => 'American Samoa',
//             'GU' => 'Guam',
//             'MP' => 'Northern Mariana Islands'
//     ];

//     return view('checkout.guest', compact('cartItems', 'subtotal', 'tax', 'shipping', 'total', 'states'));
// }

// public function guestCheckout()
// {
//     $cartItems = session()->get('cart', []);
//     if (empty($cartItems)) {
//         return redirect()->route('cart.index');
//     }

//     $subtotal = collect($cartItems)->sum(function ($item) {
//         return $item['price'] * $item['quantity'];
//     });
    
//     // Get tax rates from database
//     $taxRates = DB::table('tax_rates')->pluck('rate', 'state_code');
//     $defaultTaxRate = 0.0825; // Default tax rate if state not found
    
//     // Get selected state from session or default to first state
//     $selectedState = session()->get('selected_state', 'TX');
//     $taxRate = $taxRates[$selectedState] ?? $defaultTaxRate;
    
//     $tax = $subtotal * $taxRate;
//     $shipping = session()->get('delivery_option') === 'delivery' ? 10 : 0;
//     $total = $subtotal + $tax + $shipping;

//     // Get states from database with tax rates
//     $states = DB::table('tax_rates')
//         ->select('state_code', 'state_name')
//         ->pluck('state_name', 'state_code')
//         ->toArray();

//     return view('checkout.guest', compact('cartItems', 'subtotal', 'tax', 'shipping', 'total', 'states', 'taxRates'));
// }

public function guestCheckout()
{
    $cartItems = session()->get('cart', []);
    if (empty($cartItems)) {
        return redirect()->route('cart.index');
    }

    $subtotal = collect($cartItems)->sum(function ($item) {
        return $item['price'] * $item['quantity'];
    });
    
    // Get selected state from session or set a default
    $selectedState = session()->get('selected_state');
    
    // Get tax rate from database if state is selected
    $taxRate = 0;
    if ($selectedState) {
        $taxRate = DB::table('tax_rates')
            ->where('state_code', $selectedState)
            ->value('rate') ?? 0;
    }

    $taxRate = ($taxRate ?? 0) / 100;
    
    $tax = $subtotal * $taxRate;
    $shipping = session()->get('delivery_option') === 'delivery' ? 10 : 0;
    $total = $subtotal + $tax + $shipping;

    // Get states from tax_rates table
    $states = DB::table('tax_rates')
        ->pluck('state_name', 'state_code')
        ->toArray();

    return view('checkout.guest', compact('cartItems', 'subtotal', 'tax', 'shipping', 'total', 'states'));
}


public function updateTax(Request $request)
{
    $state = $request->state;
    $subtotal = $request->subtotal;
    
    // Get tax rate from database and convert to decimal
    $taxRate = DB::table('tax_rates')
        ->where('state_code', $state)
        ->value('rate');
    
    // Convert percentage to decimal (e.g., 8.25% becomes 0.0825)
    $taxRate = ($taxRate ?? 0) / 100;
    
    $tax = $subtotal * $taxRate;
    
    session()->put('selected_state', $state);
    
    return response()->json([
        'tax' => number_format($tax, 2),
        'total' => number_format($subtotal + $tax + ($request->shipping ?? 0), 2)
    ]);
}


// public function updateTax(Request $request)
// {
//     $state = $request->state;
//     $subtotal = $request->subtotal;
    
//     $taxRate = DB::table('tax_rates')
//         ->where('state_code', $state)
//         ->value('rate') ?? 0.0825;
    
//     $tax = $subtotal * $taxRate;
    
//     session()->put('selected_state', $state);
    
//     return response()->json([
//         'tax' => number_format($tax, 2),
//         'total' => number_format($subtotal + $tax + ($request->shipping ?? 0), 2)
//     ]);
// }

// public function processGuestCheckout(Request $request)
// {
//     try {
//         Log::info('Starting guest checkout process', ['request' => $request->all()]);
//         DB::beginTransaction();

//         // Initialize validation rules
//         $validationRules = [
//             'first_name' => 'required|string|max:255',
//             'last_name' => 'required|string|max:255',
//             'email' => 'required|email|max:255',
//             'phone' => 'required|string|max:20',
//             'delivery_method' => 'required|in:pickup,delivery',
//             'payment_method' => 'required|in:card,cash_on_delivery',
//         ];


//         // Add delivery validation rules if delivery method is selected
//         if ($request->delivery_method === 'delivery') {
//             $validationRules = array_merge($validationRules, [
//                 'address' => 'required|string|max:255',
//                 'city' => 'required|string|max:255',
//                 'state' => 'required|string|max:255',
//                 'zip_code' => 'required|string|max:20',
//                 'country' => 'required|string|max:2',
//                 'shipping_method' => 'required|string',
//                 'shipping_cost' => 'required|string',
//             ]);
//         }

//         // Validate all rules at once
//         $validated = $request->validate($validationRules);

      
//         // User account creation
//         $userId = 1;
//         if ($request->create_account && $request->password) {
//             Log::info('Creating user account', ['email' => $request->email]);
//             $user = User::create([
//                 'name' => $request->first_name . ' ' . $request->last_name,
//                 'email' => $request->email,
//                 'password' => Hash::make($request->password),
//             ]);
//             $userId = $user->id;
//             Log::info('User account created', ['user_id' => $userId]);
//         }

//         // Order calculations
//         $orderNumber = 'ORD-' . strtoupper(Str::random(10));
//         Log::info('Generated order number', ['order_number' => $orderNumber]);

//         $cartItems = session('cart', []);
//         Log::info('Cart items retrieved', ['items' => $cartItems]);

//         $subtotal = collect($cartItems)->sum(function($item) {
//             return $item['price'] * $item['quantity'];
//         });
//         $tax = $subtotal * 0.1;
//         $shipping = $request->delivery_method === 'delivery' ? $request->shipping_cost : 0;
//         $total = $subtotal + $tax + $shipping;

        
//         if ($request->payment_method === 'card') {
//             Log::info('Processing card payment', ['total' => $total]);
//             $paymentResult = $this->processPayment(new Request([
//                 'dataValue' => $request->dataValue,
//                 'dataDescriptor' => $request->dataDescriptor,
//                 'amount' => $total
//             ]));
            
//             if (!$paymentResult['success']) {
//                 return back()->with('error', $paymentResult['message']);
//             }
//         }


//         Log::info('Order totals calculated', [
//             'subtotal' => $subtotal,
//             'tax' => $tax,
//             'shipping' => $shipping,
//             'total' => $total
//         ]);

//         // Create order
//         Log::info('Creating order record');
//         $order = Order::create([
//             'order_number' => $orderNumber,
//             'user_id' =>  $userId,
//             'subtotal' => $subtotal,
//             'tax' => $tax,
//             'shipping' => $shipping,
//             'total' => $total,
//             'payment_method' => $request->payment_method,
//             'payment_status' => $request->payment_method === 'card' ? 'paid' : 'pending',
//             'order_status' => $request->payment_method === 'card' ? 'processing' : 'pending',
//             'notes' => $request->notes,
//             'shipping_name' => $request->first_name . ' ' . $request->last_name,
//             'shipping_email' => $request->email,
//             'shipping_phone' => $request->phone,
//             'shipping_address' => $request->address ?? null,
//             'shipping_city' => $request->city ?? null,
//             'shipping_state' => $request->state ?? null,
//             'shipping_country' => $request->country ?? null,
//             'shipping_zipcode' => $request->zip_code ?? null,
//             'billing_name' => $request->first_name . ' ' . $request->last_name,
//             'billing_email' => $request->email,
//             'billing_phone' => $request->phone,
//             'billing_address' => $request->address ?? null,
//             'billing_city' => $request->city ?? null,
//             'billing_state' => $request->state ?? null,
//             'billing_country' => $request->country ?? null,
//             'billing_zipcode' => $request->zip_code ?? null,
//         ]);
//         Log::info('Order created', ['order_id' => $order->id]);

//         // Create order items and update stock
//         Log::info('Processing order items');
//         foreach ($cartItems as $item) {
//             try {
//                 Log::info('Creating order item', ['product_id' => $item['id']]);
//                 OrderItem::create([
//                     'order_id' => $order->id,
//                     'product_id' => $item['id'],
//                     'product_name' => $item['name'],
//                     'quantity' => $item['quantity'],
//                     'price' => $item['price'],
//                     'subtotal' => $item['price'] * $item['quantity']
//                 ]);

//                 $product = Product::find($item['id']);
//                 if ($request->payment_method === 'card') {
//                     Log::info('Updating product stock', [
//                         'product_id' => $item['id'],
//                         'quantity' => $item['quantity']
//                     ]);
//                     $product->decrement('stock_quantity', $item['quantity']);
//                 }
//             } catch (\Exception $e) {
//                 Log::error('Error processing order item', [
//                     'product_id' => $item['id'],
//                     'error' => $e->getMessage()
//                 ]);
//                 throw $e;
//             }
//         }

//         // Send email
//         Log::info('Sending order confirmation email');
//         try {
//             $this->sendOrderConfirmationEmail($order, $request->payment_method);
//         } catch (\Exception $e) {
//             Log::error('Email sending failed', ['error' => $e->getMessage()]);
//             // Continue processing even if email fails
//         }

//         DB::commit();
//         Log::info('Transaction committed');

//         session()->forget('cart');
//         Log::info('Cart cleared');

//         Log::info('Checkout process completed successfully', ['order_number' => $order->order_number]);
//         return redirect()->route('checkout.success', ['order' => $order->order_number])
//             ->with('success', 'Order placed successfully!');

//     } catch (\Exception $e) {
//         DB::rollBack();
//         Log::error('Checkout process failed', [
//             'error' => $e->getMessage(),
//             'trace' => $e->getTraceAsString()
//         ]);
//         return back()->with('error', 'Order processing failed: ' . $e->getMessage());
//     }
// }

public function processGuestCheckout(Request $request)
{
    try {
        Log::info('Starting guest checkout process', ['request' => $request->all()]);
        DB::beginTransaction();

        // Initialize validation rules
        $validationRules = [
            'first_name' => 'required|string|max:255',
            'last_name' => 'required|string|max:255',
            'email' => 'required|email|max:255',
            'phone' => 'required|string|max:20',
            'delivery_method' => 'required|in:pickup,delivery',
            'payment_method' => 'required|in:card,cash_on_delivery',
        ];

         // Add delivery validation rules if delivery method is selected
         if ($request->delivery_method === 'delivery') {
            $validationRules = array_merge($validationRules, [
                'address' => 'required|string|max:255',
                'city' => 'required|string|max:255',
                'state' => 'required|string|max:255',
                'zip_code' => 'required|string|max:20',
                'country' => 'required|string|max:2',
                'shipping_method' => 'required|string',
                'shipping_cost' => 'required|numeric',
            ]);
        } else {
            // If pickup, require billing address
            $validationRules = array_merge($validationRules, [
                'billing_address' => 'required|string|max:255',
                'billing_city' => 'required|string|max:255',
                'billing_state' => 'required|string|max:255',
                'billing_zip_code' => 'required|string|max:20',
                'billing_country' => 'required|string|max:2',
            ]);
        }

        // Add billing address validation if "same_as_shipping" is not checked
        if (!$request->has('same_as_shipping')) {
            $validationRules = array_merge($validationRules, [
                'billing_address' => 'required|string|max:255',
                'billing_city' => 'required|string|max:255',
                'billing_state' => 'required|string|max:255',
                'billing_zip_code' => 'required|string|max:20',
                'billing_country' => 'required|string|max:2',
            ]);
        }

        // Add card payment validation if card payment is selected
        if ($request->payment_method === 'card') {
            $validationRules = array_merge($validationRules, [
                'dataValue' => 'required',
                'dataDescriptor' => 'required',
            ]);
        }

        // Validate all rules at once
        $validated = $request->validate($validationRules);

        // User account creation
        $userId = 1;
        if ($request->create_account && $request->password) {
            Log::info('Creating user account', ['email' => $request->email]);
            $user = User::create([
                'name' => $request->first_name . ' ' . $request->last_name,
                'email' => $request->email,
                'password' => Hash::make($request->password),
            ]);
            $userId = $user->id;
            Log::info('User account created', ['user_id' => $userId]);
        }

        // Order calculations
        $orderNumber = 'ORD-' . strtoupper(Str::random(10));
        Log::info('Generated order number', ['order_number' => $orderNumber]);

        $cartItems = session('cart', []);
        Log::info('Cart items retrieved', ['items' => $cartItems]);

        $subtotal = collect($cartItems)->sum(function($item) {
            return $item['price'] * $item['quantity'];
        });
        $tax = $subtotal * 0.1;
        $shipping = $request->delivery_method === 'delivery' ? $request->shipping_cost : 0;
        $total = $subtotal + $tax + $shipping;

        // Process card payment if selected
        if ($request->payment_method === 'card') {
            Log::info('Processing card payment', ['total' => $total]);
            $paymentResult = $this->processPayment(new Request([
                'dataValue' => $request->dataValue,
                'dataDescriptor' => $request->dataDescriptor,
                'amount' => $total
            ]));
            
            if (!$paymentResult['success']) {
                return back()->with('error', $paymentResult['message']);
            }
        }

        Log::info('Order totals calculated', [
            'subtotal' => $subtotal,
            'tax' => $tax,
            'shipping' => $shipping,
            'total' => $total
        ]);

        // Determine billing information based on same_as_shipping checkbox
        $billingName = $request->first_name . ' ' . $request->last_name;
        $billingEmail = $request->email;
        $billingPhone = $request->phone;
        
        // if ($request->has('same_as_shipping')) {
        //     // Use shipping address for billing
        //     $billingAddress = $request->address;
        //     $billingCity = $request->city;
        //     $billingState = $request->state;
        //     $billingCountry = $request->country;
        //     $billingZipcode = $request->zip_code;
        // } else {
        //     // Use separate billing address
        //     $billingAddress = $request->billing_address;
        //     $billingCity = $request->billing_city;
        //     $billingState = $request->billing_state;
        //     $billingCountry = $request->billing_country;
        //     $billingZipcode = $request->billing_zip_code;
        // }

        // Determine shipping/billing information
        if ($request->delivery_method === 'delivery') {
            $shippingAddress = $request->address;
            $shippingCity = $request->city;
            $shippingState = $request->state;
            $shippingZipcode = $request->zip_code;
            $shippingCountry = $request->country;
            
            // Use shipping address for billing if same_as_shipping is checked
            if ($request->has('same_as_shipping')) {
                $billingAddress = $request->address;
                $billingCity = $request->city;
                $billingState = $request->state;
                $billingZipcode = $request->zip_code;
                $billingCountry = $request->country;
            } else {
                $billingAddress = $request->billing_address;
                $billingCity = $request->billing_city;
                $billingState = $request->billing_state;
                $billingZipcode = $request->billing_zip_code;
                $billingCountry = $request->billing_country;
            }
        } else {
            // For pickup, use billing address as the main address
            $billingAddress = $request->billing_address;
            $billingCity = $request->billing_city;
            $billingState = $request->billing_state;
            $billingZipcode = $request->billing_zip_code;
            $billingCountry = $request->billing_country;
            
            // Set shipping address to null for pickup
            $shippingAddress = null;
            $shippingCity = null;
            $shippingState = null;
            $shippingZipcode = null;
            $shippingCountry = null;
        }

        // Create order
        Log::info('Creating order record');
        $order = Order::create([
            'order_number' => $orderNumber,
            'user_id' =>  $userId,
            'subtotal' => $subtotal,
            'tax' => $tax,
            'shipping' => $shipping,
            'total' => $total,
            'payment_method' => $request->payment_method,
            'payment_status' => $request->payment_method === 'card' ? 'paid' : 'pending',
            'order_status' => $request->payment_method === 'card' ? 'processing' : 'pending',
            'notes' => $request->notes,
            'shipping_name' => $request->first_name . ' ' . $request->last_name,
            'shipping_email' => $request->email,
            'shipping_phone' => $request->phone,
            'shipping_address' => $request->address ?? null,
            'shipping_city' => $request->city ?? null,
            'shipping_state' => $request->state ?? null,
            'shipping_country' => $request->country ?? null,
            'shipping_zipcode' => $request->zip_code ?? null,
            'billing_name' => $billingName,
            'billing_email' => $billingEmail,
            'billing_phone' => $billingPhone,
            'billing_address' => $billingAddress ?? null,
            'billing_city' => $billingCity ?? null,
            'billing_state' => $billingState ?? null,
            'billing_country' => $billingCountry ?? null,
            'billing_zipcode' => $billingZipcode ?? null,
        ]);
        Log::info('Order created', ['order_id' => $order->id]);

        // Create order items and update stock
        Log::info('Processing order items');
        foreach ($cartItems as $item) {
            try {
                Log::info('Creating order item', ['product_id' => $item['id']]);
                OrderItem::create([
                    'order_id' => $order->id,
                    'product_id' => $item['id'],
                    'product_name' => $item['name'],
                    'quantity' => $item['quantity'],
                    'price' => $item['price'],
                    'subtotal' => $item['price'] * $item['quantity']
                ]);

                $product = Product::find($item['id']);
                if ($request->payment_method === 'card') {
                    Log::info('Updating product stock', [
                        'product_id' => $item['id'],
                        'quantity' => $item['quantity']
                    ]);
                    $product->decrement('stock_quantity', $item['quantity']);
                }
            } catch (\Exception $e) {
                Log::error('Error processing order item', [
                    'product_id' => $item['id'],
                    'error' => $e->getMessage()
                ]);
                throw $e;
            }
        }

        // Send email
        Log::info('Sending order confirmation email');
        try {
            $this->sendOrderConfirmationEmail($order, $request->payment_method);
        } catch (\Exception $e) {
            Log::error('Email sending failed', ['error' => $e->getMessage()]);
            // Continue processing even if email fails
        }

        DB::commit();
        Log::info('Transaction committed');

        session()->forget('cart');
        Log::info('Cart cleared');

        Log::info('Checkout process completed successfully', ['order_number' => $order->order_number]);
        return redirect()->route('checkout.success', ['order' => $order->order_number])
            ->with('success', 'Order placed successfully!');

    } catch (\Exception $e) {
        DB::rollBack();
        Log::error('Checkout process failed', [
            'error' => $e->getMessage(),
            'trace' => $e->getTraceAsString()
        ]);
        return back()->with('error', 'Order processing failed: ' . $e->getMessage());
    }
}


public function success($orderNumber)
{
    $order = Order::where('order_number', $orderNumber)->firstOrFail();
    return view('checkout.success', compact('order'));
}



    // public function success($orderNumber)
    // {
    //     $order = Order::where('order_number', $orderNumber)->firstOrFail();
    //     return view('checkout.success', compact('order'));
    // }


// private function sendOrderConfirmationEmail($order, $paymentMethod)
// {
//     try {

//         $order = $order->load('orderItems');
//         $mail = new PHPMailer(true);

//         // Server settings
//         $mail->isSMTP();
//         $mail->Host       = 'aphrodailymart.com';
//         $mail->SMTPAuth   = true;
//         $mail->Username   = 'hello@aphrodailymart.com'; // Your Gmail address
//         $mail->Password   = '9OzDs8j_dIED'; // Your Gmail App Password
//         $mail->SMTPSecure = 'ssl';
//         $mail->Port       = 465;

//         // Recipients
//         $mail->setFrom('hello@aphrodailymart.com', 'APHRODAILYMART!');
//         // $mail->addAddress($order->shipping_email, $order->shipping_name);
//         $mail->addAddress($order->shipping_email ?: $order->billing_email, $order->shipping_name);

//         // Content
//         $mail->isHTML(true);
//         $mail->Subject = 'Order Confirmation #' . $order->order_number;
        
//         // Different email templates based on payment method
//         if ($paymentMethod === 'card') {
//             $mail->Body = $this->getPaidOrderEmailTemplate($order);
//         } else {
//             $mail->Body = $this->getCODOrderEmailTemplate($order);
//         }

//         $mail->send();
        
//         // Send admin notification
//         $this->sendAdminNotification($order);

//     } catch (Exception $e) {
//         Log::error("Mail sending failed: " . $e->getMessage());
//     }
// }

// Update the sendOrderConfirmationEmail method
private function sendOrderConfirmationEmail($order, $paymentMethod)
{
    try {
        $order = $order->load('orderItems');
        $mail = new PHPMailer(true);

        // Server settings
        $mail->isSMTP();
        $mail->Host       = 'aphrodailymart.com';
        $mail->SMTPAuth   = true;
        $mail->Username   = 'hello@aphrodailymart.com';
        $mail->Password   = '9OzDs8j_dIED';
        $mail->SMTPSecure = 'ssl';
        $mail->Port       = 465;

        // Recipients
        $mail->setFrom('hello@aphrodailymart.com', 'APHRODAILYMART!');
        
        // Make sure we have a valid email address
        $recipientEmail = $order->shipping_email ?: $order->billing_email ?: Auth::user()->email;
        $recipientName = $order->shipping_name ?: Auth::user()->name;
        
        if (!$recipientEmail) {
            throw new \Exception('No valid recipient email address found');
        }

        $mail->addAddress($recipientEmail, $recipientName);
        
        // Content
        $mail->isHTML(true);
        $mail->Subject = 'Order Confirmation #' . $order->order_number;
        
        // Different email templates based on payment method
        if ($paymentMethod === 'card') {
            $mail->Body = $this->getPaidOrderEmailTemplate($order);
        } else {
            $mail->Body = $this->getCODOrderEmailTemplate($order);
        }

        $mail->send();
        Log::info('Order confirmation email sent successfully', [
            'order_id' => $order->id,
            'recipient' => $recipientEmail
        ]);
        
        // Send admin notification
        $this->sendAdminNotification($order);
        
        return true;

    } catch (\Exception $e) {
        Log::error('Mail sending failed', [
            'error' => $e->getMessage(),
            'order_id' => $order->id,
            'recipient_email' => $recipientEmail ?? 'not set'
        ]);
        return false;
    }
}

private function getPaidOrderEmailTemplate($order)
{
    $itemsHtml = '';
    if ($order->orderItems) {
        foreach ($order->orderItems as $item) {
            $itemsHtml .= "
                <tr>
                    <td>{$item->product_name}</td>
                    <td>{$item->quantity}</td>
                    <td>\${$item->price}</td>
                    <td>\${$item->subtotal}</td>
                </tr>";
        }
    }

    return "
        <h1>Thank you for your order!</h1>
        <p>Dear {$order->shipping_name},</p>
        <p>Your order #{$order->order_number} has been confirmed and paid.</p>
        
        <h2>Order Details:</h2>
        <table border='1' cellpadding='5' cellspacing='0'>
            <tr>
                <th>Item</th>
                <th>Quantity</th>
                <th>Price</th>
                <th>Subtotal</th>
            </tr>
            {$itemsHtml}
        </table>
        
        <p>Subtotal: \${$order->subtotal}</p>
        <p>Tax: \${$order->tax}</p>
        <p>Shipping: \${$order->shipping}</p>
        <p><strong>Total: \${$order->total}</strong></p>
        
        <h2>Shipping Address:</h2>
        <p>
            {$order->shipping_address}<br>
            {$order->shipping_city}, {$order->shipping_state}<br>
            {$order->shipping_zipcode}<br>
            {$order->shipping_country}
        </p>

        ";
}



// private function getPaidOrderEmailTemplate($order)
// {
//     $items = '';
//     foreach ($order->orderItems as $item) {
//         $items .= "
//             <tr>
//                 <td>{$item->product_name}</td>
//                 <td>{$item->quantity}</td>
//                 <td>\${$item->price}</td>
//                 <td>\${$item->subtotal}</td>
//             </tr>";
//     }

//     return "
//         <h1>Thank you for your order!</h1>
//         <p>Dear {$order->shipping_name},</p>
//         <p>Your order #{$order->order_number} has been confirmed and paid.</p>
        
//         <h2>Order Details:</h2>
//         <table border='1' cellpadding='5' cellspacing='0'>
//             <tr>
//                 <th>Item</th>
//                 <th>Quantity</th>
//                 <th>Price</th>
//                 <th>Subtotal</th>
//             </tr>
//             {$items}
//         </table>
        
//         <p>Subtotal: \${$order->subtotal}</p>
//         <p>Tax: \${$order->tax}</p>
//         <p>Shipping: \${$order->shipping}</p>
//         <p><strong>Total: \${$order->total}</strong></p>
        
//         <h2>Shipping Address:</h2>
//         <p>
//             {$order->shipping_address}<br>
//             {$order->shipping_city}, {$order->shipping_state}<br>
//             {$order->shipping_zipcode}<br>
//             {$order->shipping_country}
//         </p>";
// }

private function getCODOrderEmailTemplate($order)
{
    $items = '';
    foreach ($order->orderItems as $item) {
        $items .= "
            <tr>
                <td>{$item->product_name}</td>
                <td>{$item->quantity}</td>
                <td>\${$item->price}</td>
                <td>\${$item->subtotal}</td>
            </tr>";
    }

    return "
        <h1>Thank you for your order!</h1>
        <p>Dear {$order->shipping_name},</p>
        <p>Your order #{$order->order_number} has been confirmed.</p>
        <p><strong>Payment Method: Cash on Delivery</strong></p>
        
        <h2>Order Details:</h2>
        <table border='1' cellpadding='5' cellspacing='0'>
            <tr>
                <th>Item</th>
                <th>Quantity</th>
                <th>Price</th>
                <th>Subtotal</th>
            </tr>
            {$items}
        </table>
        
        <p>Subtotal: \${$order->subtotal}</p>
        <p>Tax: \${$order->tax}</p>
        <p>Shipping: \${$order->shipping}</p>
        <p><strong>Total to be paid: \${$order->total}</strong></p>
        
        
        
        <p>Please have the exact amount ready for payment upon delivery.</p>";
}

private function sendAdminNotification($order)
{
    try {
        $mail = new PHPMailer(true);

        // Server settings
        $mail->isSMTP();
        $mail->Host       = 'aphrodailymart.com';
        $mail->SMTPAuth   = true;
        $mail->Username   = 'hello@aphrodailymart.com'; // Your Gmail address
        $mail->Password   = '9OzDs8j_dIED'; // Your Gmail App Password
        $mail->SMTPSecure = 'ssl';
        $mail->Port       = 465;

        // Recipients
        $mail->setFrom('hello@aphrodailymart.com', 'APHRODAILYMART!');
        //$mail->addAddress('admin@aphrodailymart.com', 'Admin');
        $mail->addAddress('philipchibuike1@gmail.com', 'Admin');

        // Content
        $mail->isHTML(true);
        $mail->Subject = 'New Order Received #' . $order->order_number;
        $mail->Body = $this->getAdminEmailTemplate($order);

        $mail->send();

    } catch (Exception $e) {
        Log::error("Admin notification failed: " . $e->getMessage());
    }
}

private function getAdminEmailTemplate($order)
{
    $items = '';
    foreach ($order->orderItems as $item) {
        $items .= "
            <tr>
                <td>{$item->product_name}</td>
                <td>{$item->quantity}</td>
                <td>\${$item->price}</td>
                <td>\${$item->subtotal}</td>
            </tr>";
    }

    return "
        <h1>New Order Received</h1>
        <p><strong>Order #{$order->order_number}</strong></p>
        <p>Payment Method: {$order->payment_method}</p>
        <p>Payment Status: {$order->payment_status}</p>
        
        <h2>Customer Details:</h2>
        <p>
            Name: {$order->shipping_name}<br>
            Email: {$order->shipping_email}<br>
            Phone: {$order->shipping_phone}
        </p>
        
        <h2>Order Details:</h2>
        <table border='1' cellpadding='5' cellspacing='0'>
            <tr>
                <th>Item</th>
                <th>Quantity</th>
                <th>Price</th>
                <th>Subtotal</th>
            </tr>
            {$items}
        </table>
        
        <p>Subtotal: \${$order->subtotal}</p>
        <p>Tax: \${$order->tax}</p>
        <p>Shipping: \${$order->shipping}</p>
        <p><strong>Total: \${$order->total}</strong></p>
        
        <h2>Shipping Address:</h2>
        <p>
            {$order->shipping_address}<br>
            {$order->shipping_city}, {$order->shipping_state}<br>
            {$order->shipping_zipcode}<br>
            {$order->shipping_country}
        </p>";
}
// ... rest of the controller code ...

}