<?php

namespace App\Http\Controllers;

use App\Models\Order;
use App\Models\OrderItem;
use App\Models\Product;
use App\Services\MpesaService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;
use App\Mail\OrderPlacedMail;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class CheckoutController extends Controller
{
    protected $mpesaService;

    public function __construct(MpesaService $mpesaService)
    {
        $this->mpesaService = $mpesaService;
    }

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

        $user = Auth::user();
        return view('cart.checkout', compact('cart', 'user'));
    }

    public function process(Request $request)
    {
        $cart = session()->get('cart', []);
        if (empty($cart)) {
            return redirect()->route('cart.index')->with('error', 'Your cart is empty!');
        }

        $request->validate([
            'name' => 'required|string|max:255',
            'phone' => 'required|string|max:20',
            'shipping_address' => 'required|string',
            'payment_method' => 'required|in:mpesa,cod',
            'notes' => 'nullable|string',
        ]);

        $deliveryFee = 350.00; // Flat delivery charge
        $subtotal = 0;
        foreach ($cart as $item) {
            $subtotal += $item['price'] * $item['quantity'];
        }
        $totalAmount = $subtotal + $deliveryFee;

        // Start database transaction
        DB::beginTransaction();

        try {
            $order = Order::create([
                'user_id' => Auth::id(),
                'order_number' => 'MJ-' . strtoupper(Str::random(8)),
                'total_amount' => $totalAmount,
                'shipping_address' => $request->shipping_address,
                'phone' => $request->phone,
                'payment_method' => $request->payment_method,
                'payment_status' => 'pending',
                'status' => 'pending',
                'notes' => $request->notes,
                'delivery_fee' => $deliveryFee,
            ]);

            foreach ($cart as $id => $item) {
                OrderItem::create([
                    'order_id' => $order->id,
                    'product_id' => $id,
                    'quantity' => $item['quantity'],
                    'price' => $item['price'],
                ]);

                // Update product stock if available
                $product = Product::find($id);
                if ($product) {
                    $product->decrement('stock_quantity', $item['quantity']);
                    if ($product->stock_quantity <= 0) {
                        $product->update(['stock_status' => 'out_of_stock']);
                    }
                }
            }

            DB::commit();

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

            // Send Email Notification
            try {
                Mail::to(Auth::user()->email)->send(new OrderPlacedMail($order));
            } catch (\Exception $e) {
                // Log error but don't fail checkout
                \Log::error('Failed to send order email: ' . $e->getMessage());
            }

            // Handle M-Pesa trigger
            if ($request->payment_method === 'mpesa') {
                // Trigger STK Push (returns boolean/response)
                $response = $this->mpesaService->initiateStkPush($request->phone, $totalAmount, $order->order_number);
                
                return redirect()->route('order.track', $order->order_number)
                    ->with('success', 'Order placed! An M-Pesa payment request has been sent to your phone.')
                    ->with('trigger_mpesa_modal', true);
            }

            return redirect()->route('order.track', $order->order_number)
                ->with('success', 'Order placed successfully! Cash on Delivery confirmed.');

        } catch (\Exception $e) {
            DB::rollBack();
            return back()->with('error', 'Something went wrong: ' . $e->getMessage());
        }
    }

    public function track($orderNumber)
    {
        $order = Order::where('order_number', $orderNumber)->with('items.product')->firstOrFail();
        return view('cart.track', compact('order'));
    }

    public function simulateMpesaPayment($orderNumber)
    {
        $order = Order::where('order_number', $orderNumber)->firstOrFail();
        
        // Simulating the callback success
        $order->update([
            'payment_status' => 'paid',
            'status' => 'confirmed'
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Payment received successfully via M-Pesa. Order confirmed!'
        ]);
    }
}
