<?php

namespace App\Http\Controllers;

use App\Mail\Ordercopytransfer;
use App\Models\Productcolor;
use Illuminate\Http\Request;
use App\Services\PaymentService;
use App\Models\Order;
use App\Models\Product;
use App\Models\Cart;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Auth;
use App\Models\Area;
use App\Models\Bulkorder;
use App\Models\Shippingzone;
use App\Models\Userdata;
use App\Mail\OrderConfirmed;
use App\Models\Systemlog;
use Carbon\Carbon;
use Illuminate\Routing\Controller;
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 PaymentController extends Controller
{
    use VerifiesPaymentTotal;
    protected $paymentService;

    public function __construct(PaymentService $paymentService)
    {
        $this->paymentService = $paymentService;
    }


    public function createSession(Request $request)
    {
        $orderDetails = $request->all();


        // Security: Recalculate amount on server
        try {
            $verifiedAmount = $this->verifyTotalAmount($orderDetails);
            $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 response()->json(['error' => 'Invalid order data: ' . $e->getMessage()], 400);
        }

        $orderId = $this->generateUniqueOrderId();
        $transactionId = Str::uuid()->toString();

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

        session(['order_details' => $request->all()]);
        session(['orderId' => $orderId]);
        session(['transactionId' => $transactionId]);
        $response = $this->paymentService->createPaymentSession($request, $orderId, $transactionId);
       
        if ($response instanceof \Illuminate\Http\JsonResponse) {
            return $response;
        }

        try {
            // Get the response body
            $responseBody = $response->getBody()->getContents();

            $params = json_decode($responseBody, true);
            // Access the 'result' parameter
            $result = $params['result'] ?? null;
          
            if ($result === 'SUCCESS') {
                // Prepare the session response data
                $sessionResponse = [
                    'session.id' => $params['session']['id'] ?? null,
                    'session.updateStatus' => $params['session']['updateStatus'] ?? null,
                    'session.version' => $params['session']['version'] ?? null,
                    'successIndicator' => $params['successIndicator'] ?? null,
                    'result' => $params['result'] ?? null,
                ];

                // Update PendingOrder with the successIndicator for verification
                $pendingOrderModel = PendingOrder::where('order_id', $orderId)->first();
             
                if ($pendingOrderModel) {
                    $payload = $pendingOrderModel->payload;
                    $payload['expected_success_indicator'] = $sessionResponse['successIndicator'];
                    $pendingOrderModel->update(['payload' => $payload]);
                }

                session(['expected_success_indicator' => $sessionResponse['successIndicator']]);
                
                return response()->json([
                    'session' => [
                        'id' => $sessionResponse['session.id'],
                        'session.id' => $sessionResponse['session.id'],
                        'updateStatus' => $sessionResponse['session.updateStatus'],
                        'version' => $sessionResponse['session.version']
                    ],
                    'successIndicator' => $sessionResponse['successIndicator'],
                    'result' => $sessionResponse['result']
                ]);
            } else {
                return response()->json(['error' => 'Payment session creation failed: ' . ($params['result'] ?? 'Unknown error')], 400);
            }
        } catch (\Exception $e) {
            // Handle exceptions and return an error response
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }

    function generateUniqueOrderId()
    {
        // Get the current timestamp in milliseconds
        $timestamp = round(microtime(true) * 1000);

        // Generate a random number between 1000 and 9999
        $randomNumber = rand(1000, 9999);

        // Combine the timestamp and random number to create a unique numeric order ID
        return $timestamp . $randomNumber;
    }

public function next_page(Request $request)
{
    $sessionId = $request->query('session_id');

    return view('web.home.payment.payment', [
        'session_id' => $sessionId
    ]);
}



    public function handleCallback(Request $request)
    {
        $resultIndicator = $request->query('resultIndicator');
        $sessionVersion = $request->query('sessionVersion');
        $orderId = $request->query('order_id');

        // Attempt to recover order data from database if session is lost
        $pendingOrder = null;
        if ($orderId) {
            $pendingOrder = PendingOrder::where('order_id', $orderId)->first();
        }

        // Verify the response
        if ($this->isValidResponse($resultIndicator, $sessionVersion)) {
            if ($this->isPaymentSuccessful($resultIndicator, $pendingOrder)) {

                // Construct the data structure expected by save_data
                if ($pendingOrder) {
                    $sessionData = [
                        'order_details' => $pendingOrder->payload,
                        'orderId' => $pendingOrder->order_id
                    ];
                } else {
                    $sessionData = $request->session()->all();
                }

                $this->save_data($sessionData);

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

                return redirect()->route('american.plastic.web.order.confirmed');
            } else {
                // Payment failed
                session()->flash('error', 'Your transaction was unsuccessful. Please try again.');
                if ($pendingOrder) {
                    $pendingOrder->update(['status' => 'failed']);
                }
            }
        } else {
            // Invalid response
            return response()->json(['message' => 'Invalid response'], 400);
        }
    }

    public function save_data($sessionData)
    {
        $newOrderIds = []; // Array to store the new order IDs
        $orderItems = []; // Array to store order items for email
        $totalOrderAmount = 0;
        $totalServiceFee = 0;
        $totalTaxAmountSum = 0;

        try {
            $user = Auth::user();
            $userid = $user->id ?? 'Guest';

            $appliedPointsTotal = 0;
            if ($user && !empty($sessionData['order_details']['use_points'])) {
                try {
                    $verifiedAmount = $this->verifyTotalAmount($sessionData['order_details']);
                    $appliedPointsTotal = min($user->recycling_points, $verifiedAmount);
                } catch (\Exception $e) {
                    Log::error('Error calculating applied points: ' . $e->getMessage());
                }
            }

            // Extract customer details
            $customer_firstname = $sessionData['order_details']['cus_firstname'];
            $customer_lastname = $sessionData['order_details']['cus_lastname'];
            $customerphone = $sessionData['order_details']['cus_phone'];
            $customeremail = $sessionData['order_details']['cus_email'];
            $company = $sessionData['order_details']['cus_company'];
            $addressone = $sessionData['order_details']['cus_address_one'];
            $addresstwo = $sessionData['order_details']['cus_address_two'];
            $city = $sessionData['order_details']['cus_city'];
            $district = $sessionData['order_details']['cus_district'];
            $postalcode = $sessionData['order_details']['cus_postcode'];
            $ordernote = $sessionData['order_details']['order_note'];
            $shippingprice = $sessionData['order_details']['shipping_price'];
            $amount = $sessionData['order_details']['amount'];
            $weight = $sessionData['order_details']['totalweight'];

            // Get shipping zone data
            $city_name = $sessionData['order_details']['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];
            }

            // Split the comma-separated strings into arrays
            $productIds = explode(',', $sessionData['order_details']['productid']);
            $orderColors = explode(',', $sessionData['order_details']['order_color']);
            $orderQuantities = explode(',', $sessionData['order_details']['order_qty']);

            // Validate arrays
            if (count($productIds) === 0 || count($productIds) !== count($orderColors) || count($productIds) !== count($orderQuantities)) {
                throw new \Exception('Product details mismatch');
            }


            $count = count($productIds);

            // Use orderId from recovered data if available, else from session
            $baseOrderId = $sessionData['orderId'] ?? session('orderId');

            // Calculate shipping total using server-side data directly
            $totalWeightForShipping = 0;
            foreach ($productIds as $index => $productId) {
                $qty = (int) ($orderQuantities[$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;
            $baseServiceFee = $count > 0 ? ($shippingprice / $count) : 0;

            // Handle Voucher Redemption
            if (isset($sessionData['order_details']['voucher_code'])) {
                $voucherCode = $sessionData['order_details']['voucher_code'];
                $voucher = \App\Models\Voucher::where('code', $voucherCode)->first();
                if ($voucher && $voucher->isValid()) {
                    $voucher->update([
                        'redeemed_by' => $userid != 'Guest' ? $userid : null,
                        'redeemed_at' => now()
                    ]);
                }
            }

            foreach ($productIds as $index => $productId) {
                $ordercolor = $orderColors[$index] ?? null;
                $orderqty = (int) ($orderQuantities[$index] ?? 1);

                // Skip if quantity is invalid
                if ($orderqty <= 0) {
                    continue;
                }

                // Generate unique order ID
                $uniquePart = substr(uniqid(), -4);
                $newOrderId = 'BNK-' . $baseOrderId . '-' . $uniquePart;

                // Get product data with lock to prevent race conditions
                $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.weight',
                        'product.cutted_price',
                        'product_color.price',
                        'product_color.product_color'
                    )
                    ->where('product.id', $productId)
                    ->where('product_color.product_color', $ordercolor)
                    ->lockForUpdate()
                    ->first();

                if (!$productdata) {
                    continue; // Skip if product not found
                }

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

                // Calculate prices and weights
                $unitprice = $productdata->price ?? $productdata->product_price;
                $totalPrice = $unitprice * $orderqty;
                $productWeight = $productdata->weight * $orderqty;
                $service_fee = $baseServiceFee;
                $finalamount = $totalPrice + $service_fee;

                // Create and save order
                $order = new Order();
                $order->userid = $userid;
                $order->zone_id = $zonedata->id;
                $order->order_id = $newOrderId;
                $order->product_id = $productId;
                $order->first_name = $customer_firstname;
                $order->last_name = $customer_lastname;
                $order->color = $ordercolor;
                $order->quantity = $orderqty;
                $order->telephone = $customerphone;
                $order->company = $company;
                $order->email = $customeremail;
                $order->address_1 = $addressone;
                $order->address_2 = $addresstwo;
                $order->city = $city;
                $order->district = $district;
                $order->postcode = $postalcode;
                $order->ordernote = $ordernote;
                $order->payment_method = 'visa';
                $order->processing = 1;
                $order->service_fee = $service_fee;
                $order->total = $totalPrice;
                $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 * $orderqty * $lineTaxPercentage) / 100, 2);
                }
                $order->tax_amount = $lineTaxAmount;
                $order->tax_percentage = $lineTaxPercentage;

                $order->voucher_code = $sessionData['order_details']['voucher_code'] ?? null;
                if ($index === 0) {
                    $order->discount_amount = $sessionData['order_details']['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;

                // Process in transaction
                DB::transaction(function () use ($order, $productdata, $orderqty, $user, $productId, $ordercolor) {
                    $order->save();
                    $this->updateqty($productdata, $orderqty);
                    $this->updateorder_qty($productdata, $orderqty);
                    $this->updatecolorstock($productId, $ordercolor, $orderqty);
                    if ($user) {
                        $product = Product::find($productId);
                        $this->remove_fromCart($product, $user->id, $ordercolor);
                    }
                });

                // Store order information


                $newOrderIds[] = $order->id;
                $newOrderIdsNO[] = $order->order_id;
                $totalOrderAmount += $totalPrice;
                $totalServiceFee += $service_fee;
                $totalTaxAmountSum += $lineTaxAmount;


                $productDetails[] = [
                    'name' => $productdata->product_name,
                    'color' => $ordercolor,
                    'quantity' => $orderqty,
                    'price' => $productdata->price ?? $productdata->product_price
                ];

                $orderItems[] = [
                    'product_id' => $productId,
                    'product_name' => $productdata->product_name,
                    'color' => $ordercolor,
                    'quantity' => $orderqty,
                    'unit_price' => $productdata->price ?? $productdata->product_price,
                    'total_price' => $totalPrice,
                    'service_fee' => $service_fee,
                    'final_amount' => $finalamount,
                    'tax_amount' => $lineTaxAmount,
                    'cutted_price' => $productdata->cutted_price,
                    'settextcolor' => $this->setcolor($ordercolor),
                ];
            }

            $taxPercentage = (Auth::user() && Auth::user()->is_corporate) ? (float) \App\Models\SystemSetting::get('corporate_tax_percentage', 18.00) : 0;
            $taxAmount = $totalTaxAmountSum;

            // Send email confirmation after all orders are processed
            if (count($orderItems) > 0) {
                $orderdate = Carbon::today();

                $discountAmount = $sessionData['order_details']['discount_amount'] ?? 0;

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

                // Generate Invoice
                $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 + $taxAmount - $discountAmount - $appliedPointsTotal);

                $invoice = \App\Models\Invoice::create([
                    'invoice_number' => $invoiceNumber,
                    'order_id' => 'ORDER-' . implode('-', $newOrderIds),
                    'customer_name' => $customer_firstname . ' ' . $customer_lastname,
                    'customer_email' => $customeremail,
                    'billing_address' => $addressone . ', ' . ($city_name ?? $addressone),
                    'invoice_date' => now(),
                    'subtotal' => $invoiceSubtotal,
                    'tax_percentage' => $taxPercentage,
                    'tax_amount' => $taxAmount,
                    'shipping_cost' => $totalServiceFee,
                    'discount_amount' => $discountAmount,
                    'total_amount' => $invoiceTotal,
                    'status' => 'pending',
                    'points_applied' => $appliedPointsTotal,
                    'points_used_flag' => $appliedPointsTotal > 0 ? 1 : 0,
                ]);

                try {
                    // Customer email
                    $this->mailtoCustomer(
                        $customeremail,
                        $customer_firstname,
                        $newOrderIdsNO,
                        $orderItems,
                        $totalOrderAmount,
                        $totalServiceFee,
                        $customerphone,
                        $addressone,
                        $addresstwo,
                        $orderdate,
                        $taxAmount ?? 0,
                        $taxPercentage ?? 0,
                        $discountAmount,
                        $invoice,
                        $appliedPointsTotal
                    );

                    $this->copyTransfer(
                        $customeremail,
                        $customer_firstname,
                        $newOrderIds,
                        $orderItems,
                        $totalOrderAmount,
                        $totalServiceFee,
                        $customerphone,
                        $addressone,
                        $addresstwo,
                        $orderdate,
                        $taxAmount ?? 0,
                        $taxPercentage ?? 0,
                        $discountAmount,
                        $appliedPointsTotal
                    );
                    // Send to Koombiyo using the first order for customer details

                } catch (\Exception $e) {
                    // Log email error
                    Systemlog::create([
                        'message' => json_encode([
                            'error_type' => 'email_failed',
                            'customer_name' => $customer_firstname,
                            'order_ids' => $newOrderIds,
                            'total_amount' => $totalOrderAmount,
                            'service_fee' => $totalServiceFee,
                            'customer_phone' => $customerphone,
                            'customer_address' => $addressone,
                            'order_date' => $orderdate,
                            'customer_email' => $customeremail,
                            'error_message' => $e->getMessage(),
                            'timestamp' => now()->toDateTimeString()
                        ], JSON_PRETTY_PRINT)
                    ]);
                }
                $this->sendToKoombiyo(
                    $customer_firstname,
                    $customerphone,
                    trim($addressone . ' ' . $addresstwo),
                    $city,
                    $district,
                    $postalcode,
                    $ordernote ?? 'Order from website',
                    $productDetails,
                    $totalOrderAmount + $totalServiceFee + $taxAmount - $discountAmount ?? 0,
                    $newOrderIds
                );
            }



            return response()->json(['code' => 'true', 'msg' => 'Order confirmed', 'orderIds' => $newOrderIds]);
        } catch (\Throwable $th) {
            DB::table('error_logs')->insert([
                'message' => $th->getMessage(),
                'file' => $th->getFile(),
                'line' => $th->getLine(),
                'trace' => $th->getTraceAsString(),
                'created_at' => now(),
            ]);

            return response()->json(['code' => 'false', 'msg' => $th->getMessage()]);
        }
    }


    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([

                    '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 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 = [
            'Ampara' => 1,
            'Anuradhapura' => 2,
            'Badulla' => 3,
            'Batticaloa' => 4,
            'Colombo' => 5,
            'Galle' => 6,
            'Gampaha' => 7,
            'Hambantota' => 8,
            'Jaffna' => 9,
            'Kalutara' => 10,
            'Kandy' => 11,
            'Kegalle' => 12,
            'Kilinochchi' => 13,
            'Kurunegala' => 14,
            'Mannar' => 15,
            'Matale' => 16,
            'Matara' => 17,
            'Moneragala' => 18,
            'Mullativu' => 19,
            'Mullaitivu' => 19,
            'Nuwara Eliya' => 20,
            'Polonnaruwa' => 21,
            'Puttalam' => 22,
            'Ratnapura' => 23,
            'Trincomalee' => 24,
            'Vavuniya' => 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
    }

    /**
     * Generate order description from order data
     */

    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 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'];
            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 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(),
            ]);
        }
    }
    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)
    {
        if ($productdata) {
            $productData = Product::find($productdata->id);
            $productData->qty -= $orderqty;
            // Save the updated product data
            $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);
        }
    }

    private function remove_fromCart($productdata, $userid, $ordercolor)
    {
        $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);
        }
    }

    private function updateorder_qty($productdata, $orderqty)
    {

        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);
        }
    }


    private function isValidResponse($resultIndicator, $sessionVersion)
    {

        return !empty($resultIndicator) && !empty($sessionVersion);
    }

    private function isPaymentSuccessful($resultIndicator, $pendingOrder = null)
    {
        $expectedSuccessIndicator = null;

        if ($pendingOrder && isset($pendingOrder->payload['expected_success_indicator'])) {
            $expectedSuccessIndicator = $pendingOrder->payload['expected_success_indicator'];
        } else {
            $expectedSuccessIndicator = session('expected_success_indicator');
        }

        // Compare the received resultIndicator with the expected one
        return !empty($expectedSuccessIndicator) && $resultIndicator === $expectedSuccessIndicator;
    }
}
