<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\Product;
use App\Models\Cart;
use App\Models\SystemSetting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;
use App\Mail\OrderPlaced;
use App\Mail\NewOrderNotification;
use App\Mail\PaybillPaymentVerification;
use App\Mail\PaybillPaymentApproved;

class CheckoutController extends Controller
{
    // Note: We don't need showCheckout() anymore since route uses closure
    
    public function processCODCheckout(Request $request)
    {
        \Log::info('=== COD CHECKOUT PROCESS STARTED ===');
        \Log::info('User ID: ' . (auth()->check() ? auth()->id() : 'Not logged in'));
        
        // Get cart from database for logged-in users
        if (auth()->check()) {
            $cartItems = Cart::with(['product', 'deal'])
                ->where('user_id', auth()->id())
                ->get();
            
            if ($cartItems->count() == 0) {
                \Log::error('Cart is empty from database!');
                return redirect()->route('checkout')
                    ->with('error', 'Your cart appears to be empty. Please add items to cart and try again.')
                    ->withInput();
            }
            
            // Convert to array format with deal prices
            $cart = [];
            $originalSubtotal = 0;
            $discountedSubtotal = 0;
            $totalDiscount = 0;
            
            foreach ($cartItems as $item) {
                if ($item->product) {
                    $originalPrice = $item->original_price ?? $item->product->price;
                    $actualPrice = $item->actual_price ?? $item->product->price;
                    $quantity = $item->quantity;
                    
                    $cart[] = [
                        'product_id' => $item->product_id,
                        'name' => $item->product->name,
                        'original_price' => $originalPrice,
                        'price' => $actualPrice, // Use actual price (with deal if applicable)
                        'quantity' => $quantity,
                        'cart_id' => $item->id,
                        'deal_id' => $item->deal_id,
                        'deal_type' => $item->deal_type,
                        'deal_discount_value' => $item->deal_discount_value,
                    ];
                    
                    $originalSubtotal += $originalPrice * $quantity;
                    $discountedSubtotal += $actualPrice * $quantity;
                    $totalDiscount += ($originalPrice - $actualPrice) * $quantity;
                }
            }
            \Log::info('Cart loaded from database. Count: ' . count($cart));
            \Log::info('Original Subtotal: ' . $originalSubtotal);
            \Log::info('Discounted Subtotal: ' . $discountedSubtotal);
            \Log::info('Total Discount: ' . $totalDiscount);
        } else {
            // For guests, get from session
            $cart = session()->get('cart', []);
            \Log::info('Cart loaded from session. Count: ' . count($cart));
            
            if (empty($cart)) {
                \Log::error('Cart is empty from session!');
                return redirect()->route('checkout')
                    ->with('error', 'Your cart appears to be empty. Please add items to cart and try again.')
                    ->withInput();
            }
            
            // Calculate totals for guest cart
            $originalSubtotal = 0;
            $discountedSubtotal = 0;
            $totalDiscount = 0;
            
            foreach ($cart as $item) {
                $originalPrice = $item['original_price'] ?? $item['price'];
                $actualPrice = $item['price'];
                $quantity = $item['quantity'];
                
                $originalSubtotal += $originalPrice * $quantity;
                $discountedSubtotal += $actualPrice * $quantity;
                $totalDiscount += ($originalPrice - $actualPrice) * $quantity;
            }
            
            \Log::info('Guest Cart - Original Subtotal: ' . $originalSubtotal);
            \Log::info('Guest Cart - Discounted Subtotal: ' . $discountedSubtotal);
            \Log::info('Guest Cart - Total Discount: ' . $totalDiscount);
        }
        
        // Validate shipping information
        $validated = $request->validate([
            'shipping_name' => 'required|string|max:255',
            'shipping_email' => 'required|email|max:255',
            'shipping_phone' => 'required|string|max:20',
            'shipping_address' => 'required|string',
            'shipping_city' => 'required|string|max:100',
            'shipping_state' => 'required|string|max:100',
            'shipping_zip' => 'required|string|max:20',     
            'shipping_country' => 'required|string|max:100', 
            'shipping_notes' => 'nullable|string',
            'billing_same' => 'nullable',
            'billing_name' => 'nullable|string|max:255',
            'billing_address' => 'nullable|string',
            'payment_method' => 'required|in:cod',
        ], [
            'shipping_name.required' => 'Your name is required',
            'shipping_email.required' => 'Your email is required',
            'shipping_phone.required' => 'Your phone number is required',
            'shipping_address.required' => 'Shipping address is required',
            'shipping_city.required' => 'City is required',
            'shipping_state.required' => 'State/Region is required',
            'shipping_zip.required' => 'Zip/Postal code is required',
            'shipping_country.required' => 'Country is required',
            'payment_method.required' => 'Please select a payment method',
        ]);
        
        \Log::info('COD Validation passed');
        
        // Use discounted subtotal (with deals applied)
        $subtotal = $discountedSubtotal;
        $tax = 0;
        $shipping = 0;
        $total = $subtotal;
        
        // Prepare shipping address
        $shippingAddress = [
            'name' => $validated['shipping_name'],
            'email' => $validated['shipping_email'],
            'phone' => $validated['shipping_phone'],
            'address' => $validated['shipping_address'],
            'city' => $validated['shipping_city'],
            'state' => $validated['shipping_state'],
            'zip' => $validated['shipping_zip'],
            'country' => $validated['shipping_country'],
            'notes' => $validated['shipping_notes'] ?? null,
        ];
        
        // Prepare billing address
        if (isset($validated['billing_same']) && $validated['billing_same'] == 'on') {
            $billingAddress = $shippingAddress;
        } else {
            $billingAddress = [
                'name' => $validated['billing_name'] ?? $validated['shipping_name'],
                'email' => $validated['shipping_email'],
                'phone' => $validated['shipping_phone'],
                'address' => $validated['billing_address'] ?? $validated['shipping_address'],
                'city' => $validated['shipping_city'],
                'state' => $validated['shipping_state'],
                'zip' => $validated['shipping_zip'],
                'country' => $validated['shipping_country'],
            ];
        }
        
        try {
            \Log::info('Creating COD order...');
            
            // Create the order
            $order = Order::create([
                'order_number' => Order::generateOrderNumber(),
                'user_id' => Auth::id(),
                'subtotal' => $subtotal,
                'tax' => $tax,
                'shipping' => $shipping,
                'total' => $total,
                'status' => 'pending',
                'payment_status' => 'pending',
                'payment_method' => 'cod',
                'shipping_address' => json_encode($shippingAddress),
                'billing_address' => json_encode($billingAddress),
                'customer_name' => $validated['shipping_name'],
                'customer_email' => $validated['shipping_email'],
                'customer_phone' => $validated['shipping_phone'],
                'notes' => 'COD Order - Shipping fee to be calculated. Customer will be contacted.' . 
                          ($totalDiscount > 0 ? ' Deal savings: Ksh ' . number_format($totalDiscount, 2) . '.' : ''),
            ]);
            
            \Log::info('COD Order created with ID: ' . $order->id . ', Number: ' . $order->order_number);
            \Log::info('Order subtotal (with deals): ' . $subtotal);
            \Log::info('Total discount applied: ' . $totalDiscount);
            
            // Create order items with deal prices
            foreach ($cart as $item) {
                $product = Product::find($item['product_id']);
                
                OrderItem::create([
                    'order_id' => $order->id,
                    'product_id' => $item['product_id'],
                    'product_name' => $item['name'],
                    'original_price' => $item['original_price'], // Store original price
                    'price' => $item['price'], // Store actual price (with deal)
                    'quantity' => $item['quantity'],
                    'total' => $item['price'] * $item['quantity'],
                    'deal_id' => $item['deal_id'] ?? null,
                    'deal_type' => $item['deal_type'] ?? null,
                    'deal_discount_value' => $item['deal_discount_value'] ?? null,
                ]);
                
                // Update product stock
                if ($product) {
                    $product->decrement('stock', $item['quantity']);
                }
            }
            
            // Clear the cart after successful order
            if (auth()->check()) {
                // Clear from database
                Cart::where('user_id', auth()->id())->delete();
                \Log::info('Cart cleared from database');
            } else {
                // Clear from session
                session()->forget('cart');
                \Log::info('Cart cleared from session');
            }
            
            // SEND EMAILS - FIXED: Use queue or try-catch with proper error handling
            $this->sendCODEmails($order, $validated, $totalDiscount);
            
            $successMessage = 'Order placed successfully! You have selected Cash on Delivery. Our team will contact you within 24 hours to discuss shipping costs and finalize your order.';
            
            if ($totalDiscount > 0) {
                $successMessage .= ' You saved Ksh ' . number_format($totalDiscount, 2) . ' with deals!';
            }
            
            \Log::info('Redirecting to order confirmation for COD order: ' . $order->id);
            
            return redirect()->route('order.confirmation', ['order' => $order->id])
                 ->with('success', $successMessage);
                
        } catch (\Exception $e) {
            \Log::error('COD Checkout Error: ' . $e->getMessage());
            \Log::error($e->getTraceAsString());
            
            return redirect()->back()
                ->with('error', 'There was an error processing your order. Please try again.')
                ->withInput();
        }
    }
    
