<?php

namespace App\Http\Controllers;

use App\Models\Order;
use App\Models\OrderItem;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Log;

class OrderController extends Controller
{
    /**
     * Show checkout form.
     */
    public function checkout(Request $request)
    {
        $cart = session()->get('cart', []);
        
        if (empty($cart)) {
            return redirect()->route('cart.index')->with('error', 'Your cart is empty.');
        }

        $cartItems = [];
        $subtotal = 0;

        foreach ($cart as $productId => $item) {
            $product = Product::with('images')->find($productId);
            if ($product) {
                $price = $product->sale_price ?? $product->price;
                $itemTotal = $price * $item['quantity'];
                $subtotal += $itemTotal;
                
                $cartItems[] = [
                    'product' => $product,
                    'quantity' => $item['quantity'],
                    'price' => $price,
                    'subtotal' => $itemTotal,
                ];
            }
        }

        $total = $subtotal;

        return view('orders.checkout', compact('cartItems', 'subtotal', 'total'));
    }

    /**
     * Process the order.
     */
    public function store(Request $request)
    {
        $cart = session()->get('cart', []);
        
        if (empty($cart)) {
            return redirect()->route('cart.index')->with('error', 'Your cart is empty.');
        }

        $request->validate([
            'customer_name' => 'required|string|max:255',
            'customer_email' => 'required|email|max:255',
            'customer_phone' => 'required|string|max:20',
            'customer_address' => 'nullable|string',
            'notes' => 'nullable|string',
        ]);

        // Calculate totals
        $cartItems = [];
        $subtotal = 0;

        foreach ($cart as $productId => $item) {
            $product = Product::with('images')->find($productId);
            if ($product) {
                $price = $product->sale_price ?? $product->price;
                $itemTotal = $price * $item['quantity'];
                $subtotal += $itemTotal;
                
                $cartItems[] = [
                    'product' => $product,
                    'quantity' => $item['quantity'],
                    'price' => $price,
                    'subtotal' => $itemTotal,
                ];
            }
        }

        $total = $subtotal;

        // Create order
        $order = Order::create([
            'order_number' => Order::generateOrderNumber(),
            'customer_name' => $request->customer_name,
            'customer_email' => $request->customer_email,
            'customer_phone' => $request->customer_phone,
            'customer_address' => $request->customer_address,
            'notes' => $request->notes,
            'subtotal' => $subtotal,
            'total' => $total,
            'status' => 'pending',
        ]);

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

        // Clear cart
        session()->forget('cart');

        // Send notifications
        try {
            $this->sendEmailNotification($order);
        } catch (\Exception $e) {
            Log::error('Failed to send email notification: ' . $e->getMessage());
        }

        try {
            $this->sendWhatsAppNotification($order);
        } catch (\Exception $e) {
            Log::error('Failed to send WhatsApp notification: ' . $e->getMessage());
        }

        return redirect()->route('orders.confirmation', $order->id)
            ->with('success', 'Your order has been placed successfully!');
    }

    /**
     * Show order confirmation page.
     */
    public function confirmation($id)
    {
        $order = Order::with('items.product')->findOrFail($id);
        return view('orders.confirmation', compact('order'));
    }

    /**
     * Send email notification to business.
     */
    private function sendEmailNotification(Order $order)
    {
        $businessEmail = env('BUSINESS_EMAIL', config('mail.from.address'));
        
        Mail::send('emails.order-notification', ['order' => $order], function ($message) use ($businessEmail, $order) {
            $message->to($businessEmail)
                    ->subject('New Order: ' . $order->order_number);
        });
    }

    /**
     * Send WhatsApp notification to business.
     */
    private function sendWhatsAppNotification(Order $order)
    {
        $whatsappNumber = '+27818352564';
        
        // Format phone number (remove any non-numeric characters except +)
        $phoneNumber = preg_replace('/[^0-9+]/', '', $whatsappNumber);
        
        // Build WhatsApp message
        $message = "🍰 *New Order Received!*\n\n";
        $message .= "Order Number: *{$order->order_number}*\n";
        $message .= "Customer: {$order->customer_name}\n";
        $message .= "Email: {$order->customer_email}\n";
        $message .= "Phone: {$order->customer_phone}\n";
        
        if ($order->customer_address) {
            $message .= "Address: {$order->customer_address}\n";
        }
        
        $message .= "\n*Items:*\n";
        foreach ($order->items as $item) {
            $message .= "• {$item->product_name} x{$item->quantity} - R" . number_format($item->subtotal, 2) . "\n";
        }
        
        $message .= "\n*Total: R" . number_format($order->total, 2) . "*\n";
        
        if ($order->notes) {
            $message .= "\nNotes: {$order->notes}\n";
        }

        // Create WhatsApp URL
        $whatsappUrl = 'https://wa.me/' . $phoneNumber . '?text=' . urlencode($message);
        
        // For now, we'll log it. In production, you might want to use a WhatsApp API
        Log::info('WhatsApp notification URL: ' . $whatsappUrl);
        
        // You can also use file_get_contents or curl to send if you have WhatsApp Business API
        // For now, we'll just log it so the business can see the URL in logs
    }
}
