<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;

class CheckoutController extends Controller {
    private function cartItems() {
        return \App\Models\CartItem::with("product")
            ->where("session_id", session()->getId())->get();
    }

    private function calculateTotals(float $subtotal): array {
        $coupon   = session("coupon");
        $discount = $coupon ? (float)$coupon["discount"] : 0;
        $shipping = $subtotal - $discount >= 499 ? 0 : 60;
        $total    = max(0, $subtotal - $discount) + $shipping;
        return compact("discount", "shipping", "total", "coupon");
    }

    public function index() {
        $items    = $this->cartItems();
        $subtotal = $items->sum(fn($i) => $i->product->price * $i->qty);
        $totals   = $this->calculateTotals($subtotal);
        $rzpKey   = env("RAZORPAY_KEY", "");
        return view("checkout", compact("items", "subtotal", "rzpKey") + $totals);
    }

    public function store(Request $request) {
        $request->validate([
            "name" => "required|string|max:100",
            "email" => "required|email",
            "phone" => "required|string|max:15",
            "address" => "required|string",
            "city" => "required|string",
            "pincode" => "required|string|max:10",
        ]);

        $items = $this->cartItems();
        if ($items->isEmpty()) return redirect()->route("cart")->with("error", "Cart is empty.");

        $subtotal = $items->sum(fn($i) => $i->product->price * $i->qty);
        $totals   = $this->calculateTotals($subtotal);

        $order = \App\Models\Order::create([
            "order_number"   => \App\Models\Order::generateNumber(),
            "user_id"        => auth()->id(),
            "name"           => $request->name,
            "email"          => $request->email,
            "phone"          => $request->phone,
            "address"        => $request->address,
            "city"           => $request->city,
            "pincode"        => $request->pincode,
            "subtotal"       => $subtotal,
            "discount"       => $totals["discount"],
            "coupon_id"      => $totals["coupon"]["id"] ?? null,
            "coupon_code"    => $totals["coupon"]["code"] ?? null,
            "shipping_cost"  => $totals["shipping"],
            "total"          => $totals["total"],
            "payment_method" => "cod",
            "status"         => "placed",
        ]);

        foreach ($items as $item) {
            $order->items()->create([
                "product_id" => $item->product_id,
                "name"       => $item->product->name,
                "image"      => $item->product->image,
                "price"      => $item->product->price,
                "old_price"  => $item->product->old_price,
                "qty"        => $item->qty,
            ]);
        }

        if ($totals["coupon"]) { \App\Models\Coupon::find($totals["coupon"]["id"])->increment("used_count"); }

        \App\Models\CartItem::where("session_id", session()->getId())->delete();
        session()->forget("coupon");

        try { \Mail::to($order->email)->send(new \App\Mail\OrderConfirmationMail($order)); } catch (\Throwable) {}

        return redirect()->route("order.success", $order->order_number);
    }

    public function razorpayCallback(Request $request) {
        $request->validate([
            "name" => "required", "email" => "required|email", "phone" => "required",
            "address" => "required", "city" => "required", "pincode" => "required",
            "razorpay_payment_id" => "required",
        ]);

        $api = new \Razorpay\Api\Api(env("RAZORPAY_KEY"), env("RAZORPAY_SECRET"));
        try {
            $api->utility->verifyPaymentSignature([
                "razorpay_order_id"   => $request->razorpay_order_id,
                "razorpay_payment_id" => $request->razorpay_payment_id,
                "razorpay_signature"  => $request->razorpay_signature,
            ]);
        } catch (\Exception) {
            return redirect()->route("checkout")->with("error", "Payment verification failed.");
        }

        $items    = $this->cartItems();
        $subtotal = $items->sum(fn($i) => $i->product->price * $i->qty);
        $totals   = $this->calculateTotals($subtotal);

        $order = \App\Models\Order::create([
            "order_number"   => \App\Models\Order::generateNumber(),
            "user_id"        => auth()->id(),
            "name"           => $request->name,
            "email"          => $request->email,
            "phone"          => $request->phone,
            "address"        => $request->address,
            "city"           => $request->city,
            "pincode"        => $request->pincode,
            "subtotal"       => $subtotal,
            "discount"       => $totals["discount"],
            "coupon_id"      => $totals["coupon"]["id"] ?? null,
            "coupon_code"    => $totals["coupon"]["code"] ?? null,
            "shipping_cost"  => $totals["shipping"],
            "total"          => $totals["total"],
            "payment_method" => "online",
            "payment_id"     => $request->razorpay_payment_id,
            "status"         => "placed",
        ]);

        foreach ($items as $item) {
            $order->items()->create([
                "product_id" => $item->product_id,
                "name"       => $item->product->name,
                "image"      => $item->product->image,
                "price"      => $item->product->price,
                "old_price"  => $item->product->old_price,
                "qty"        => $item->qty,
            ]);
        }

        if ($totals["coupon"]) { \App\Models\Coupon::find($totals["coupon"]["id"])->increment("used_count"); }

        \App\Models\CartItem::where("session_id", session()->getId())->delete();
        session()->forget("coupon");

        try { \Mail::to($order->email)->send(new \App\Mail\OrderConfirmationMail($order)); } catch (\Throwable) {}

        return redirect()->route("order.success", $order->order_number);
    }

    public function createRazorpayOrder(Request $request) {
        $items    = $this->cartItems();
        $subtotal = $items->sum(fn($i) => $i->product->price * $i->qty);
        $totals   = $this->calculateTotals($subtotal);
        $amountPaise = (int)($totals["total"] * 100);

        $api = new \Razorpay\Api\Api(env("RAZORPAY_KEY"), env("RAZORPAY_SECRET"));
        $rzpOrder = $api->order->create(["amount" => $amountPaise, "currency" => "INR", "receipt" => "rcpt_" . time()]);
        return response()->json(["id" => $rzpOrder->id, "amount" => $amountPaise]);
    }

    public function success(string $orderNumber) {
        $order = \App\Models\Order::where("order_number", $orderNumber)->with("items")->firstOrFail();
        return view("order-success", compact("order"));
    }
}