    /**
     * Process Direct Paybill Checkout
     */
    public function processPaybillCheckout(Request $request)
    {
        \Log::info('=== PAYBILL CHECKOUT PROCESS STARTED ===');
        \Log::info('User ID: ' . (auth()->check() ? auth()->id() : 'Not logged in'));
        
        // Get cart from database for logged-in users
        if (auth()->check()) {
            $cartItems = Cart::with(['product', 'deal'])
                ->where('user_id', auth()->id())
                ->get();
            
            if ($cartItems->count() == 0) {
                \Log::error('Cart is empty from database!');
                return redirect()->route('checkout')
                    ->with('error', 'Your cart appears to be empty. Please add items to cart and try again.')
                    ->withInput();
            }
            
            // Convert to array format with deal prices
            $cart = [];
            $originalSubtotal = 0;
            $discountedSubtotal = 0;
            $totalDiscount = 0;
            
            foreach ($cartItems as $item) {
                if ($item->product) {
                    $originalPrice = $item->original_price ?? $item->product->price;
                    $actualPrice = $item->actual_price ?? $item->product->price;
                    $quantity = $item->quantity;
                    
                    $cart[] = [
                        'product_id' => $item->product_id,
                        'name' => $item->product->name,
                        'original_price' => $originalPrice,
                        'price' => $actualPrice, // Use actual price (with deal if applicable)
                        'quantity' => $quantity,
                        'cart_id' => $item->id,
                        'deal_id' => $item->deal_id,
                        'deal_type' => $item->deal_type,
                        'deal_discount_value' => $item->deal_discount_value,
                    ];
                    
                    $originalSubtotal += $originalPrice * $quantity;
                    $discountedSubtotal += $actualPrice * $quantity;
                    $totalDiscount += ($originalPrice - $actualPrice) * $quantity;
                }
            }
            \Log::info('Cart loaded from database. Count: ' . count($cart));
            \Log::info('Original Subtotal: ' . $originalSubtotal);
            \Log::info('Discounted Subtotal: ' . $discountedSubtotal);
            \Log::info('Total Discount: ' . $totalDiscount);
        } else {
            // For guests, get from session
            $cart = session()->get('cart', []);
            \Log::info('Cart loaded from session. Count: ' . count($cart));
            
            if (empty($cart)) {
                \Log::error('Cart is empty from session!');
                return redirect()->route('checkout')
                    ->with('error', 'Your cart appears to be empty. Please add items to cart and try again.')
                    ->withInput();
            }
            
            // Calculate totals for guest cart
            $originalSubtotal = 0;
            $discountedSubtotal = 0;
            $totalDiscount = 0;
            
            foreach ($cart as $item) {
                $originalPrice = $item['original_price'] ?? $item['price'];
                $actualPrice = $item['price'];
                $quantity = $item['quantity'];
                
                $originalSubtotal += $originalPrice * $quantity;
                $discountedSubtotal += $actualPrice * $quantity;
                $totalDiscount += ($originalPrice - $actualPrice) * $quantity;
            }
            
            \Log::info('Guest Cart - Original Subtotal: ' . $originalSubtotal);
            \Log::info('Guest Cart - Discounted Subtotal: ' . $discountedSubtotal);
            \Log::info('Guest Cart - Total Discount: ' . $totalDiscount);
        }
        
        // Validate shipping information
        $validated = $request->validate([
            'shipping_name' => 'required|string|max:255',
            'shipping_email' => 'required|email|max:255',
            'shipping_phone' => 'required|string|max:20',
            'shipping_address' => 'required|string',
            'shipping_city' => 'required|string|max:100',
            'shipping_state' => 'required|string|max:100',
            'shipping_zip' => 'required|string|max:20',     
            'shipping_country' => 'required|string|max:100', 
            'shipping_notes' => 'nullable|string',
            'billing_same' => 'nullable',
            'billing_name' => 'nullable|string|max:255',
            'billing_address' => 'nullable|string',
            'payment_method' => 'required|in:paybill',
        ], [
            'shipping_name.required' => 'Your name is required',
            'shipping_email.required' => 'Your email is required',
            'shipping_phone.required' => 'Your phone number is required',
            'shipping_address.required' => 'Shipping address is required',
            'shipping_city.required' => 'City is required',
            'shipping_state.required' => 'State/Region is required',
            'shipping_zip.required' => 'Zip/Postal code is required',
            'shipping_country.required' => 'Country is required',
            'payment_method.required' => 'Please select a payment method',
        ]);
        
        \Log::info('Paybill Validation passed');
        
        // Use discounted subtotal (with deals applied)
        $subtotal = $discountedSubtotal;
        $tax = 0;
        $shipping = 0;
        $total = $subtotal;
        
        // Get paybill details from system settings
        $paybillDetails = SystemSetting::getPaybillDetails();
        
        // Prepare shipping address
        $shippingAddress = [
            'name' => $validated['shipping_name'],
            'email' => $validated['shipping_email'],
            'phone' => $validated['shipping_phone'],
            'address' => $validated['shipping_address'],
            'city' => $validated['shipping_city'],
            'state' => $validated['shipping_state'],
            'zip' => $validated['shipping_zip'],
            'country' => $validated['shipping_country'],
            'notes' => $validated['shipping_notes'] ?? null,
        ];
        
        // Prepare billing address
        if (isset($validated['billing_same']) && $validated['billing_same'] == 'on') {
            $billingAddress = $shippingAddress;
        } else {
            $billingAddress = [
                'name' => $validated['billing_name'] ?? $validated['shipping_name'],
                'email' => $validated['shipping_email'],
                'phone' => $validated['shipping_phone'],
                'address' => $validated['billing_address'] ?? $validated['shipping_address'],
                'city' => $validated['shipping_city'],
                'state' => $validated['shipping_state'],
                'zip' => $validated['shipping_zip'],
                'country' => $validated['shipping_country'],
            ];
        }
        
        try {
            \Log::info('Creating Paybill order...');
            
            // Create the order with special payment status
            $order = Order::create([
                'order_number' => Order::generateOrderNumber(),
                'user_id' => Auth::id(),
                'subtotal' => $subtotal,
                'tax' => $tax,
                'shipping' => $shipping,
                'total' => $total,
                'status' => 'pending_payment_verification', // Special status for paybill
                'payment_status' => 'pending_verification', // Special payment status
                'payment_method' => 'paybill',
                'shipping_address' => json_encode($shippingAddress),
                'billing_address' => json_encode($billingAddress),
                'customer_name' => $validated['shipping_name'],
                'customer_email' => $validated['shipping_email'],
                'customer_phone' => $validated['shipping_phone'],
                'notes' => 'Direct Paybill Order - Payment pending verification. ' .
                          'Paybill: ' . ($paybillDetails['paybill_number'] ?? 'N/A') . ', ' .
                          'Account: ' . ($paybillDetails['account_number'] ?? 'N/A') . '. ' .
                          ($totalDiscount > 0 ? 'Deal savings: Ksh ' . number_format($totalDiscount, 2) . '.' : ''),
            ]);
            
            \Log::info('Paybill Order created with ID: ' . $order->id . ', Number: ' . $order->order_number);
            \Log::info('Order subtotal (with deals): ' . $subtotal);
            \Log::info('Total discount applied: ' . $totalDiscount);
            
            // Create order items with deal prices
            foreach ($cart as $item) {
                $product = Product::find($item['product_id']);
                
                OrderItem::create([
                    'order_id' => $order->id,
                    'product_id' => $item['product_id'],
                    'product_name' => $item['name'],
                    'original_price' => $item['original_price'], // Store original price
                    'price' => $item['price'], // Store actual price (with deal)
                    'quantity' => $item['quantity'],
                    'total' => $item['price'] * $item['quantity'],
                    'deal_id' => $item['deal_id'] ?? null,
                    'deal_type' => $item['deal_type'] ?? null,
                    'deal_discount_value' => $item['deal_discount_value'] ?? null,
                ]);
                
                // DON'T update product stock yet - wait for payment verification
                // Stock will be updated when admin verifies payment
            }
            
            // Clear the cart after successful order
            if (auth()->check()) {
                // Clear from database
                Cart::where('user_id', auth()->id())->delete();
                \Log::info('Cart cleared from database');
            } else {
                // Clear from session
                session()->forget('cart');
                \Log::info('Cart cleared from session');
            }
            
            // Send Paybill-specific emails
            $this->sendPaybillEmails($order, $validated, $totalDiscount, $paybillDetails);
            
            $successMessage = 'Order placed successfully! You have selected Direct Paybill. ';
            $successMessage .= 'Please pay Ksh ' . number_format($total, 2) . ' to Paybill: ' . 
                              ($paybillDetails['paybill_number'] ?? 'N/A') . ' Account: ' . 
                              ($paybillDetails['account_number'] ?? 'N/A') . '. ';
            $successMessage .= 'Our admin will verify your payment and then process your order. You will receive an email confirmation once payment is verified.';
            
            if ($totalDiscount > 0) {
                $successMessage .= ' You saved Ksh ' . number_format($totalDiscount, 2) . ' with deals!';
            }
            
            \Log::info('Redirecting to order confirmation for Paybill order: ' . $order->id);
            
            return redirect()->route('order.confirmation', ['order' => $order->id])
                 ->with('success', $successMessage)
                 ->with('payment_pending', true);
                
        } catch (\Exception $e) {
            \Log::error('Paybill Checkout Error: ' . $e->getMessage());
            \Log::error($e->getTraceAsString());
            
            return redirect()->back()
                ->with('error', 'There was an error processing your order. Please try again.')
                ->withInput();
        }
    }
    
