<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Product;
use App\Models\PdOrder;
use App\Models\VendorOrder;
use App\Models\Division;
use App\Models\District;
use App\Models\Upazila;
use App\Models\User;
use App\Services\VoucherTransactionService;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\DB;

class OrderController extends Controller
{
    // Step-1: Checkout page (quantity/price/size/color)
    public function create(string $slug)
    {
        $product = Product::active()->where('slug', $slug)->firstOrFail();
        return view('order.checkout', compact('product'));
    }

    // Step-1 submit -> persist to session -> redirect to Step-2 (customer)
    public function store(Product $product, Request $request)
    {
        $request->validate([
            'qty'        => ['required','integer','min:1'],
            'size'       => ['nullable','string','max:100'],
            'color'      => ['nullable','string','max:100'],
            'sale_price' => ['required','numeric'],
        ]);

        $admin  = (float) $product->admin_price;
        $maxRes = (float) $product->reseller_price;
        $sale   = (float) $request->sale_price;
        $qty    = max(1, (int) $request->qty);

        if ($sale < $admin || $sale > $maxRes) {
            return back()
                ->withErrors(['sale_price' => 'এমাউন্ট সঠিকভাবে লিখুন (পাইকারি ও সর্বোচ্চ বিক্রয় মূল্যের মধ্যে দিন)।'])
                ->withInput();
        }

        // Step-1 ডেটা সেশনে রাখি
        session([
            'checkout.product_id' => $product->id,
            'checkout.qty'        => $qty,
            'checkout.size'       => $request->size,
            'checkout.color'      => $request->color,
            'checkout.sale_price' => $sale,
        ]);

        return redirect()->route('order.customer', $product->id);
    }

    // Step-2: Customer info form + order summary
    public function customer(Product $product, Request $request)
    {
        // === (A) Success modal path: অর্ডার হয়ে গেলে এখানেই পপআপ দেখাতে হবে ===
        if (session()->has('order_success')) {
            $data  = session('order_success');
            $order = PdOrder::where('id', $data['id'] ?? 0)->first();

            // ভুল/অন্য প্রোডাক্টের অর্ডার হলে fallback করে পুরোনো লজিক চালু
            if ($order && (int)$order->product_id === (int)$product->id) {
                // অর্ডার থেকে সামারি বানাই (checkout সেশন দরকার নেই)
                $summary = [
                    'qty'                    => (int) $order->qty,
                    'sale_price'             => (float) $order->sale_price,
                    'admin_price'            => (float) $order->admin_price,
                    'reseller_price'         => (float) $order->reseller_price,
                    'size'                   => (string) ($order->size ?? ''),
                    'color'                  => (string) ($order->color ?? ''),
                    'wholesale_total'        => (float) $order->wholesale_total,
                    'per_earn'               => max(0, (float)$order->sale_price - (float)$order->admin_price),
                    'earn_total'             => (float) $order->earn_total,
                    'grand_total'            => (float) $order->grand_total,
                    'delivery_payment_type'  => (int) $order->delivery_payment_type,
                    'delivery_charge'        => (float) $order->delivery_charge,
                ];

                // সরাসরি ভিউ—এখানেই পপআপ দেখাবে (session('order_success') ব্যবহার করে)
                return view('order.customer', compact('product','summary'));
            }
            // না মিললে নিচের (B) checkout-session path-এ পড়বে
        }

        // === (B) Checkout-session path: এখনো অর্ডার হয়নি, ফর্ম দেখানোর আগে সেশন থাকা চাই ===
        if ((int) session('checkout.product_id') !== (int) $product->id) {
            return redirect()
                ->route('order.create', $product->slug)
                ->withErrors(['error' => 'সেশন মেয়াদোত্তীর্ণ। আবার চেষ্টা করুন।']);
        }

        $qty   = (int) session('checkout.qty', 1);
        $sale  = (float) session('checkout.sale_price', $product->admin_price);
        $admin = (float) $product->admin_price;

        $summary = [
            'qty'                    => $qty,
            'sale_price'             => $sale,
            'admin_price'            => $admin,
            'reseller_price'         => (float) $product->reseller_price,
            'size'                   => (string) session('checkout.size', ''),
            'color'                  => (string) session('checkout.color', ''),
            'wholesale_total'        => $admin * $qty,
            'per_earn'               => max(0, $sale - $admin),
            'earn_total'             => max(0, $sale - $admin) * $qty,
            'grand_total'            => $sale * $qty,
            'delivery_payment_type'  => (int) $product->delivery_payment_type,
            'delivery_charge'        => $product->deliveryChargeForZone(Product::DELIVERY_ZONE_OUT_DHAKA),
        ];

        return view('order.customer', compact('product', 'summary'));
    }

