<?php

namespace App\Http\Controllers;

use App\Mail\OrderConfirmed;
use App\Mail\Ordercopytransfer;
use App\Models\Area;
use App\Models\Cart;
use App\Models\Order;
use App\Models\Product;
use App\Models\Productcolor;
use App\Models\Shippingzone;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;

use App\Models\PendingOrder;
use App\Traits\VerifiesPaymentTotal;

class MintpayController extends Controller
{
    use VerifiesPaymentTotal;
    protected $merchantId;
    protected $apiToken;
    protected $mode;
    protected $baseUrl;
    protected $loginUrl;

    public function __construct()
    {
        $this->merchantId = env('MINTPAY_MERCHANT_ID');
        $this->apiToken = env('MINTPAY_API_TOKEN');
        $this->mode = env('MINTPAY_MODE', 'live');

        $this->baseUrl = $this->mode === 'live'
            ? 'https://app.mintpay.lk/user-order/api/'
            : 'https://dev.mintpay.lk/user-order/api/';

        $this->loginUrl = $this->mode === 'live'
            ? 'https://app.mintpay.lk/user-order/login/'
            : 'https://dev.mintpay.lk/user-order/login/';
    }

    public function payWithMintpay(Request $request)
    {

        // Security: Recalculate amount on server
        try {
            $verifiedAmount = $this->verifyTotalAmount($request->all());
            $user = Auth::user();
            if ($request->input('use_points') && $user) {
                $appliedPointsTotal = min($user->recycling_points, $verifiedAmount);
                $verifiedAmount -= $appliedPointsTotal;
            }
            $request->merge(['amount' => $verifiedAmount]);
        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'Invalid order data: ' . $e->getMessage());
        }


        $orderId = $request->input('order_id', time() . rand(111, 999));



        $amount = number_format((float) $request->input('amount'), 2, '.', '');
        $currency = 'LKR';
        $firstName = $request->input('cus_firstname');
        $lastName = $request->input('cus_lastname', '');
        $email = $request->input('cus_email') ?? Auth::user()->email;
        $mobile = $request->input('cus_phone', '');
        $productName = $request->input('description', '1 Product');
        $order_id = $request->input('order_id');

        // Store order data in database to prevent loss during session expiry
        PendingOrder::create([
            'order_id' => $order_id,
            'payment_method' => 'mintpay',
            'payload' => $request->all(),
            'status' => 'pending'
        ]);

        $order_color = $request->input('order_color');
        $order_qty = $request->input('order_qty');
        $cus_address_one = $request->input('cus_address_one');
        $cus_address_two = $request->input('cus_address_two');
        $cus_company = $request->input('cus_company');
        $cus_city = $request->input('cus_city');
        $cus_district = $request->input('cus_district');
        $cus_postcode = $request->input('cus_postcode');
        $order_note = $request->input('order_note');
        $shipping_price = $request->input('shipping_price', 0);
        $totalweight = $request->input('totalweight', 0);
        $productid = $request->input('productid');

        session([
            'payment_data' => [
                'amount' => $amount,
                'currency' => $currency,
                'firstName' => $firstName,
                'lastName' => $lastName,
                'email' => $email,
                'mobile' => $mobile,
                'productName' => $productName,
                'order_id' => $order_id,
                'order_color' => $order_color,
                'order_qty' => $order_qty,
                'cus_address_one' => $cus_address_one,
                'cus_address_two' => $cus_address_two,
                'cus_city' => $cus_city,
                'cus_district' => $cus_district,
                'cus_postcode' => $cus_postcode,
                'order_note' => $order_note,
                'shipping_price' => $shipping_price,
                'totalweight' => $totalweight,
                'productid' => $productid,
                'cuscompany' => $cus_company,
                'voucher_code' => $request->input('voucher_code'),
                'discount_amount' => $request->input('discount_amount', 0),
            ]
        ]);

        $data = [
            "merchant_id" => $this->merchantId,
            "order_id" => uniqid(),
            "total_price" => $amount,
            "discount" => 0,
            "customer_email" => $email,
            "customer_id" => 2,
            "customer_telephone" => $mobile,
            "ip" => $request->ip(),
            "x_forwarded_for" => $request->header('X-Forwarded-For', $request->ip()),
            "delivery_street" => $cus_address_one . ' ' . $cus_address_two,
            "delivery_region" => $cus_city,
            "delivery_postcode" => $cus_postcode,
            "cart_created_date" => now()->format('Y-m-d H:i:s'),
            "cart_updated_date" => now()->format('Y-m-d H:i:s'),
            "success_url" => route('mintpay.success', ['order_id' => $order_id]),
            "fail_url" => route('mintpay.fail', ['order_id' => $order_id]),
            "products" => [
                [
                    "name" => "Products",
                    "product_id" => "1",
                    "sku" => "0",
                    "quantity" => 0,
                    "unit_price" => $amount,
                    "discount" => 0.00,
                    "created_date" => now()->format('Y-m-d H:i:s'),
                    "updated_date" => now()->format('Y-m-d H:i:s'),
                ],
            ],
        ];

        // Step 1: Send order details to Mintpay
        $response = Http::withHeaders([
            'Authorization' => 'Token ' . $this->apiToken,
            'Content-Type' => 'application/json',
        ])->post($this->baseUrl, $data);