    /**
     * Send Paybill-specific emails
     */
    private function sendPaybillEmails($order, $validated, $totalDiscount = 0, $paybillDetails = [])
    {
        try {
            \Log::info('Sending Paybill emails...');
            
            // Check if mail is configured
            $mailConfig = config('mail');
            
            // 1. Send email to customer
            \Log::info('Attempting to send customer email to: ' . $validated['shipping_email']);
            
            // Check if email is valid
            if (!filter_var($validated['shipping_email'], FILTER_VALIDATE_EMAIL)) {
                \Log::error('Invalid email address: ' . $validated['shipping_email']);
                return;
            }
            
            // Send order confirmation to customer
            $customerEmail = new \App\Mail\OrderPlaced($order, 'paybill', $totalDiscount);
            Mail::to($validated['shipping_email'])->send($customerEmail);
            
            \Log::info('Customer email sent successfully to: ' . $validated['shipping_email']);
            
            // 2. Get admin emails from database
            $adminEmails = User::where('role', 'admin')
                ->whereNotNull('email')
                ->pluck('email')
                ->filter(function($email) {
                    return filter_var($email, FILTER_VALIDATE_EMAIL);
                })
                ->toArray();
            
            \Log::info('Admin emails from database: ' . json_encode($adminEmails));
            
            // Send payment verification email to all admins
            if (!empty($adminEmails)) {
                \Log::info('Attempting to send admin verification emails to: ' . implode(', ', $adminEmails));
                
                $adminNotification = new \App\Mail\PaybillPaymentVerification($order, $paybillDetails, $totalDiscount);
                Mail::to($adminEmails)->send($adminNotification);
                
                \Log::info('Admin verification notification sent to all admins');
            } else {
                \Log::warning('No valid admin emails found in database');
            }
            
            \Log::info('Paybill emails sent successfully');
            
        } catch (\Exception $e) {
            \Log::error('Paybill email sending failed: ' . $e->getMessage());
            \Log::error('Email error trace: ' . $e->getTraceAsString());
            // Don't throw error - continue with order placement
        }
    }
    