    // Step-2 submit -> Final confirm & save order (success হলে customer পেজেই পপআপ)
    public function confirm(Product $product, Request $request)
    {
        if ((int) session('checkout.product_id') !== (int) $product->id) {
            return redirect()
                ->route('order.create', $product->slug)
                ->withErrors(['error' => 'সেশন মেয়াদোত্তীর্ণ। আবার চেষ্টা করুন।']);
        }

        $request->validate([
            'customer_name'  => ['required','string','max:191'],
            'customer_phone' => ['required','string','max:30'],
            'alt_phone'      => ['nullable','string','max:30'],
            'address'        => ['required','string','max:500'],
            'delivery_zone'  => ['required', Rule::in([
                Product::DELIVERY_ZONE_DHAKA_CITY,
                Product::DELIVERY_ZONE_SUB_DHAKA,
                Product::DELIVERY_ZONE_OUT_DHAKA,
            ])],
            'district_id'    => ['required','exists:pd_districts,id'],
            'upazila_id'     => ['required','exists:pd_upazilas,id'],
        ]);

        if ((int) $product->stock <= 0) {
            return back()->withErrors(['error' => 'এই প্রোডাক্ট টি মজুদ নেই।'])->withInput();
        }

        $qty   = (int) session('checkout.qty', 1);
        $size  = session('checkout.size');
        $color = session('checkout.color');
        $sale  = (float) session('checkout.sale_price', $product->admin_price);
        $admin = (float) $product->admin_price;

        $wholesale_total = $admin * $qty;
        $per_earn        = max(0, $sale - $admin);
        $earn_total      = $per_earn * $qty;
        $grand_total     = $sale * $qty;

        $district = District::findOrFail($request->district_id);
        $division = Division::findOrFail($district->division_id);
        $upazila  = Upazila::where('id', $request->upazila_id)
                           ->where('district_id', $district->id)
                           ->firstOrFail();

        $selectedZone = (string) $request->input('delivery_zone');
        $resolvedZone = $this->resolveDeliveryZone((string) $district->name, (string) $upazila->name);
        if ($selectedZone !== $resolvedZone) {
            return back()
                ->withErrors(['delivery_zone' => 'নির্বাচিত ডেলিভারি জোনের সাথে জেলা/থানা মিলছে না।'])
                ->withInput();
        }

        $delivery_payment_type = (int) $product->delivery_payment_type; // 0=No advance, 1=Advance
        $delivery_charge       = $product->deliveryChargeForZone($selectedZone);
        $deducted              = false;
        $order = null;

        try {
            DB::transaction(function () use (
                $product,
                $qty,
                $admin,
                $sale,
                $wholesale_total,
                $earn_total,
                $grand_total,
                $size,
                $color,
                $delivery_payment_type,
                $delivery_charge,
                $request,
                $division,
                $district,
                $upazila,
                &$deducted,
                &$order
            ) {
                $user = User::lockForUpdate()->findOrFail((int) auth()->id());

                if ($delivery_payment_type === 1) {
                    $beforeVoucher = (float) ($user->voucher_balance ?? 0);
                    if ($beforeVoucher < $delivery_charge) {
                        throw new \RuntimeException('আপনার পর্যাপ্ত ব্যালেন্স নাই।');
                    }

                    $afterVoucher = $beforeVoucher - $delivery_charge;
                    $user->voucher_balance = $afterVoucher;
                    $user->save();
                    $deducted = true;
                }

                $order = PdOrder::create([
                    'user_id'         => $user->id,
                    'product_id'      => $product->id,
                    'category_id'     => $product->category_id,
                    'qty'             => $qty,

                    'admin_price'     => $admin,
                    'reseller_price'  => (float) $product->reseller_price,
                    'sale_price'      => $sale,
                    'wholesale_total' => $wholesale_total,
                    'earn_total'      => $earn_total,
                    'grand_total'     => $grand_total,

                    'size'            => $size,
                    'color'           => $color,

                    'delivery_payment_type'   => $delivery_payment_type,
                    'delivery_charge'         => $delivery_charge,
                    'delivery_charge_deducted'=> $deducted ? 1 : 0,

                    'customer_name'   => $request->customer_name,
                    'customer_phone'  => $request->customer_phone,
                    'alt_phone'       => $request->alt_phone,
                    'address'         => $request->address,

                    'division'        => $division->name,
                    'district'        => $district->name,
                    'thana'           => $upazila->name,

                    'status'          => 'pending',
                ]);

                if ($delivery_payment_type === 1) {
                    VoucherTransactionService::record(
                        userId: (int) $user->id,
                        direction: 'debit',
                        amount: $delivery_charge,
                        before: $beforeVoucher,
                        after: $afterVoucher,
                        source: 'pd_order_delivery_charge_debit',
                        description: 'Order #' . $order->id . ' ডেলিভারি চার্জ ভাউচার ব্যালেন্স থেকে কাটা হয়েছে।',
                        referenceType: 'pd_order',
                        referenceId: $order->id,
                        metadata: [
                            'product_id' => $product->id,
                            'delivery_charge' => $delivery_charge,
                            'delivery_zone' => (string) $request->input('delivery_zone'),
                        ]
                    );
                }

                if (!empty($product->vendor_profile_id)) {
                    VendorOrder::create([
                        'pd_order_id' => $order->id,
                        'product_id' => $product->id,
                        'vendor_profile_id' => (int) $product->vendor_profile_id,
                        'user_id' => $user->id,
                        'order_no' => 'PD-' . $order->id,
                        'status' => 'pending',
                        'total_amount' => $grand_total,
                        'ordered_at' => now(),
                    ]);
                }
            });
        } catch (\RuntimeException $e) {
            return back()->withErrors(['error' => $e->getMessage()])->withInput();
        } catch (\Throwable $e) {
            report($e);
            return back()->withErrors(['error' => 'অর্ডার সম্পন্ন করা যায়নি। আবার চেষ্টা করুন।'])->withInput();
        }

        // checkout সেশন ক্লিয়ার
        session()->forget('checkout');

        // customer পেজেই পপআপ দেখাতে order_success সেশন সেট করি
        return redirect()
            ->route('order.customer', $product->id)
            ->with('order_success', [
                'id'           => $order->id,
                'product_id'   => $product->id, // ← নতুন: মিল চেকের কাজে লাগবে
                'title'        => $product->title,
                'banner_photo' => $product->banner_photo_url ?? asset('images/no-image.png'),
            ]);
    }

    private function resolveDeliveryZone(string $districtName, string $upazilaName): string
    {
        if ($this->isGazipurDistrictName($districtName) || $this->isSavarThanaName($upazilaName)) {
            return Product::DELIVERY_ZONE_SUB_DHAKA;
        }

        if ($this->isDhakaDistrictName($districtName)) {
            return Product::DELIVERY_ZONE_DHAKA_CITY;
        }

        return Product::DELIVERY_ZONE_OUT_DHAKA;
    }

    private function isDhakaDistrictName(string $name): bool
    {
        $txt = trim(mb_strtolower($name));

        return str_contains($txt, 'dhaka') || preg_match('/ঢাকা/u', $name) === 1;
    }

    private function isGazipurDistrictName(string $name): bool
    {
        $txt = trim(mb_strtolower($name));

        return str_contains($txt, 'gazipur')
            || preg_match('/গাজীপুর/u', $name) === 1
            || preg_match('/গাজিপুর/u', $name) === 1;
    }

    private function isSavarThanaName(string $name): bool
    {
        $txt = trim(mb_strtolower($name));

        return str_contains($txt, 'savar') || preg_match('/সাভার/u', $name) === 1;
    }
}