        $result = $response->json();

        // Step 2: Redirect to Mintpay payment page
        if ($result['message'] === 'Success') {
            $purchaseId = $result['data'];
            return view('mintpay.redirect', [
                'url' => $this->loginUrl,
                'purchaseId' => $purchaseId,
            ]);
        }

        return back()->with('error', 'Mintpay payment initiation failed: ' . ($result['data'] ?? 'Unknown error'));
    }

    public function success(Request $request)
    {
        $orderId = $request->input('order_id');
        $pendingOrder = null;
        if ($orderId) {
            $pendingOrder = PendingOrder::where('order_id', $orderId)->first();
        }

        $this->savemintorder($pendingOrder);

        if ($pendingOrder) {
            $pendingOrder->update(['status' => 'completed']);
        }

        return view('web.home.checkout.success', [
            'message' => 'Payment completed successfully!'
        ]);
    }
    public function savemintorder($pendingOrder = null)
    {
        $newOrderIds = [];
        $orderItems = [];
        $productDetails = [];
        $totalOrderAmount = 0;
        $totalServiceFee = 0;

        try {
            $user = Auth::user();

            $paymentData = null;
            if ($pendingOrder) {
                $paymentData = $pendingOrder->payload;
                // Standardize keys if they differ between request and session storage
                if (!isset($paymentData['cuscompany']) && isset($paymentData['cus_company'])) {
                    $paymentData['cuscompany'] = $paymentData['cus_company'];
                }
            } elseif (session()->has('payment_data')) {
                $paymentData = session('payment_data');
            }

            if (!$paymentData) {
                throw new \Exception('Payment data not found in database or session');
            }

            // Get shipping zone data
            $city_name = $paymentData['cus_city'] ?? null;
            $areaData = $city_name ? Area::where('area_name', $city_name)->first() : null;

            // If area not found, default to Zone A (serviceid 1)
            $serviceid = $areaData ? $areaData->serviceid : 1;

            $zonedata = Shippingzone::where('id', $serviceid)->first();
            if (!$zonedata) {
                // Secondary fallback if specific zone or Zone A is missing from DB
                $zonedata = Shippingzone::where('id', 1)->first() ?: (object) ['id' => 1, 'price' => 425];
            }

            // Security: Recalculate and verify amount on server using session data
            try {
                $verifiedAmount = $this->verifyTotalAmount($paymentData);
                $user = Auth::user();
                $appliedPointsTotal = 0;
                if (!empty($paymentData['use_points']) && $user) {
                    $appliedPointsTotal = min($user->recycling_points, $verifiedAmount);
                    $verifiedAmount -= $appliedPointsTotal;
                }
                $paymentData['amount'] = $verifiedAmount;
            } catch (\Exception $e) {
                throw new \Exception('Invalid session order data: ' . $e->getMessage());
            }

            // Validate and explode the arrays from session
            $productIds = !empty($paymentData['productid']) ? explode(',', $paymentData['productid']) : [];

            $colors = !empty($paymentData['order_color']) ? explode(',', $paymentData['order_color']) : [];
            $quantities = !empty($paymentData['order_qty']) ? explode(',', $paymentData['order_qty']) : [];

            if (count($productIds) === 0 || count($productIds) !== count($colors) || count($productIds) !== count($quantities)) {
                throw new \Exception('Invalid product data: counts mismatch');
            }

            // Calculate shipping total using server-side data directly
            $totalWeightForShipping = 0;
            foreach ($productIds as $index => $productId) {
                $qty = (int) ($quantities[$index] ?? 1);
                $pData = DB::table('product')->select('weight')->where('id', $productId)->first();
                if ($pData) {
                    $totalWeightForShipping += ($pData->weight * $qty);
                }
            }

            $productweightcostAll = $totalWeightForShipping > 1000 ? ceil(($totalWeightForShipping - 1000) / 1000) * 100 : 0;
            $shippingprice = ($zonedata->price ?? 0) + $productweightcostAll;

            $itemCount = count($productIds);
            $perProductShipping = $itemCount > 0 ? ($shippingprice / $itemCount) : 0;

            // Calculate tax for corporate customer
            $taxPercentage = 0;
            if (Auth::check() && Auth::user()->is_corporate) {
                $taxPercentage = (float) \App\Models\SystemSetting::get('corporate_tax_percentage', 18.00);
            }

            // Process each product
            foreach ($productIds as $index => $productId) {
                $color = $colors[$index] ?? null;
                $quantity = (int) ($quantities[$index] ?? 1);

                if ($quantity <= 0) {
                    continue;
                }

                // Check for duplicate orders
                $existingOrder = Order::where('product_id', $productId)
                    ->where('color', $color)
                    ->where('userid', $user->id ?? 'Guest')
                    ->where('created_at', '>=', Carbon::now()->subMinutes(5))
                    ->first();

                if ($existingOrder) {
                    continue;
                }

                // Get product data with lock
                $productdata = DB::table('product')
                    ->join('product_color', 'product.id', '=', 'product_color.product_id')
                    ->select(
                        'product.id',
                        'product.product_name',
                        'product.product_price',
                        'product.qty',
                        'product.order',
                        'product.weight',
                        'product.cutted_price',
                        'product.product_image',
                        'product_color.product_color',
                        'product_color.price'
                    )
                    ->where('product.id', $productId)
                    ->where('product_color.product_color', $color)
                    ->lockForUpdate()
                    ->first();

                if (!$productdata) {
                    Log::error('Product not found', [
                        'product_id' => $productId,
                        'color' => $color
                    ]);
                    continue;
                }

                // Validate stock
                if ($productdata->qty < $quantity) {
                    throw new \Exception("Insufficient stock for product ID: {$productId}");
                }

                // Calculate prices and weights
                $unitprice = $productdata->price ?? $productdata->product_price;
                $productPrice = $unitprice * $quantity;
                $productWeight = $productdata->weight * $quantity;
                // // dd($productWeight); // Debugging line - you might want to remove this in production

                // // Fixed calculation for weight cost
                // $productweightcost = ($productWeight > 1000) ? ceil(($productWeight - 1000) / 1000) * 100 : 0;


                $service_fee = $perProductShipping;

                $finalamount = $productPrice + $service_fee;

                $taxSubtotalItem = round((($productdata->cutted_price ?? $productdata->price) * $taxPercentage) / 100, 2);
                $taxAmountItem = $taxSubtotalItem * $quantity;
                $finalamount += $taxAmountItem;

                // Generate order ID
                $baseId = $paymentData['order_id'] ?? session('mintpay_order_id', substr(uniqid(), -8));
                $uniquePart = substr(uniqid(), -5);
                $orderId = 'MINTPAY-' . $baseId . '-' . $uniquePart;

                // Create order
                $order = new Order();
                $order->userid = $user->id ?? "Guest";
                $order->zone_id = $zonedata->id;
                $order->order_id = $orderId;
                $order->product_id = $productId;
                $order->first_name = $paymentData['cus_firstname'] ?? '';
                $order->last_name = $paymentData['cus_lastname'] ?? '';
                $order->color = $color;
                $order->quantity = $quantity;
                $order->telephone = $paymentData['cus_phone'] ?? '';
                $order->company = $paymentData['cuscompany'] ?? '';
                $order->email = $paymentData['email'] ?? '';
                $order->address_1 = $paymentData['cus_address_one'] ?? '';
                $order->address_2 = $paymentData['cus_address_two'] ?? '';
                $order->city = $paymentData['cus_city'] ?? '';
                $order->district = $paymentData['cus_district'] ?? '';
                $order->postcode = $paymentData['cus_postcode'] ?? '';
                $order->ordernote = $paymentData['order_note'] ?? '';
                $order->processing = 1;
                $order->transaction_id = 0;
                $order->mintpay_order_id = $baseId;
                $order->tracking = '';
                $order->payment_method = 'mintpay';
                $order->service_fee = $service_fee;
                $order->total = $productPrice;
                $order->totalweight = $productWeight;

                // Calculate tax for this line item if corporate
                $lineTaxPercentage = 0;
                $lineTaxAmount = 0;
                if (Auth::check() && Auth::user()->is_corporate) {
                    $lineTaxPercentage = (float) \App\Models\SystemSetting::get('corporate_tax_percentage', 18.00);
                    $taxBaseSetting = \App\Models\SystemSetting::get('tax_calculation_base', 'selling_price');
                    $taxBasePrice = ($taxBaseSetting === 'cutted_price' && isset($productdata->cutted_price))
                        ? $productdata->cutted_price
                        : $unitprice;

                    $lineTaxAmount = round(($taxBasePrice * $quantity * $lineTaxPercentage) / 100, 2);
                }
                $order->tax_amount = $lineTaxAmount;
                $order->tax_percentage = $lineTaxPercentage;

                $order->voucher_code = $paymentData['voucher_code'] ?? null;
                if ($index === 0) {
                    $order->discount_amount = $paymentData['discount_amount'] ?? 0;
                    $order->points_applied = $appliedPointsTotal;
                    $order->points_used_flag = $appliedPointsTotal > 0 ? 1 : 0;
                } else {
                    $order->discount_amount = 0;
                    $order->points_applied = 0;
                    $order->points_used_flag = 0;
                }
                $order->status = 1;

                DB::transaction(function () use ($order, $productdata, $quantity, $user, $productId, $color, $index) {
                    $order->save();
                    $this->updateqty($productdata, $quantity);
                    $this->updateorder_qty($productdata, $quantity);
                    $this->updatecolorstock($productId, $color, $quantity);
                    if ($user) {
                        $product = Product::find($productId);
                        $this->remove_fromCart($product, $user->id, $color);
                    }
                    if ($index === 0 && !empty($order->voucher_code)) {
                        $voucher = \App\Models\Voucher::where('code', $order->voucher_code)->first();
                        if ($voucher && $voucher->isValid()) {
                            $voucher->update([
                                'redeemed_by' => $user ? $user->id : null,
                                'redeemed_at' => now()
                            ]);
                        }
                    }
                });

                // Store data
                $newOrderIds[] = $order->id;
                $newOrderIdsNO[] = $order->order_id;
                $totalOrderAmount += $productPrice;
                $totalServiceFee += $service_fee;

                $productDetails[] = [
                    'name' => $productdata->product_name,
                    'color' => $color,
                    'quantity' => $quantity,
                    'price' => $unitprice
                ];

                $orderItems[] = [
                    'product_id' => $productId,
                    'product_name' => $productdata->product_name,
                    'color' => $color,
                    'quantity' => $quantity,
                    'unit_price' => $productdata->price ?? $productdata->product_price,
                    'total_price' => $productPrice,
                    'service_fee' => $service_fee,
                    'tax_amount' => round(((\App\Models\SystemSetting::get('tax_calculation_base', 'selling_price') === 'cutted_price' && isset($productdata->cutted_price) ? $productdata->cutted_price : ($productdata->price ?? $productdata->product_price)) * $quantity * $taxPercentage) / 100, 2),
                    'final_amount' => $finalamount,
                    'settextcolor' => $this->setcolor($color)
                ];
            }

            // Send emails if orders were created
            if (count($orderItems) > 0) {
                $orderdate = Carbon::today();
                $totalTaxAmount = 0;
                foreach ($orderItems as $item) {
                    $product = Product::find($item['product_id']);
                    $taxBaseSetting = \App\Models\SystemSetting::get('tax_calculation_base', 'selling_price');
                    $taxBasePrice = ($taxBaseSetting === 'cutted_price' && isset($product->cutted_price)) ? $product->cutted_price : $item['unit_price'];
                    $totalTaxAmount += round(($taxBasePrice * $item['quantity'] * $taxPercentage) / 100, 2);
                }

                $discountAmount = $paymentData['discount_amount'] ?? 0;

                if ($appliedPointsTotal > 0 && $user) {
                    $user->recycling_points -= $appliedPointsTotal;
                    $user->save();
                }

                // Generate Invoice for Mintpay order (was missing in this controller)
                $todayDate = date('Ymd');
                $todayCount = \App\Models\Invoice::withoutGlobalScopes()->whereDate('invoice_date', date('Y-m-d'))->count() + 1;
                do {
                    $invoiceNumber = 'INV-' . $todayDate . '-' . str_pad($todayCount, 4, '0', STR_PAD_LEFT);
                    $todayCount++;
                } while (\App\Models\Invoice::withoutGlobalScopes()->where('invoice_number', $invoiceNumber)->exists());

                $invoiceSubtotal = $totalOrderAmount;
                $invoiceTotal = max(0, $invoiceSubtotal + $totalServiceFee + $totalTaxAmount - $discountAmount - $appliedPointsTotal);

                $invoice = \App\Models\Invoice::create([
                    'invoice_number' => $invoiceNumber,
                    'order_id' => 'ORDER-' . implode('-', $newOrderIds),
                    'customer_name' => ($paymentData['cus_firstname'] ?? '') . ' ' . ($paymentData['lastName'] ?? ''),
                    'customer_email' => $paymentData['email'] ?? '',
                    'billing_address' => ($paymentData['cus_address_one'] ?? '') . ', ' . ($paymentData['cus_city'] ?? ''),
                    'invoice_date' => now(),
                    'subtotal' => $invoiceSubtotal,
                    'tax_percentage' => $taxPercentage,
                    'tax_amount' => $totalTaxAmount,
                    'shipping_cost' => $totalServiceFee,
                    'discount_amount' => $discountAmount,
                    'total_amount' => $invoiceTotal,
                    'status' => 'paid',
                    'points_applied' => $appliedPointsTotal,
                    'points_used_flag' => $appliedPointsTotal > 0 ? 1 : 0,
                ]);

                try {
                    $this->mailtoCustomer(
                        $paymentData['email'] ?? '',
                        $paymentData['cus_firstname'] ?? '',
                        $newOrderIdsNO,
                        $orderItems,
                        $totalOrderAmount,
                        $totalServiceFee,
                        $paymentData['cus_phone'] ?? '',
                        $paymentData['cus_address_one'] ?? '',
                        $paymentData['cus_address_two'] ?? '',
                        $orderdate,
                        $totalTaxAmount,
                        $taxPercentage,
                        $discountAmount,
                        $invoice,
                        $appliedPointsTotal
                    );

                    $this->copyTransfer(
                        $paymentData['email'] ?? '',
                        $paymentData['cus_firstname'] ?? '',
                        $newOrderIds,
                        $orderItems,
                        $totalOrderAmount,
                        $totalServiceFee,
                        $paymentData['cus_phone'] ?? '',
                        $paymentData['cus_address_one'] ?? '',
                        $paymentData['cus_address_two'] ?? '',
                        $orderdate,
                        $totalTaxAmount,
                        $taxPercentage,
                        $discountAmount,
                        $appliedPointsTotal
                    );
                } catch (\Exception $e) {
                    Log::error('Email sending failed', ['error' => $e->getMessage()]);
                }

                // Send to Koombiyo
                try {

                    $totalAmount = ($totalOrderAmount ?? 0)
                        + ($totalTaxAmount ?? 0)
                        + ($totalServiceFee ?? 0)
                        - ($discountAmount ?? 0);

                    $response = $this->sendToKoombiyo(
                        $paymentData['cus_firstname'] ?? '',
                        $paymentData['cus_phone'] ?? '',
                        trim(($paymentData['cus_address_one'] ?? '') . ' ' . ($paymentData['cus_address_two'] ?? '')),
                        $paymentData['cus_city'] ?? '',
                        $paymentData['cus_district'] ?? '',
                        $paymentData['cus_postcode'] ?? '',
                        $paymentData['order_note'] ?? 'Order from website',
                        $productDetails,
                        $totalAmount,
                        $newOrderIds
                    );

                    Log::info('Koombiyo API Success', [
                        'order_ids' => $newOrderIds,
                        'response' => $response,
                    ]);

                } catch (\Throwable $e) {

                    Log::error('Koombiyo API Error', [
                        'message' => $e->getMessage(),
                        'file' => $e->getFile(),
                        'line' => $e->getLine(),
                        'trace' => $e->getTraceAsString(),
                        'order_ids' => $newOrderIds,
                        'customer' => $paymentData['cus_firstname'] ?? '',
                        'phone' => $paymentData['cus_phone'] ?? '',
                    ]);

                    // Optional: continue execution without stopping
                    // Or return false depending on your requirement.
                }
            }

            // Clear session data
            session()->forget('payment_data');
            session()->forget('mintpay_order_id');

            return [
                'success' => true,
                'orderIds' => $newOrderIds
            ];
        } catch (\Throwable $th) {
            Log::error('savemintpayorder error', [
                'error' => $th->getMessage(),
                'trace' => $th->getTraceAsString()
            ]);
            DB::table('error_logs')->insert([
                'message' => $th->getMessage(),
                'file' => $th->getFile(),
                'line' => $th->getLine(),
                'trace' => $th->getTraceAsString(),
                'created_at' => now(),
            ]);

            return [
                'success' => false,
                'message' => $th->getMessage()
            ];
        }
    }

    public function copyTransfer($email, $name, $orderIds, $orderItems, $totalOrderAmount, $totalServiceFee, $cusphone, $addressone, $addresstwo, $orderdate, $taxAmount = 0, $taxPercentage = 0, $discountAmount = 0, $pointsApplied = 0)
    {
        try {
            $recipients = ['sales@americanplastic.lk', 'info@americanplastic.lk', 'ashan.r@americanplastic.lk'];
            //$recipients = ['kalpamadusanka113@gmail.com'];
            Mail::to($recipients)->send(new Ordercopytransfer(
                $name,
                $orderIds[0], // Use first order ID as reference
                $orderItems,
                $totalOrderAmount,
                $totalServiceFee,
                $cusphone,
                $addressone,
                $addresstwo,
                $orderdate,
                $taxAmount,
                $taxPercentage,
                $discountAmount,
                $pointsApplied
            ));
        } catch (\Throwable $th) {
            DB::table('error_logs')->insert([
                'message' => $th->getMessage(),
                'file' => $th->getFile(),
                'line' => $th->getLine(),
                'trace' => $th->getTraceAsString(),
                'created_at' => now(),
            ]);
        }
    }

    public function mailtoCustomer($email, $name, $orderIds, $orderItems, $totalOrderAmount, $totalServiceFee, $cusphone, $addressone, $addresstwo, $orderdate, $taxAmount = 0, $taxPercentage = 0, $discountAmount = 0, $invoice = null, $pointsApplied = 0)
    {

        try {
            Mail::to($email)->send(new OrderConfirmed(
                $name,
                $orderIds[0], // Use first order ID as reference
                $orderItems,
                $totalOrderAmount,
                $totalServiceFee,
                $cusphone,
                $addressone,
                $addresstwo,
                $orderdate,
                $taxAmount,
                $taxPercentage,
                $discountAmount,
                $invoice,
                $pointsApplied
            ));
        } catch (\Throwable $th) {
            DB::table('error_logs')->insert([
                'message' => $th->getMessage(),
                'file' => $th->getFile(),
                'line' => $th->getLine(),
                'trace' => $th->getTraceAsString(),
                'created_at' => now(),
            ]);
        }
    }
    public function setcolor($colorchecked)
    {
        try {
            if ($colorchecked == '#A78B8D') {
                $cartcolor = 'Marblepink';
            } elseif ($colorchecked == '#61A8F8') {
                $cartcolor = 'Babyblue';
            } elseif ($colorchecked == '#C55C82') {
                $cartcolor = 'Pink';
            } elseif ($colorchecked == '#FF0000') {
                $cartcolor = 'Red';
            } elseif ($colorchecked == '#CAD3D0') {
                $cartcolor = 'Clear';
            } elseif ($colorchecked == '#BA9978') {
                $cartcolor = 'Beige';
            } elseif ($colorchecked == '#88DB86') {
                $cartcolor = 'Applegreen';
            } elseif ($colorchecked == '#DEE4EE') {
                $cartcolor = 'Marblewhite';
            } elseif ($colorchecked == '#BDB8EE') {
                $cartcolor = 'Marbleviolet';
            } elseif ($colorchecked == '#E9CBB9') {
                $cartcolor = 'Marbleorange';
            } elseif ($colorchecked == '#FEF250') {
                $cartcolor = 'Lemonyellow';
            } elseif ($colorchecked == '#f4c2c2') {
                $cartcolor = 'Babypink';
            } elseif ($colorchecked == '#D2C77D') {
                $cartcolor = 'Metallicgold';
            } elseif ($colorchecked == '#DAD9C6') {
                $cartcolor = 'Buttermilk';
            } elseif ($colorchecked == '#E9C500') {
                $cartcolor = 'Yellow';
            } elseif ($colorchecked == '#D3CBC4') {
                $cartcolor = 'Graybeige';
            } elseif ($colorchecked == '#0F2D8D') {
                $cartcolor = 'Blue';
            } elseif ($colorchecked == '#005E3A') {
                $cartcolor = 'Green';
            } elseif ($colorchecked == '#D6F2E6') {
                $cartcolor = 'Marblegreen';
            } elseif ($colorchecked == '#BF8BFF') {
                $cartcolor = 'Violet';
            } elseif ($colorchecked == '#6B4B36') {
                $cartcolor = 'Brown';
            } elseif ($colorchecked == '#C0C0C0') {
                $cartcolor = 'Silver';
            } elseif ($colorchecked == '#808080') {
                $cartcolor = 'Grey';
            } elseif ($colorchecked == '#6CD2FA') {
                $cartcolor = 'Skyblue';
            } elseif ($colorchecked == '#D09305') {
                $cartcolor = 'Orange';
            } elseif ($colorchecked == '#13598B') {
                $cartcolor = 'Metallicblue';
            } elseif ($colorchecked == '#9582BB') {
                $cartcolor = 'Metallicviolet';
            } elseif ($colorchecked == '#A286F4') {
                $cartcolor = 'Purple';
            } elseif ($colorchecked == '#62ADE6') {
                $cartcolor = 'Marbleblue';
            } elseif ($colorchecked == '#80355C') {
                $cartcolor = 'Marblered';
            } elseif ($colorchecked == '#2FCBD4') {
                $cartcolor = 'Avocadogreen';
            } elseif ($colorchecked == '#FFA07A') {
                $cartcolor = 'Lightorange';
            } elseif ($colorchecked == '#DDD3D1') {
                $cartcolor = 'Marblebeige';
            } elseif ($colorchecked == '#F4C430') {
                $cartcolor = 'Saffron';
            } elseif ($colorchecked == '#000000') {
                $cartcolor = 'Black';
            } elseif ($colorchecked == '#D4AF37') {
                $cartcolor = 'Marblegold';
            } elseif ($colorchecked == '#FFFFFF') {
                $cartcolor = 'Purewhite';
            } elseif ($colorchecked == '#B4B4B8') {
                $cartcolor = 'Metallicsilver';
            } elseif ($colorchecked == '#58C3C2') {
                $cartcolor = 'Marblegreen';
            } elseif ($colorchecked == '#006A4E') {
                $cartcolor = 'Bottlegreen';
            } elseif ($colorchecked == '#6F4E37') {
                $cartcolor = 'Coffee';
            } elseif ($colorchecked == '#FFFDD0') {
                $cartcolor = 'Cream';
            } elseif ($colorchecked == '#A9A9A9') {
                $cartcolor = 'Darkgrey';
            } elseif ($colorchecked == '#C40233') {
                $cartcolor = 'Metalicred';
            } elseif ($colorchecked == '#9582BB') {
                $cartcolor = 'Metalicviolet';
            } elseif ($colorchecked == '#3D7764') {
                $cartcolor = 'Metalicgreen';
            } elseif ($colorchecked == '#F8B700') {
                $cartcolor = 'Metalicyellow';
            }
            return $cartcolor;
        } catch (\Throwable $th) {
            DB::table('error_logs')->insert([
                'message' => $th->getMessage(),
                'file' => $th->getFile(),
                'line' => $th->getLine(),
                'trace' => $th->getTraceAsString(),
                'created_at' => now(),
            ]);
        }
    }
    private function updateqty($productdata, $orderqty)
    {
        try {
            if ($productdata) {
                $productData = Product::find($productdata->id);
                $productData->qty = $productdata->qty - $orderqty;
                $productData->update();

                return response()->json([
                    'success' => true,
                    'message' => 'Product quantity updated successfully.',
                    'product' => $productData
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => 'Product not found.'
                ], 404);
            }

        } catch (\Throwable $th) {
            DB::table('error_logs')->insert([
                'message' => $th->getMessage(),
                'file' => $th->getFile(),
                'line' => $th->getLine(),
                'trace' => $th->getTraceAsString(),
                'created_at' => now(),
            ]);
        }


    }

    private function sendToKoombiyo(
        $customerName,
        $phone,
        $address,
        $city,
        $district,
        $postcode,
        $notes,
        $productDetails,
        $codValue,
        $orderIds
    ) {
        try {
            $waybillId = $this->getWaybillId();
            if (!$waybillId) {
                throw new \Exception('Failed to get waybill ID from Koombiyo');
            }

            // Build product description
            $description = "Order Details:\n";
            foreach ($productDetails as $product) {
                $description .= sprintf(
                    "%s (Color: %s) x %d - Rs.%.2f\n",
                    $product['name'],
                    $this->getsetcolor($product['color']),
                    $product['quantity'],
                    $product['price']
                );
            }

            $apiData = [
                'apikey' => 'ORkohpssTIlGBjSqDYyb',
                'orderWaybillid' => $waybillId,
                'orderNo' => 'ORDER-' . implode('-', $orderIds),
                'receiverName' => $customerName,
                'receiverStreet' => $address,
                'receiverDistrict' => $this->getDistrictId($district),
                'receiverCity' => $this->getCityId($city, $district),
                'receiverPhone' => $phone,
                'description' => 'Plastic Products',
                'spclNote' => $notes,
                'getCod' => 0
            ];

            $response = Http::asForm()
                ->post('https://application.koombiyodelivery.lk/api/Addorders/users', $apiData);

            if ($response->successful()) {
                // Update all orders with tracking info
                Order::whereIn('id', $orderIds)->update([
                    'mintpay_order_id' => $waybillId,
                    'tracking' => 'WAYBILL-' . $waybillId
                ]);

                return true;
            } else {
                throw new \Exception('Koombiyo API error: ' . $response->body());
            }
        } catch (\Exception $th) {
            DB::table('error_logs')->insert([
                'message' => $th->getMessage(),
                'file' => $th->getFile(),
                'line' => $th->getLine(),
                'trace' => $th->getTraceAsString(),
                'created_at' => now(),
            ]);
            return false;
        }
    }

    public function getsetcolor($color)
    {

        if ($color == '#A78B8D') {
            $colorName = 'Marblepink';
        } else if ($color == '#61A8F8') {
            $colorName = 'Babyblue';
        } else if ($color == '#C55C82') {
            $colorName = 'Pink';
        } else if ($color == '#FF0000') {
            $colorName = 'Red';
        } else if ($color == '#CAD3D0') {
            $colorName = 'Clear';
        } else if ($color == '#BA9978') {
            $colorName = 'Beige';
        } else if ($color == '#88DB86') {
            $colorName = 'Applegreen';
        } else if ($color == '#DEE4EE') {
            $colorName = 'Marblewhite';
        } else if ($color == '#BDB8EE') {
            $colorName = 'Marbleviolet';
        } else if ($color == '#E9CBB9') {
            $colorName = 'Marbleorange';
        } else if ($color == '#FEF250') {
            $colorName = 'Lemonyellow';
        } else if ($color == '#f4c2c2') {
            $colorName = 'Babypink';
        } else if ($color == '#D2C77D') {
            $colorName = 'Metallicgold';
        } else if ($color == '#DAD9C6') {
            $colorName = 'Buttermilk';
        } else if ($color == '#E9C500') {
            $colorName = 'Yellow';
        } else if ($color == '#D3CBC4') {
            $colorName = 'Graybeige';
        } else if ($color == '#0F2D8D') {
            $colorName = 'Blue';
        } else if ($color == '#005E3A') {
            $colorName = 'Green';
        } else if ($color == '#D6F2E6') {
            $colorName = 'Marblegreen';
        } else if ($color == '#BF8BFF') {
            $colorName = 'Violet';
        } else if ($color == '#6B4B36') {
            $colorName = 'Brown';
        } else if ($color == '#C0C0C0') {
            $colorName = 'Silver';
        } else if ($color == '#808080') {
            $colorName = 'Grey';
        } else if ($color == '#6CD2FA') {
            $colorName = 'Skyblue';
        } else if ($color == '#D09305') {
            $colorName = 'Orange';
        } else if ($color == '#13598B') {
            $colorName = 'Metallicblue';
        } else if ($color == '#9582BB') {
            $colorName = 'Metalicviolet';
        } else if ($color == '#A286F4') {
            $colorName = 'Purple';
        } else if ($color == '#62ADE6') {
            $colorName = 'Marbleblue';
        } else if ($color == '#80355C') {
            $colorName = 'Marblered';
        } else if ($color == '#2FCBD4') {
            $colorName = 'Avocadogreen';
        } else if ($color == '#FFA07A') {
            $colorName = 'Lightorange';
        } else if ($color == '#DDD3D1') {
            $colorName = 'Marblebeige';
        } else if ($color == '#F4C430') {
            $colorName = 'Saffron';
        } else if ($color == '#000000') {
            $colorName = 'Black';
        } else if ($color == '#D4AF37') {
            $colorName = 'Marblegold';
        } else if ($color == '#FFFFFF') {
            $colorName = 'Purewhite';
        } else if ($color == '#B4B4B8') {
            $colorName = 'Metallicsilver';
        } else if ($color == '#58C3C2') {
            $colorName = 'Marblegreen';
        } else if ($color == '#006A4E') {
            $colorName = 'Bottlegreen';
        } else if ($color == '#6F4E37') {
            $colorName = 'Coffee';
        } else if ($color == '#FFFDD0') {
            $colorName = 'Cream';
        } else if ($color == '#A9A9A9') {
            $colorName = 'Darkgrey';
        } else if ($color == '#C40233') {
            $colorName = 'Metalicred';
        } else if ($color == '#3D7764') {
            $colorName = 'Metalicgreen';
        } else if ($color == '#F8B700') {
            $colorName = 'Metalicyellow';
        }
        return $colorName;
    }
    public function getWaybillId()
    {
        try {
            $response = Http::asForm()->post('https://application.koombiyodelivery.lk/api/Waybils/users', [
                'apikey' => 'ORkohpssTIlGBjSqDYyb',
                'limit' => 1
            ]);

            if ($response->successful()) {
                $data = $response->json();

                Log::info('Waybill API Response', ['response' => $data]);

                // Check multiple possible response structures
                if (isset($data['data']) && is_array($data['data']) && count($data['data']) > 0) {
                    return $data['data'][0]['waybill_id'] ?? $data['data'][0]['barcode'] ?? $data['data'][0]['id'];
                } elseif (isset($data['waybill_id'])) {
                    return $data['waybill_id'];
                } elseif (isset($data['barcode'])) {
                    return $data['barcode'];
                } elseif (isset($data['waybills']) && is_array($data['waybills']) && count($data['waybills']) > 0) {
                    return $data['waybills'][0]['waybill_id'] ?? null;
                }

                Log::error('No waybill ID found in API response', ['response' => $data]);
                return null;
            } else {
                Log::error('Failed to get waybill ID - API error', [
                    'status' => $response->status(),
                    'response' => $response->body()
                ]);
                return null;
            }
        } catch (\Exception $e) {
            Log::error('Exception while getting waybill ID from Koombiyo API', [
                'error' => $e->getMessage()
            ]);
            return null;
        }
    }

    /**
     * Get district ID for Koombiyo API
     */
    private function getDistrictId($districtName)
    {
        // You may want to create a mapping table or cache this data
        $districtMapping = [
            'Colombo' => 1,
            'Gampaha' => 2,
            'Kalutara' => 3,
            'Kandy' => 4,
            'Matale' => 5,
            'Nuwara Eliya' => 6,
            'Galle' => 7,
            'Matara' => 8,
            'Hambantota' => 9,
            'Jaffna' => 10,
            'Kilinochchi' => 11,
            'Mannar' => 12,
            'Vavuniya' => 13,
            'Mullativu' => 14,
            'Batticaloa' => 15,
            'Ampara' => 16,
            'Trincomalee' => 17,
            'Kurunegala' => 18,
            'Puttalam' => 19,
            'Anuradhapura' => 20,
            'Polonnaruwa' => 21,
            'Badulla' => 22,
            'Moneragala' => 23,
            'Ratnapura' => 24,
            'Kegalle' => 25
        ];

        return $districtMapping[$districtName] ?? 1; // Default to Colombo
    }

    /**
     * Get city ID for Koombiyo API
     */
    private function getCityId($cityName, $districtName)
    {
        // This is a simplified version. You should ideally call the Cities API
        // or maintain a mapping table for accurate city IDs
        try {
            $districtId = $this->getDistrictId($districtName);
            $response = Http::asForm()->post('https://application.koombiyodelivery.lk/api/Cities/users', [
                'apikey' => 'ORkohpssTIlGBjSqDYyb',
                'district_id' => $districtId
            ]);

            if ($response->successful()) {
                $cities = $response->json();
                // Find matching city (adjust based on actual API response structure)
                foreach ($cities as $city) {
                    if (stripos($city['name'], $cityName) !== false) {
                        return $city['id'];
                    }
                }
            }
        } catch (\Exception $e) {
            Log::error('Failed to get city ID from Koombiyo API', ['error' => $e->getMessage()]);
        }

        return 1; // Default city ID
    }


    public function updatecolorstock($productid, $color, $qty)
    {
        try {
            $productcolor = Productcolor::where('product_id', $productid)->where('product_color', $color)->first();


            $productcolor->pc_qty = $productcolor->pc_qty - $qty;
            $productcolor->update();

        } catch (\Throwable $th) {
            DB::table('error_logs')->insert([
                'message' => $th->getMessage(),
                'file' => $th->getFile(),
                'line' => $th->getLine(),
                'trace' => $th->getTraceAsString(),
                'created_at' => now(),
            ]);
        }
    }
    private function remove_fromCart($productdata, $userid, $ordercolor)
    {
        try {
            $cart = Cart::where('productid', $productdata->id)->where('userid', $userid)->where('color', $ordercolor)->first();
            if ($cart) {
                $cart->delete();
                return response()->json([
                    'success' => true,
                    'message' => 'Product removed from cart successfully.',
                    'cart' => $cart
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => 'Product not found in cart.'
                ], 404);
            }
        } catch (\Throwable $th) {
            //throw $th;
        }
    }

    private function updateorder_qty($productdata, $orderqty)
    {
        try {
            if ($productdata) {
                $productData = Product::find($productdata->id);
                $productData->order += $orderqty;
                // Save the updated product data
                $productData->update();

                return response()->json([
                    'success' => true,
                    'message' => 'Product order quantity updated successfully.',
                    'product' => $productData
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => 'Product not found.'
                ], 404);
            }

        } catch (\Throwable $th) {
            DB::table('error_logs')->insert([
                'message' => $th->getMessage(),
                'file' => $th->getFile(),
                'line' => $th->getLine(),
                'trace' => $th->getTraceAsString(),
                'created_at' => now(),
            ]);
        }


    }
    public function fail()
    {
        return view('web.home.checkout.unsuccess', [
            'message' => 'Payment was cancelled.'
        ]);
    }
}