    private function sendCODEmails($order, $validated, $totalDiscount = 0)
    {
        try {
            \Log::info('Sending COD emails...');
            
            // Check if mail is configured
            $mailConfig = config('mail');
            \Log::info('Mail configuration check:', [
                'driver' => $mailConfig['default'] ?? 'not set',
                'host' => $mailConfig['mailers']['smtp']['host'] ?? 'not set',
                'from_address' => $mailConfig['from']['address'] ?? 'not set'
            ]);
            
            // 1. Send email to customer
            \Log::info('Attempting to send customer email to: ' . $validated['shipping_email']);
            
            // Check if email is valid
            if (!filter_var($validated['shipping_email'], FILTER_VALIDATE_EMAIL)) {
                \Log::error('Invalid email address: ' . $validated['shipping_email']);
                return;
            }
            
            // Send using queue or directly with error handling
            $customerEmail = new \App\Mail\OrderPlaced($order, 'cod', $totalDiscount);
            Mail::to($validated['shipping_email'])->send($customerEmail);
            
            \Log::info('Customer email sent successfully to: ' . $validated['shipping_email']);
            
            // 2. Get admin emails from database
            $adminEmails = User::where('role', 'admin')
                ->whereNotNull('email')
                ->pluck('email')
                ->filter(function($email) {
                    return filter_var($email, FILTER_VALIDATE_EMAIL);
                })
                ->toArray();
            
            \Log::info('Admin emails from database for COD: ' . json_encode($adminEmails));
            
            // Send email to all admins
            if (!empty($adminEmails)) {
                \Log::info('Attempting to send admin email to: ' . implode(', ', $adminEmails));
                
                $adminNotification = new \App\Mail\NewOrderNotification($order, 'cod', $totalDiscount);
                Mail::to($adminEmails)->send($adminNotification);
                
                \Log::info('Admin notification sent to all admins');
            } else {
                \Log::warning('No valid admin emails found in database for COD notification');
            }
            
            \Log::info('COD emails sent successfully');
            
        } catch (\Exception $e) {
            \Log::error('Email sending failed: ' . $e->getMessage());
            \Log::error('Email error trace: ' . $e->getTraceAsString());
            // Don't throw error - continue with order placement
            // But log it for debugging
        }
    }
    
