<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use GuzzleHttp\Client;
use App\Models\Payment;
use App\Models\Orders;
use App\Models\CartItem;
use App\Models\Product;
use App\Models\Notification;
use App\Models\User;
use App\Models\ShippingDetails;
use App\Jobs\SendBuyerPurchaseMail;
use App\Jobs\SendSellerPurchaseMail;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Log;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        $this->middleware('auth');

        return view('home');
    }

    public function paymentCallbackAPI(Request $request)
    {
        // Handle the callback from Tap after the payment is completed
        // Sell Product Proceed with Online Payment
        $tapChargeId = $request->input('tap_id');

        if ($tapChargeId) {
            // $api_tap_company = env('API_TAP_COMPANY');
            $environment_data = getEnvironmentData();

            $client = new Client();
            $response = $client->get("https://api.tap.company/v2/charges/{$tapChargeId}", [
                'headers' => [
                    'Authorization' => $environment_data['API_TAP_COMPANY'],
                    'Content-Type' => 'application/json',
                ],
            ]);

            $responseBody = json_decode($response->getBody(), true);
            
            Log::channel('sell_product_payment')->info('Sell product payment callback called', [
                'sell_product_payment_details' => json_encode($responseBody)
            ]);

            if ($responseBody['status'] === 'CAPTURED') {
                $userId = $responseBody['metadata']['user_id'];

                $cart_data = CartItem::select('product_sku', 'quantity')->where('user_id', $userId)->get();

                $payment_data = new Payment;
                $payment_data->user_id = $userId;
                // $payment_data->product_sku = $responseBody['metadata']['product_sku'];
                $payment_data->order_id = $responseBody['order']['id'];
                $payment_data->amount = $responseBody['amount'];
                // $payment_data->payment_status = $responseBody['status'];
                $payment_data->payment_status = 'capture';
                $payment_data->payment_details = json_encode($responseBody);
                $payment_data->save();

                $buyerSkus = [];
                $sellerProductMap = [];

                foreach ($cart_data as $key => $cart) {
                    $product = Product::where('sku', $cart->product_sku)->firstOrFail();

                    $sellerId = $product->user_id;
                    $sellerProductMap[$sellerId][] = $product->sku;

                    // Store buyer's SKUs
                    $buyerSkus[] = $product->sku;

                    $commission_percentage = $product->commission_percentage;
                    $price = $product->price;

                    $wallet_amount = $price - (($price * $commission_percentage) / 100);

                    $seller = User::find($product->user_id);
                    $seller->pending_balance = $seller->pending_balance + $wallet_amount;
                    $seller->total_earnings = $seller->total_earnings + $wallet_amount;
                    $seller->save();

                    Orders::create([
                        'product_sku' => $cart->product_sku,
                        'quantity' => $cart->quantity,
                        'user_id' => $userId,
                        'shipping_id' => $responseBody['metadata']['shipping_id'],
                        'price' => $price,
                        'payment_id' => $payment_data->id
                    ]);

                    //$product->is_sell = 1;
                    $product->payment_done = 1;
                    $product->product_quantity = $product->product_quantity - $cart->quantity;
                    $product->save();

                    CartItem::where('user_id', $userId)->delete();
                }

                $buyer = User::find($userId);
                if ($buyer && $buyer->email) {
                    dispatch(new SendBuyerPurchaseMail($buyer, $buyerSkus));
                }

                // Buyer Notification
                $message = "Thank you for your purchase! You have successfully purchased the product. The seller will be notified and will process your order shortly.";
                Notification::create([
                    'user_id' => $userId,
                    'title' => "Product Purchase Confirmation",
                    'message' => $message,
                ]);
                
                pushNotification($userId, $message);

                // Seller-wise Notification
                foreach ($sellerProductMap as $sellerId => $productSkus) {
                    $seller_message = "You have received a new order for your product(s): " . implode(", ", $productSkus) . ". Please check your dashboard and proceed with shipping.";
                    Notification::create([
                        'user_id' => $sellerId,
                        'title' => "New Product Sold",
                        'message' => $seller_message,
                    ]);
                    
                    pushNotification($sellerId, $seller_message);

                    $seller = User::find($sellerId);
                    if ($seller && $seller->email) {
                        dispatch(new SendSellerPurchaseMail($seller, $productSkus));
                    }
                }

                return redirect('/payment-success')->with('success', 'Thank you for completing your secure online payment.');  // Success view
            } else {
                return redirect('/payment-failed');
            }
        } else {
            return redirect('/payment-failed');
        }
    }

    public function auctionPaymentCallbackAPI (Request $request)
    {
        // Handle the callback from Tap after the payment is completed
        // Auction Product Proceed with Online Payment

        $tapChargeId = $request->input('tap_id');

        if ($tapChargeId) {
            $environment_data = getEnvironmentData();

            $client = new Client();
            $response = $client->get("https://api.tap.company/v2/charges/{$tapChargeId}", [
                'headers' => [
                    'Authorization' => $environment_data['API_TAP_COMPANY'],
                    'Content-Type' => 'application/json',
                ],
            ]);

            $responseBody = json_decode($response->getBody(), true);

            Log::channel('auction_product_payment')->info('Auction product payment callback called', [
                'auction_product_payment_details' => json_encode($responseBody)
            ]);

            if ($responseBody['status'] === 'CAPTURED') {
                $payment_data = new Payment;
                $payment_data->user_id = $responseBody['metadata']['user_id'];
                // $payment_data->product_sku = $responseBody['metadata']['product_sku'];
                $payment_data->order_id = $responseBody['order']['id'];
                $payment_data->amount = $responseBody['amount'];
                $payment_data->payment_status = 'capture';
                //$payment_data->payment_status = $responseBody['status'];
                $payment_data->payment_details = json_encode($responseBody);
                $payment_data->save();

                $commission_percentage = $responseBody['metadata']['commission_percentage'];
                $price = $responseBody['amount'];

                $wallet_amount = $price - (($price * $commission_percentage) / 100);

                $seller = User::find($responseBody['metadata']['user_id']);
                $seller->pending_balance = $seller->pending_balance + $wallet_amount;
                $seller->total_earnings = $seller->total_earnings + $wallet_amount;
                $seller->save();

                Orders::create([
                    'product_sku' => $responseBody['metadata']['product_sku'],
                    'user_id' => $responseBody['metadata']['user_id'],
                    'shipping_id' => $responseBody['metadata']['shipping_id'],
                    'price' => $price,
                    'payment_id' => $payment_data->id
                ]);

                $product = Product::where('sku', $responseBody['metadata']['product_sku'])->firstOrFail();
                $product->is_sell = 1;
                $product->payment_done = 1;
                $product->save();

                // Buyer Notification
                $message = "Thank you for your purchase! You have successfully purchased the product. The seller will be notified and will process your order shortly.";
                Notification::create([
                    'user_id' => $responseBody['metadata']['user_id'],
                    'title' => "Product Purchase Confirmation",
                    'message' => $message,
                ]);
                
                pushNotification($responseBody['metadata']['user_id'], $message);
		
		        $seller_message = "You have received a new order for your product(s): $product->sku Please check your dashboard and proceed with shipping.";
                Notification::create([
                    'user_id' => $product->user_id,
                    'title' => "New Product Sold",
                    'message' => $seller_message
                ]);
                
                pushNotification($product->user_id, $seller_message);

                return redirect('/payment-success')->with('success', 'Thank you for completing your secure online payment.'); // Success view
            } else {
                return redirect('/payment-failed');
            }
        } else {
            return redirect('/payment-failed');
        }
    }

    public function paymentSuccess(Request $request)
    {
        return view('payment.success');
    }

    public function paymentFailed(Request $request)
    {
        return view('payment.failed');
    }

    public function selectPaymentOption($user_id, $product_sku){
        if (! request()->hasValidSignature()) {
            abort(403, 'Link expired or invalid');
        }

        $orders = Orders::select('payment_id')->where('user_id', $user_id)->where('product_sku', $product_sku)->first();
        
        if(isset($orders) && !empty($orders)){
            $payment = Payment::where('id', $orders->payment_id)->first();
            
            if (isset($payment) && $payment->payment_status === 'capture' || $payment->payment_status === 'cash_payment' || $payment->payment_status === 'paid_on_delivery') {
                return view('errors.payment-message', [
                    'message' => 'This payment link has already been used.',
                ]);
            }
        }

        return view('payment.select_payment_option', compact('user_id', 'product_sku'));
    }

    public function selectPaymentOptionForSellProduct($user_id, $shipping_id, $total_amount){
        return view('payment.select_payment_option', compact('user_id', 'shipping_id', 'total_amount'));
    }

    public function selectPaymentOptionSubmit(Request $request){
        if(isset($request->product_sku) && $request->product_sku != ''){
            // Auction Product Proceed with Online Payment
            if($request->payment_method == 'online_payment'){
                $product_sku = $request->product_sku;
                $user_id = $request->user_id;

                $orders = Orders::select('payment_id')->where('user_id', $user_id)->where('product_sku', $product_sku)->first();
                
                if(isset($orders) && !empty($orders)){
                    $payment = Payment::where('id', $orders->payment_id)->first();
                    
                    if (isset($payment) && $payment->payment_status === 'capture') {
                        return view('errors.payment-message', [
                            'message' => 'This payment link has already been used.',
                        ]);
                    }
                }
            
                return view('payment.payment_load',compact('user_id', 'product_sku'));
            } else {
                // Auction Product Proceed with Cash Payment
                $buyer_id = $request->user_id; 

                $user = User::select('first_name', 'last_name', 'email', 'country_id', 'phone')->where('id', $buyer_id)->first();
                $product = Product::select('sku', 'user_id', 'price', 'highest_bid_amount', 'commission_percentage', 'is_sell')->where('sku', $request->product_sku)->first();

                $country_details = getCountrydetailsById($user->country_id);
                $phone_code = $country_details->phone_code;

                $shipping_details = ShippingDetails::select('id', 'shipping_fee')->where(['product_sku' => $product->sku])->first();

                $amount = $product->highest_bid_amount != '' ? $product->highest_bid_amount + $shipping_details->shipping_fee : $product->price + $shipping_details->shipping_fee;

                $payment_data = new Payment;
                $payment_data->user_id = $buyer_id;
                $payment_data->order_id = 'ord_' . Str::random(22);
                $payment_data->amount = $amount;
                $payment_data->payment_status = 'pending';
                $payment_data->save();

                // Get commission data safely
                $commission_percentage = floatval($product->commission_percentage ?? 0);
                $price = floatval($amount ?? 0);

                // Calculate wallet amount
                $commission_amount = ($price * $commission_percentage) / 100;
                $wallet_amount = $price - $commission_amount;

                // Fetch seller
                $seller = User::select('id', 'pending_balance', 'total_earnings')->findOrFail($product->user_id);

                User::where('id', $product->user_id)->update([
                    'pending_balance' => $seller->pending_balance + $wallet_amount,
                    'total_earnings' => $seller->total_earnings + $wallet_amount
                ]);

                // Update seller balances
                // $seller->pending_balance = $seller->pending_balance + $wallet_amount;
                // $seller->total_earnings = $seller->total_earnings + $wallet_amount;
                // $seller->save();

                Orders::create([
                    'product_sku' => $request->product_sku,
                    'user_id' => $buyer_id,
                    'shipping_id' => $shipping_details->id,
                    'price' => $price,
                    'payment_id' => $payment_data->id
                ]);

                // Mark product sold
                Product::where('sku', $request->product_sku)->update(['is_sell' => 1]);

                // Buyer Notification
                $message = "Thank you for your purchase! You have successfully purchased the product. The seller will be notified and will process your order shortly.";
                Notification::create([
                    'user_id' => $buyer_id,
                    'title' => "Product Purchase Confirmation",
                    'message' => $message,
                ]);
                
                pushNotification($buyer_id, $message);
        
                // Seller Notification
                $seller_message = "You have received a new order for your product(s): $product->sku Please check your dashboard and proceed with shipping.";
                Notification::create([
                    'user_id' => $product->user_id,
                    'title' => "New Product Sold",
                    'message' => $seller_message
                ]);
                
                pushNotification($product->user_id, $seller_message);

                // return redirect('/payment/cash-payment-success'); // Success view
                return redirect('/payment-success')->with('success', 'Thank you for your purchase! You have successfully purchased the product. The seller will be notified and will process your order shortly.');
            }
        } else {
            // Sell Product Proceed with Online Payment
            if($request->payment_method == 'online_payment'){
                // Proceed with online payment
                $user_id = $request->user_id;
                $user = User::find($user_id);

                $country_details = getCountrydetailsById($user->country_id);
                $phone_code = $country_details->phone_code;

                $client = new Client();
                // Prepare the payment data
                $paymentData = [
                    'amount' => $request->total_amount,
                    'currency' => 'BHD', 
                    //'currency' => $user->user_currancy,// Change to your currency as needed
                    'description' => 'Payment for Order',
                    'customer' => [
                        'first_name' => $user->first_name.' '.$user->last_name,
                        'email' => $user->email,
                    ],
                    'metadata' => [ // Using metadata to store additional information
                        'user_id' => $user->id,
                        'phone' => $user->phone,
                        'phone_code' => $phone_code,
                        'shipping_id' => $request->shipping_id
                    ],
                    'source' => [
                        'id' => 'src_all', // Use 'src_all' to allow all payment methods
                    ],
                    'redirect' => [
                        'url' => route('payment.payment_callback_api'), // Callback URL
                    ],
                ];

                try {
                    // Send the request to Tap's API
                    $environment_data = getEnvironmentData();
                    $response = $client->post('https://api.tap.company/v2/charges', [
                        'headers' => [
                            'Authorization' => $environment_data['API_TAP_COMPANY'],
                            'Content-Type' => 'application/json',
                        ],
                        'json' => $paymentData,
                    ]);

                    $responseBody = json_decode($response->getBody(), true);

                    $cart_data = CartItem::select('cart_items.product_sku', 'cart_items.quantity', 'products.product_quantity as stock_qty')
                        ->join('products', 'products.sku', '=', 'cart_items.product_sku')
                        ->where('cart_items.user_id', $user->id)
                        ->get();

                    // Example check — filter only products where cart qty > stock qty (out of stock / insufficient)
                    $invalid_products = $cart_data->filter(function ($item) {
                        return $item->quantity > $item->stock_qty;
                    });

                    // Check condition
                    if ($invalid_products->isEmpty()) {
                        // Stock is fine
                        if (isset($responseBody['transaction']['url'])) {
                            $data['status'] = true;
                            $data['url'] = $responseBody['transaction']['url'];
                        } else {
                            $data['status'] = false;
                            $data['url'] = null;
                        }
                    } else {
                        // Some products have insufficient stock
                        $data['status'] = false;
                        $data['url'] = null;
                    }
                } catch (\Exception $e) {
                    $data['status'] = false;
                }

                return redirect($data['url']);
            } else if($request->payment_method == 'cash_payment'){
                // Sell Product Proceed with Cash Payment

                $userId      = $request->user_id;
                $shippingId  = $request->shipping_id;
                $totalAmount = $request->total_amount;

                $cart_data = CartItem::select('product_sku', 'quantity')->where('user_id', $userId)->get();

                $payment_data = new Payment;
                $payment_data->user_id = $userId;
                $payment_data->order_id = 'ord_' . Str::random(22);
                $payment_data->amount = $totalAmount;
                $payment_data->payment_status = 'pending';
                $payment_data->save();

                $buyerSkus = [];
                $sellerProductMap = [];

                foreach ($cart_data as $key => $cart) {
                    $product = Product::where('sku', $cart->product_sku)->firstOrFail();

                    $sellerId = $product->user_id;
                    $sellerProductMap[$sellerId][] = $product->sku;

                    // Store buyer's SKUs
                    $buyerSkus[] = $product->sku;

                    $commission_percentage = $product->commission_percentage;
                    $price = $product->price;

                    $wallet_amount = $price - (($price * $commission_percentage) / 100);

                    $seller = User::find($product->user_id);
                    $seller->pending_balance = $seller->pending_balance + $wallet_amount;
                    $seller->total_earnings = $seller->total_earnings + $wallet_amount;
                    $seller->save();

                    Orders::create([
                        'product_sku' => $cart->product_sku,
                        'quantity' => $cart->quantity,
                        'user_id' => $userId,
                        'shipping_id' => $shippingId,
                        'price' => $price,
                        'payment_id' => $payment_data->id
                    ]);

                    $product->product_quantity = $product->product_quantity - $cart->quantity;
                    $product->save();

                    CartItem::where('user_id', $userId)->delete();
                }

                $data['status'] = true;

                $buyer = User::find($userId);
                if ($buyer && $buyer->email) {
                    dispatch(new SendBuyerPurchaseMail($buyer, $buyerSkus));
                }

                // Buyer Notification
                $message = "Thank you for your purchase! You have successfully purchased the product. The seller will be notified and will process your order shortly.";
                Notification::create([
                    'user_id' => $userId,
                    'title' => "Product Purchase Confirmation",
                    'message' => $message,
                ]);
                
                pushNotification($userId, $message);

                // Seller-wise Notification
                foreach ($sellerProductMap as $sellerId => $productSkus) {
                    $seller_message = "You have received a new order for your product(s): " . implode(", ", $productSkus) . ". Please check your dashboard and proceed with shipping.";
                    Notification::create([
                        'user_id' => $sellerId,
                        'title' => "New Product Sold",
                        'message' => $seller_message,
                    ]);
                    
                    pushNotification($sellerId, $seller_message);

                    $seller = User::find($sellerId);
                    if ($seller && $seller->email) {
                        dispatch(new SendSellerPurchaseMail($seller, $productSkus));
                    }
                }

                // return redirect('/payment/cash-payment-success'); // Success view
                return redirect('/payment-success')->with('success', 'Thank you for your purchase! You have successfully purchased the product. The seller will be notified and will process your order shortly.');
            }
        }
    }

    public function cashPaymentSuccess(Request $request)
    {
        return view('payment.cash_payment_success');
    }
}