    public function orderConfirmation(Order $order)
    {
        if ($order->user_id !== Auth::id() && !Auth::user()->isadmin) {
            abort(403);
        }
        
        $shippingNote = "Shipping fee will be calculated based on your location. 
                        Our team will contact you within 24 hours to confirm shipping costs.";
        
        return view('order-confirmation', compact('order', 'shippingNote'));
    }
    
    /**
     * Admin: Verify Paybill Payment
     */
    public function verifyPaybillPayment(Request $request, Order $order)
    {
        if (!Auth::user()->isadmin) {
            abort(403);
        }
        
        // Validate the order can be verified
        if ($order->payment_method !== 'paybill' || $order->payment_status !== 'pending_verification') {
            return redirect()->back()
                ->with('error', 'This order cannot be verified or has already been verified.');
        }
        
        // Update order status
        $order->update([
            'status' => 'processing',
            'payment_status' => 'paid',
            'notes' => $order->notes . "\nPayment verified by admin on " . now()->format('Y-m-d H:i:s') . 
                      ($request->notes ? "\nAdmin notes: " . $request->notes : ''),
        ]);
        
        // Update product stock (since we didn't do it during checkout)
        foreach ($order->items as $item) {
            $product = Product::find($item->product_id);
            if ($product) {
                $product->decrement('stock', $item->quantity);
            }
        }
        
        // Send payment approved email to customer
        $this->sendPaybillApprovedEmail($order);
        
        // Log the verification
        \Log::info('Paybill payment verified for order #' . $order->order_number . ' by admin: ' . Auth::user()->id);
        
        return redirect()->back()
            ->with('success', 'Payment verified successfully! Order is now being processed.');
    }
    
    /**
     * Send Paybill payment approved email to customer
     */
    private function sendPaybillApprovedEmail($order)
    {
        try {
            // Get admin emails from database
            $adminEmails = User::where('role', 'admin')
                ->whereNotNull('email')
                ->pluck('email')
                ->filter(function($email) {
                    return filter_var($email, FILTER_VALIDATE_EMAIL);
                })
                ->toArray();
            
            // Send to customer
            $customerEmail = new \App\Mail\PaybillPaymentApproved($order);
            Mail::to($order->customer_email)->send($customerEmail);
            
            \Log::info('Paybill payment approved email sent to customer: ' . $order->customer_email);
            
            // Send to all admins as confirmation
            if (!empty($adminEmails)) {
                $adminNotification = new \App\Mail\NewOrderNotification($order, 'paybill', 0);
                Mail::to($adminEmails)->send($adminNotification);
                
                \Log::info('Paybill approval notification sent to all admins: ' . implode(', ', $adminEmails));
            } else {
                \Log::warning('No admin emails found in database for approval notification');
            }
            
        } catch (\Exception $e) {
            \Log::error('Paybill approved email sending failed: ' . $e->getMessage());
        }
    }
    
    /**
     * Admin: Reject Paybill Payment
     */
    public function rejectPaybillPayment(Request $request, Order $order)
    {
        if (!Auth::user()->isadmin) {
            abort(403);
        }
        
        // Validate the order can be rejected
        if ($order->payment_method !== 'paybill' || $order->payment_status !== 'pending_verification') {
            return redirect()->back()
                ->with('error', 'This order cannot be rejected or has already been processed.');
        }
        
        $validated = $request->validate([
            'rejection_reason' => 'required|string|min:5|max:500',
        ]);
        
        // Update order status
        $order->update([
            'status' => 'cancelled',
            'payment_status' => 'failed',
            'notes' => $order->notes . "\nPayment rejected by admin on " . now()->format('Y-m-d H:i:s') . 
                      "\nReason: " . $validated['rejection_reason'],
        ]);
        
        // Send rejection email to customer
        $this->sendPaybillRejectedEmail($order, $validated['rejection_reason']);
        
        // Log the rejection
        \Log::info('Paybill payment rejected for order #' . $order->order_number . ' by admin: ' . Auth::user()->id);
        
        return redirect()->back()
            ->with('success', 'Payment rejected successfully! Customer has been notified.');
    }
    
    /**
     * Send Paybill payment rejected email to customer
     */
    private function sendPaybillRejectedEmail($order, $reason)
    {
        try {
            // You might want to create a specific email template for this
            $subject = 'Payment Rejected for Order #' . $order->order_number;
            $content = "Dear " . $order->customer_name . ",\n\n" .
                      "We regret to inform you that your payment for order #" . $order->order_number . " has been rejected.\n" .
                      "Reason: " . $reason . "\n\n" .
                      "If you believe this is an error, please contact our support team.\n\n" .
                      "Best regards,\n" .
                      "The " . config('app.name') . " Team";
            
            Mail::raw($content, function($message) use ($order, $subject) {
                $message->to($order->customer_email)
                        ->subject($subject);
            });
            
            \Log::info('Paybill payment rejected email sent to: ' . $order->customer_email);
            
        } catch (\Exception $e) {
            \Log::error('Paybill rejected email sending failed: ' . $e->getMessage());
        }
    }
}